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
|
|---|---|---|---|---|---|
0c5997b20245bf1ee179ca09893947d5f82a4620
|
Valadoc
|
gir-importer: markdown: resolve internal links
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/doclets/gtkdoc/commentconverter.vala b/src/doclets/gtkdoc/commentconverter.vala
index 91ab7591cb..cdf85ea6a0 100644
--- a/src/doclets/gtkdoc/commentconverter.vala
+++ b/src/doclets/gtkdoc/commentconverter.vala
@@ -92,7 +92,7 @@ public class Gtkdoc.CommentConverter : ContentVisitor {
current_builder.append (link.name);
}
}
-
+
public override void visit_link (Link link) {
current_builder.append_printf ("<ulink url=\"%s\">", link.url);
link.accept_children (this);
@@ -104,15 +104,15 @@ public class Gtkdoc.CommentConverter : ContentVisitor {
// If the symbol is a method and it doesn't have a constructor, fall back to linking to the class
if (sl.symbol is Method && ((Method) sl.symbol).is_constructor &&
((Method) sl.symbol).parent is Class && ((Class) ((Method) sl.symbol).parent).is_abstract) {
- current_builder.append (get_docbook_link (((Method) sl.symbol).parent, is_dbus) ?? sl.label);
+ current_builder.append (get_docbook_link (((Method) sl.symbol).parent, is_dbus) ?? sl.given_symbol_name);
} else {
- current_builder.append (get_docbook_link (sl.symbol, is_dbus) ?? sl.label);
+ current_builder.append (get_docbook_link (sl.symbol, is_dbus) ?? sl.given_symbol_name);
}
} else {
- current_builder.append (sl.label);
+ current_builder.append (sl.given_symbol_name);
}
}
-
+
public override void visit_list (Content.List list) {
string tag = "orderedlist";
switch (list.bullet) {
diff --git a/src/libvaladoc/Makefile.am b/src/libvaladoc/Makefile.am
index 84cebd817f..a4870eeb5c 100644
--- a/src/libvaladoc/Makefile.am
+++ b/src/libvaladoc/Makefile.am
@@ -60,6 +60,7 @@ libvaladoc_la_VALASOURCES = \
importer/valadocdocumentationimporter.vala \
importer/valadocdocumentationimporterscanner.vala \
importer/girdocumentationimporter.vala \
+ importer/internalidregistrar.vala \
api/symbolaccessibility.vala \
api/sourcecomment.vala \
api/girsourcecomment.vala \
diff --git a/src/libvaladoc/content/inlinecontent.vala b/src/libvaladoc/content/inlinecontent.vala
index aca48c20c4..f67ee4e1af 100644
--- a/src/libvaladoc/content/inlinecontent.vala
+++ b/src/libvaladoc/content/inlinecontent.vala
@@ -64,5 +64,12 @@ public abstract class Valadoc.Content.InlineContent : ContentElement {
return true;
}
+
+ internal void replace_node (Inline old, Inline replacement) {
+ int index = _content.index_of (old);
+ assert (index >= 0);
+
+ _content.set (index, replacement);
+ }
}
diff --git a/src/libvaladoc/content/link.vala b/src/libvaladoc/content/link.vala
index 6f3bd709a1..2dad00a665 100644
--- a/src/libvaladoc/content/link.vala
+++ b/src/libvaladoc/content/link.vala
@@ -1,7 +1,7 @@
/* link.vala
*
* Copyright (C) 2008-2009 Didier Villevalois
- * Copyright (C) 2008-2012 Florian Brosch
+ * Copyright (C) 2008-2014 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -26,10 +26,19 @@ using Gee;
public class Valadoc.Content.Link : InlineContent, Inline {
public string url {
- get;
set;
+ get;
+ }
+
+ /**
+ * Used by importers to transform internal URLs
+ */
+ public Importer.InternalIdRegistrar id_registrar {
+ internal set;
+ get;
}
+
internal Link () {
base ();
}
@@ -40,8 +49,45 @@ public class Valadoc.Content.Link : InlineContent, Inline {
public override void check (Api.Tree api_root, Api.Node container, string file_path,
ErrorReporter reporter, Settings settings)
{
- base.check (api_root, container, file_path, reporter, settings);
+
+ // Internal gktdoc-id? (gir-importer)
+ if (id_registrar != null) {
+ Api.Node? node = id_registrar.map_symbol_id (url);
+ if (node != null) {
+ InlineContent _parent = parent as InlineContent;
+ assert (_parent != null);
+
+ SymbolLink replacement = new SymbolLink (node);
+ replacement.content.add_all (content);
+
+ replacement.check (api_root, container, file_path, reporter, settings);
+ _parent.replace_node (this, replacement);
+ return ;
+ }
+
+
+ string _url = id_registrar.map_url_id (url);
+ if (_url == null) {
+ string node_segment = (container is Api.Package)? "" : container.get_full_name () + ": ";
+ reporter.simple_warning ("%s: %s[[: warning: unknown imported internal id `%s'", file_path, node_segment, url);
+
+ InlineContent _parent = parent as InlineContent;
+ assert (_parent != null);
+
+ Run replacement = new Run (Run.Style.ITALIC);
+ replacement.content.add_all (content);
+ replacement.check (api_root, container, file_path, reporter, settings);
+
+ _parent.replace_node (this, replacement);
+ return ;
+ }
+
+ url = _url;
+ }
+
+
//TODO: check url
+ base.check (api_root, container, file_path, reporter, settings);
}
public override void accept (ContentVisitor visitor) {
@@ -54,6 +100,7 @@ public class Valadoc.Content.Link : InlineContent, Inline {
public override ContentElement copy (ContentElement? new_parent = null) {
Link link = new Link ();
+ link.id_registrar = id_registrar;
link.parent = new_parent;
link.url = url;
diff --git a/src/libvaladoc/content/symbollink.vala b/src/libvaladoc/content/symbollink.vala
index 0f49b74302..70e5284958 100644
--- a/src/libvaladoc/content/symbollink.vala
+++ b/src/libvaladoc/content/symbollink.vala
@@ -1,7 +1,7 @@
/* symbollink.vala
*
* Copyright (C) 2008-2009 Didier Villevalois
- * Copyright (C) 2008-2012 Florian Brosch
+ * Copyright (C) 2008-2014 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -24,21 +24,21 @@
using Gee;
-public class Valadoc.Content.SymbolLink : ContentElement, Inline {
+public class Valadoc.Content.SymbolLink : InlineContent, Inline {
public Api.Node symbol {
get;
set;
}
- public string label {
+ public string given_symbol_name {
get;
set;
}
- internal SymbolLink (Api.Node? symbol = null, string? label = null) {
+ internal SymbolLink (Api.Node? symbol = null, string? given_symbol_name = null) {
base ();
_symbol = symbol;
- _label = label;
+ _given_symbol_name = given_symbol_name;
}
public override void configure (Settings settings, ResourceLocator locator) {
@@ -58,8 +58,14 @@ public class Valadoc.Content.SymbolLink : ContentElement, Inline {
}
public override ContentElement copy (ContentElement? new_parent = null) {
- SymbolLink link = new SymbolLink (symbol, label);
+ SymbolLink link = new SymbolLink (symbol, _given_symbol_name);
link.parent = new_parent;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (link) as Inline;
+ link.content.add (copy);
+ }
+
return link;
}
}
diff --git a/src/libvaladoc/documentation/documentationparser.vala b/src/libvaladoc/documentation/documentationparser.vala
index 3dde0b886d..4ca6aef2b6 100644
--- a/src/libvaladoc/documentation/documentationparser.vala
+++ b/src/libvaladoc/documentation/documentationparser.vala
@@ -27,7 +27,9 @@ using Gee;
public class Valadoc.DocumentationParser : Object, ResourceLocator {
- private HashMap<Api.SourceFile, GirMetaData> metadata = new HashMap<Api.SourceFile, GirMetaData> ();
+ private HashMap<Api.SourceFile, GirMetaData> metadata;
+ private Importer.InternalIdRegistrar id_registrar;
+
public DocumentationParser (Settings settings, ErrorReporter reporter,
Api.Tree tree, ModuleLoader modules)
@@ -50,6 +52,10 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
gtkdoc_parser = new Gtkdoc.Parser (settings, reporter, tree, modules);
gtkdoc_markdown_parser = new Gtkdoc.MarkdownParser (settings, reporter, tree, modules);
+
+ metadata = new HashMap<Api.SourceFile, GirMetaData> ();
+ id_registrar = new Importer.InternalIdRegistrar ();
+
init_valadoc_rules ();
}
@@ -79,7 +85,7 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
Comment doc_comment = gtkdoc_parser.parse (element, gir_comment, metadata);
return doc_comment;
} else {
- Comment doc_comment = gtkdoc_markdown_parser.parse (element, gir_comment, metadata);
+ Comment doc_comment = gtkdoc_markdown_parser.parse (element, gir_comment, metadata, id_registrar);
return doc_comment;
}
} else {
@@ -166,6 +172,10 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
}
metadata = new GirMetaData (gir_comment.file.relative_path, _settings.metadata_directories, _reporter);
+ if (metadata.index_sgml != null) {
+ id_registrar.read_index_sgml_file (metadata.index_sgml, _reporter);
+ }
+
this.metadata.set (gir_comment.file, metadata);
return metadata;
}
diff --git a/src/libvaladoc/documentation/girmetadata.vala b/src/libvaladoc/documentation/girmetadata.vala
index 41e2be8622..1a9909712a 100644
--- a/src/libvaladoc/documentation/girmetadata.vala
+++ b/src/libvaladoc/documentation/girmetadata.vala
@@ -1,6 +1,6 @@
/* girmetadata.vala
*
- * Copyright (C) 2012 Florian Brosch
+ * Copyright (C) 2012-2014 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,6 +20,9 @@
* Brosch Florian <[email protected]>
*/
+using Gee;
+
+
/**
* Metadata reader for GIR files
*/
@@ -27,7 +30,9 @@ public class Valadoc.GirMetaData : Object {
private string? metadata_path = null;
private string? resource_dir = null;
+
public bool is_docbook { private set; get; default = false; }
+ public string index_sgml { private set; get; default = null; }
/**
@@ -89,6 +94,10 @@ public class Valadoc.GirMetaData : Object {
this.is_docbook = key_file.get_boolean ("General", "is_docbook");
break;
+ case "index_sgml":
+ this.index_sgml = key_file.get_string ("General", "index_sgml");
+ break;
+
default:
reporter.simple_warning ("%s: warning: Unknown key 'General.%s'", metadata_path, key);
break;
@@ -134,6 +143,9 @@ public class Valadoc.GirMetaData : Object {
} catch (KeyFileError e) {
reporter.simple_error ("%s: error: %s", metadata_path, e.message);
}
+
+
+ // Load internal link lut:
}
}
diff --git a/src/libvaladoc/documentation/gtkdocmarkdownparser.vala b/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
index 721572d1dc..53dfe18aea 100644
--- a/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
+++ b/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
@@ -40,6 +40,7 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
private Valadoc.Token preserved_token = null;
private Regex regex_source_lang;
+ private Importer.InternalIdRegistrar id_registrar;
private GirMetaData metadata;
private Api.GirSourceComment gir_comment;
private Api.Node element;
@@ -253,6 +254,7 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
.set_reduce (() => {
Link url = _factory.create_link ();
url.url = pop_preserved_link ();
+ url.id_registrar = id_registrar;
Run label = (Run) peek ();
url.content.add_all (label.content);
@@ -517,8 +519,8 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
}),
run,
Rule.option ({
- Valadoc.TokenType.MARKDOWN_HEADLINE_HASH.action (() => {
- // TODO
+ Valadoc.TokenType.MARKDOWN_HEADLINE_HASH.action ((token) => {
+ id_registrar.register_symbol (token.value, element);
})
}),
Valadoc.TokenType.MARKDOWN_HEADLINE_END
@@ -618,12 +620,12 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
comment.content.insert (1, note);
}
- public Comment? parse (Api.Node element, Api.GirSourceComment gir_comment, GirMetaData metadata, string? this_name = null) {
+ public Comment? parse (Api.Node element, Api.GirSourceComment gir_comment, GirMetaData metadata, Importer.InternalIdRegistrar id_registrar, string? this_name = null) {
this.metadata = metadata;
+ this.id_registrar = id_registrar;
this.gir_comment = gir_comment;
this.element = element;
-
// main:
Comment? cmnt = _parse (gir_comment);
if (cmnt != null) {
@@ -673,7 +675,8 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
this.metadata = null;
this.gir_comment = null;
- this.element = element;
+ this.id_registrar = null;
+ this.element = null;
return cmnt;
}
diff --git a/src/libvaladoc/gtkdocrenderer.vala b/src/libvaladoc/gtkdocrenderer.vala
index 69ade76b46..877d7c5c9a 100644
--- a/src/libvaladoc/gtkdocrenderer.vala
+++ b/src/libvaladoc/gtkdocrenderer.vala
@@ -184,8 +184,20 @@ public class Valadoc.GtkdocRenderer : ContentRenderer {
}
public override void visit_symbol_link (SymbolLink element) {
+ if (element.content.size > 0) {
+ writer.text ("\"");
+ element.accept_children (this);
+ writer.text ("\" (");
+ visit_symbol_link (element);
+ writer.text (")");
+ } else {
+ visit_symbol_link (element);
+ }
+ }
+
+ public void write_symbol_link (SymbolLink element) {
if (element.symbol == null) {
- writer.text (element.label);
+ writer.text (element.given_symbol_name);
} else {
write_docbook_link (element.symbol);
}
diff --git a/src/libvaladoc/html/htmlmarkupwriter.vala b/src/libvaladoc/html/htmlmarkupwriter.vala
index 3c2f0cfb82..113f0c6f1a 100644
--- a/src/libvaladoc/html/htmlmarkupwriter.vala
+++ b/src/libvaladoc/html/htmlmarkupwriter.vala
@@ -1,6 +1,6 @@
/* markupwriter.vala
*
- * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois
+ * Copyright (C) 2008-2014 Florian Brosch, Didier Villevalois
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala
index 294a977773..84ba3f901b 100644
--- a/src/libvaladoc/html/htmlrenderer.vala
+++ b/src/libvaladoc/html/htmlrenderer.vala
@@ -1,6 +1,6 @@
/* htmlrenderer.vala
*
- * Copyright (C) 2008-20012 Florian Brosch, Didier Villevalois
+ * Copyright (C) 2008-20014 Florian Brosch, Didier Villevalois
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -62,26 +62,45 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
return linker.get_relative_link (_container, symbol, settings);
}
- private void write_unresolved_symbol_link (string label) {
- writer.start_tag ("code");
- writer.text (label);
- writer.end_tag ("code");
+ private void write_unresolved_symbol_link (string given_symbol_name, InlineContent? label_owner = null) {
+ if (label_owner == null || label_owner.content.size == 0) {
+ writer.start_tag ("code");
+ writer.text (given_symbol_name);
+ writer.end_tag ("code");
+ } else {
+ writer.start_tag ("i");
+ label_owner.accept_children (this);
+ writer.end_tag ("i");
+ }
}
- private void write_resolved_symbol_link (Api.Node symbol, string? given_label) {
- var label = (given_label == null || given_label == "") ? symbol.get_full_name () : given_label;
- if (symbol == _container || symbol == _owner) {
- writer.start_tag ("span", {"css", cssresolver.resolve (symbol)})
- .text (label)
- .end_tag ("span");
+ private void write_resolved_symbol_link (Api.Node symbol, string? given_symbol_name, InlineContent? label_owner = null) {
+ var symbol_name = (given_symbol_name == null || given_symbol_name == "") ? symbol.get_full_name () : given_symbol_name;
+ string href = (symbol == _container || symbol == _owner)? null : get_url (symbol);
+ string css_class = cssresolver.resolve (symbol);
+ string end_tag_name;
+
+
+ // Start Tag:
+ if (href != null) {
+ writer.start_tag ("a", {"href", href, "class", css_class});
+ end_tag_name = "a";
} else {
- var url = get_url (symbol);
- if (url == null) {
- write_unresolved_symbol_link (label);
- } else {
- writer.link (url, label, cssresolver.resolve (symbol));
- }
+ writer.start_tag ("span", {"class", css_class});
+ end_tag_name = "span";
}
+
+
+ // Content:
+ if (label_owner != null && label_owner.content.size > 0) {
+ label_owner.accept_children (this);
+ } else {
+ writer.text (symbol_name);
+ }
+
+
+ // End Tag:
+ writer.end_tag (end_tag_name);
}
private delegate void Write ();
@@ -325,9 +344,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
public override void visit_symbol_link (SymbolLink element) {
if (element.symbol == null) {
- write_unresolved_symbol_link (element.label);
+ write_unresolved_symbol_link (element.given_symbol_name, element);
} else {
- write_resolved_symbol_link (element.symbol, element.label);
+ write_resolved_symbol_link (element.symbol, element.given_symbol_name, element);
}
}
diff --git a/src/libvaladoc/importer/girdocumentationimporter.vala b/src/libvaladoc/importer/girdocumentationimporter.vala
index e4793f82e8..4186c27e7e 100644
--- a/src/libvaladoc/importer/girdocumentationimporter.vala
+++ b/src/libvaladoc/importer/girdocumentationimporter.vala
@@ -2,7 +2,7 @@
*
* Copyright (C) 2008-2010 Jürg Billeter
* Copyright (C) 2011 Luca Bruno
- * Copyright (C) 2011-2012 Florian Brosch
+ * Copyright (C) 2011-2014 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
diff --git a/src/libvaladoc/importer/internalidregistrar.vala b/src/libvaladoc/importer/internalidregistrar.vala
new file mode 100644
index 0000000000..a9ece01174
--- /dev/null
+++ b/src/libvaladoc/importer/internalidregistrar.vala
@@ -0,0 +1,88 @@
+/* gtkdocindexsgmlreader.vala
+ *
+ * Copyright (C) 2014 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;
+using Gee;
+
+
+public class Valadoc.Importer.InternalIdRegistrar {
+ private HashMap<string, Api.Node> symbol_map;
+ private HashMap<string, string> map;
+
+
+ public InternalIdRegistrar () {
+ map = new HashMap<string, string> ();
+ symbol_map = new HashMap<string, Api.Node> ();
+ }
+
+
+ public void register_symbol (string id, Api.Node symbol) {
+ this.symbol_map.set (id, symbol);
+ }
+
+ public string? map_url_id (string id) {
+ return map.get (id);
+ }
+
+ public Api.Node? map_symbol_id (string id) {
+ return symbol_map.get (id);
+ }
+
+
+ public void read_index_sgml_file (string filename, string? index_sgml_online, ErrorReporter reporter) {
+ MarkupSourceLocation begin;
+ MarkupSourceLocation end;
+ MarkupTokenType token;
+
+ string base_path = index_sgml_online ?? realpath (filename);
+ var reader = new MarkupReader (filename, reporter);
+
+ while ((token = reader.read_token (out begin, out end)) != MarkupTokenType.EOF) {
+ if (token == MarkupTokenType.START_ELEMENT && reader.name == "ONLINE") {
+ if (index_sgml_online == null) {
+ base_path = reader.get_attribute ("href");
+ if (base_path == null) {
+ reporter.error (filename, begin.line, begin.column, end.column, reader.get_line_content (begin.line), "missing attribute `href' in <ONLINE>");
+ }
+ }
+ } else if (token == MarkupTokenType.START_ELEMENT && reader.name == "ANCHOR") {
+ string id = reader.get_attribute ("id");
+ if (id == null) {
+ reporter.error (filename, begin.line, begin.column, end.column, reader.get_line_content (begin.line), "missing attribute `id' in <ANCHOR>");
+ }
+
+ string href = reader.get_attribute ("href");
+ if (href == null) {
+ reporter.error (filename, begin.line, begin.column, end.column, reader.get_line_content (begin.line), "missing attribute `href' in <ANCHOR>");
+ } else if (index_sgml_online != null) {
+ href = Path.get_basename (href);
+ }
+
+ map.set (id, Path.build_path ("/", base_path, href));
+ } else {
+ reporter.error (filename, begin.line, begin.column, end.column, reader.get_line_content (begin.line), "expected element of <ONLINE> or <ANCHOR>");
+ }
+ }
+ }
+}
+
+
diff --git a/src/libvaladoc/taglets/tagletlink.vala b/src/libvaladoc/taglets/tagletlink.vala
index 82a41baef1..990fe26e2f 100644
--- a/src/libvaladoc/taglets/tagletlink.vala
+++ b/src/libvaladoc/taglets/tagletlink.vala
@@ -1,7 +1,7 @@
/* taglet.vala
*
* Copyright (C) 2008-2009 Didier Villevalois
- * Copyright (C) 2008-2012 Florian Brosch
+ * Copyright (C) 2008-2014 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -127,12 +127,12 @@ public class Valadoc.Taglets.Link : InlineTaglet {
public override ContentElement produce_content () {
var link = new Content.SymbolLink ();
link.symbol = _symbol;
- link.label = symbol_name;
+ link.given_symbol_name = symbol_name;
Content.Inline content;
switch (_context) {
case SymbolContext.FINISH:
- link.label += ".end";
+ link.given_symbol_name += ".end";
content = link;
break;
|
1986158eade1ae778b714a5f0f6d906d0ebc33b2
|
Vala
|
vapigen: fix changing the type_name of an array field via metadata
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala
index e971ac0920..47e1fea529 100644
--- a/vapigen/valagidlparser.vala
+++ b/vapigen/valagidlparser.vala
@@ -1995,7 +1995,12 @@ public class Vala.GIdlParser : CodeVisitor {
type.value_owned = true;
}
} else if (nv[0] == "type_name") {
- ((UnresolvedType) type).unresolved_symbol = new UnresolvedSymbol (null, eval (nv[1]));
+ var unresolved_sym = new UnresolvedSymbol (null, eval (nv[1]));
+ if (type is ArrayType) {
+ ((UnresolvedType) ((ArrayType) type).element_type).unresolved_symbol = unresolved_sym;
+ } else {
+ ((UnresolvedType) type).unresolved_symbol = unresolved_sym;
+ }
} else if (nv[0] == "type_arguments") {
var type_args = eval (nv[1]).split (",");
foreach (string type_arg in type_args) {
|
208fc48688a926ffac9a7e47c7070976ad6a72de
|
Valadoc
|
libvaladoc: gir-reader: accept @<id>(::|:|->|.)(<gid>)
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index e1aa9f03db..ec1ced60f3 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -215,7 +215,11 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
this.tree = tree;
}
+ private Api.Node? element;
+
public Comment? parse (Api.Node element, Api.GirSourceComment gir_comment) {
+ this.element = element;
+
Comment? comment = this.parse_main_content (gir_comment);
if (comment == null) {
return null;
@@ -1082,6 +1086,77 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
+ private string[]? split_type_name (string id) {
+ unichar c;
+
+ for (unowned string pos = id; (c = pos.get_char ()) != '\0'; pos = pos.next_char ()) {
+ switch (c) {
+ case '-': // ->
+ return {id.substring (0, (long) (((char*) pos) - ((char*) id))), "->", (string) (((char*) pos) + 2)};
+
+ case ':': // : or ::
+ string sep = (pos.next_char ().get_char () == ':')? "::" : ":";
+ return {id.substring (0, (long) (((char*) pos) - ((char*) id))), sep, (string) (((char*) pos) + sep.length)};
+
+ case '.':
+ return {id.substring (0, (long) (((char*) pos) - ((char*) id))), ".", (string) (((char*) pos) + 1)};
+ }
+ }
+
+ return null;
+ }
+
+ private string? resolve_parameter_ctype (string parameter_name, out string? param_name) {
+ string[]? parts = split_type_name (current.content);
+ param_name = null;
+ if (parts == null) {
+ return null;
+ }
+
+ Api.FormalParameter? param = null; // type parameter or formal parameter
+ foreach (Api.Node node in this.element.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false)) {
+ if (node.name == parts[0]) {
+ param = node as Api.FormalParameter;
+ break;
+ }
+ }
+
+
+ Api.Item? inner = param.parameter_type;
+ while (inner != null) {
+ if (inner is Api.TypeReference) {
+ inner = ((Api.TypeReference) inner).data_type;
+ } else if (inner is Api.Pointer) {
+ inner = ((Api.Pointer) inner).data_type;
+ } else if (inner is Api.Array) {
+ inner = ((Api.Array) inner).data_type;
+ } else {
+ break ;
+ }
+ }
+
+
+ if (inner == null) {
+ return null;
+ }
+
+ string? cname = null;
+ if (inner is Api.ErrorDomain) {
+ cname = ((Api.ErrorDomain) inner).get_cname ();
+ } else if (inner is Api.Struct) {
+ cname = ((Api.Struct) inner).get_cname ();
+ } else if (inner is Api.Class) {
+ cname = ((Api.Class) inner).get_cname ();
+ } else if (inner is Api.Enum) {
+ cname = ((Api.Enum) inner).get_cname ();
+ } else {
+ assert_not_reached ();
+ }
+
+ param_name = (owned) parts[0];
+ return "c::" + cname + parts[1] + parts[2];
+ }
+
private Run parse_inline_content () {
Run run = factory.create_run (Run.Style.NONE);
@@ -1148,9 +1223,23 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
run.content.add (this.create_type_link (current.content));
next ();
} else if (current.type == TokenType.GTKDOC_PARAM) {
+ string? param_name;
+ string? cname = resolve_parameter_ctype (current.content, out param_name);
Run current_run = factory.create_run (Run.Style.MONOSPACED);
- current_run.content.add (factory.create_text (current.content));
- run.content.add (current_run);
+
+ if (cname == null) {
+ current_run.content.add (factory.create_text (current.content));
+ run.content.add (current_run);
+ } else {
+ current_run.content.add (factory.create_text (param_name));
+ run.content.add (current_run);
+
+ run.content.add (factory.create_text ("."));
+
+ Taglets.Link link = factory.create_taglet ("link") as Taglets.Link;
+ link.symbol_name = cname;
+ run.content.add (link);
+ }
next ();
} else if (current.type == TokenType.GTKDOC_SIGNAL) {
run.content.add (this.create_type_link ("::"+current.content));
|
35160c865ffa47a2c1958cb682b0c38406d240e5
|
Vala
|
Never mark *_register_type functions as static
*_register_type functions are called by the module init function,
which might reside in a different file.
Fixes bug 617850.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valatyperegisterfunction.vala b/codegen/valatyperegisterfunction.vala
index 5cf9fba538..7ce72052b4 100644
--- a/codegen/valatyperegisterfunction.vala
+++ b/codegen/valatyperegisterfunction.vala
@@ -79,11 +79,6 @@ public abstract class Vala.TypeRegisterFunction {
fun.add_parameter (new CCodeFormalParameter ("module", "GTypeModule *"));
var get_fun = new CCodeFunction ("%s_get_type".printf (get_type_declaration ().get_lower_case_cname (null)), "GType");
- if (get_accessibility () == SymbolAccessibility.PRIVATE) {
- fun.modifiers = CCodeModifiers.STATIC;
- // avoid C warning as this function is not always used
- fun.attributes = "G_GNUC_UNUSED";
- }
declaration_fragment.append (get_fun.copy ());
|
a82c6167163a27223548b1aa6b8cc1b720c33073
|
drools
|
JBRULES-2537 JSon Marshaller -Added JSon marshaller- using xstream
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java b/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java
index d9e560b55a7..bf808e6e071 100644
--- a/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java
+++ b/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java
@@ -142,13 +142,12 @@ public BaseClassFieldReader getClassFieldReader(final Class< ? > clazz,
final Object[] params = {index, fieldType, valueType};
return (BaseClassFieldReader) newClass.getConstructors()[0].newInstance( params );
} else {
- throw new RuntimeDroolsException( "Field/method '" + fieldName + "' not found for class '" + clazz.getName() + "'" );
+ throw new RuntimeDroolsException( "Field/method '" + fieldName + "' not found for class '" + clazz.getName() + "'\n" );
}
}
} catch ( final RuntimeDroolsException e ) {
throw e;
} catch ( final Exception e ) {
-// e.printStackTrace();
throw new RuntimeDroolsException( e );
}
}
diff --git a/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java b/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java
index 76e4acf98f3..8d0197359c3 100644
--- a/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java
+++ b/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java
@@ -41,6 +41,12 @@ public void setOutIdentifier(String outIdentifier) {
public String getIdentifier() {
return identifier;
}
+
+
+
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
public Object execute(Context context) {
StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession();
diff --git a/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java b/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java
index 14915f90a89..d34e3dedf6d 100644
--- a/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java
+++ b/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java
@@ -54,6 +54,10 @@ public Void execute(Context context) {
public String getIdentifier() {
return this.identifier;
}
+
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
public Object getObject() {
return this.object;
diff --git a/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java b/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java
index 3a62f3b56b9..01ac7ed3f40 100644
--- a/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java
+++ b/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java
@@ -1,5 +1,7 @@
package org.drools.command.runtime.rule;
+import java.io.ObjectStreamException;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@@ -89,5 +91,10 @@ public void setReturnObject(boolean returnObject) {
public String toString() {
return "session.insert(" + object + ");";
}
+
+// private Object readResolve() throws ObjectStreamException {
+// this.returnObject = true;
+// return this;
+// }
}
diff --git a/drools-core/src/main/java/org/drools/core/util/StringUtils.java b/drools-core/src/main/java/org/drools/core/util/StringUtils.java
index acc61e42095..906217f6c99 100644
--- a/drools-core/src/main/java/org/drools/core/util/StringUtils.java
+++ b/drools-core/src/main/java/org/drools/core/util/StringUtils.java
@@ -17,7 +17,10 @@
* limitations under the License.
*/
+import java.io.BufferedReader;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
@@ -1184,4 +1187,29 @@ public static String deleteAny(String inString, String charsToDelete) {
}
return out.toString();
}
+
+ public static String toString(Reader reader) throws IOException {
+ if ( reader instanceof BufferedReader ) {
+ return toString( (BufferedReader) reader );
+ } else {
+ return toString( new BufferedReader( reader ) );
+ }
+ }
+
+ public static String toString(InputStream is) throws IOException {
+ return toString( new BufferedReader(new InputStreamReader(is, "UTF-8") ) );
+ }
+
+ public static String toString(BufferedReader reader) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ try {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line).append("\n");
+ }
+ } finally {
+ reader.close();
+ }
+ return sb.toString();
+ }
}
\ No newline at end of file
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java b/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java
index bac8bda0437..96b13b255b1 100644
--- a/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java
@@ -1,1052 +1,23 @@
package org.drools.runtime.help.impl;
-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.Map.Entry;
-
-import org.drools.base.ClassObjectType;
-import org.drools.base.DroolsQuery;
-import org.drools.command.Command;
-import org.drools.command.CommandFactory;
-import org.drools.command.Setter;
-import org.drools.command.runtime.BatchExecutionCommand;
-import org.drools.command.runtime.GetGlobalCommand;
-import org.drools.command.runtime.SetGlobalCommand;
-import org.drools.command.runtime.process.AbortWorkItemCommand;
-import org.drools.command.runtime.process.CompleteWorkItemCommand;
-import org.drools.command.runtime.process.SignalEventCommand;
-import org.drools.command.runtime.process.StartProcessCommand;
-import org.drools.command.runtime.rule.FireAllRulesCommand;
-import org.drools.command.runtime.rule.GetObjectCommand;
-import org.drools.command.runtime.rule.GetObjectsCommand;
-import org.drools.command.runtime.rule.InsertElementsCommand;
-import org.drools.command.runtime.rule.InsertObjectCommand;
-import org.drools.command.runtime.rule.ModifyCommand;
-import org.drools.command.runtime.rule.QueryCommand;
-import org.drools.command.runtime.rule.RetractCommand;
-import org.drools.common.DefaultFactHandle;
-import org.drools.common.DisconnectedFactHandle;
-import org.drools.rule.Declaration;
-import org.drools.runtime.ExecutionResults;
import org.drools.runtime.help.BatchExecutionHelperProvider;
-import org.drools.runtime.impl.ExecutionResultImpl;
-import org.drools.runtime.rule.FactHandle;
-import org.drools.runtime.rule.QueryResults;
-import org.drools.runtime.rule.QueryResultsRow;
-import org.drools.runtime.rule.impl.FlatQueryResults;
-import org.drools.runtime.rule.impl.NativeQueryResults;
-import org.drools.spi.ObjectType;
import com.thoughtworks.xstream.XStream;
-import com.thoughtworks.xstream.converters.Converter;
-import com.thoughtworks.xstream.converters.MarshallingContext;
-import com.thoughtworks.xstream.converters.UnmarshallingContext;
-import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
-import com.thoughtworks.xstream.io.HierarchicalStreamReader;
-import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
-import com.thoughtworks.xstream.mapper.Mapper;
public class BatchExecutionHelperProviderImpl
implements
BatchExecutionHelperProvider {
-
- public XStream newXStreamMarshaller() {
- return newXStreamMarshaller( new XStream());
- }
-
- public XStream newXStreamMarshaller(XStream xstream) {
- ElementNames names = new XmlElementNames();
-
- // xstream.setMode( XStream.NO_REFERENCES );
- xstream.processAnnotations( BatchExecutionCommand.class );
- xstream.addImplicitCollection( BatchExecutionCommand.class,
- "commands" );
-
- xstream.alias( "batch-execution",
- BatchExecutionCommand.class );
- xstream.alias( "insert",
- InsertObjectCommand.class );
- xstream.alias( "modify",
- ModifyCommand.class );
- xstream.alias( "retract",
- RetractCommand.class );
- xstream.alias( "insert-elements",
- InsertElementsCommand.class );
- xstream.alias( "start-process",
- StartProcessCommand.class );
- xstream.alias( "signal-event",
- SignalEventCommand.class );
- xstream.alias( "complete-work-item",
- CompleteWorkItemCommand.class );
- xstream.alias( "abort-work-item",
- AbortWorkItemCommand.class );
- xstream.alias( "set-global",
- SetGlobalCommand.class );
- xstream.alias( "get-global",
- GetGlobalCommand.class );
- xstream.alias( "get-object",
- GetObjectCommand.class );
- xstream.alias( "get-objects",
- GetObjectsCommand.class );
- xstream.alias( "execution-results",
- ExecutionResultImpl.class );
- xstream.alias( "fire-all-rules",
- FireAllRulesCommand.class );
- xstream.alias( "query",
- QueryCommand.class );
- xstream.alias( "query-results",
- FlatQueryResults.class );
- xstream.alias( "query-results",
- NativeQueryResults.class );
- xstream.alias("fact-handle", DefaultFactHandle.class);
-
- xstream.registerConverter( new InsertConverter( xstream.getMapper() ) );
- xstream.registerConverter( new RetractConverter( xstream.getMapper() ) );
- xstream.registerConverter( new ModifyConverter( xstream.getMapper() ) );
- xstream.registerConverter( new GetObjectConverter( xstream.getMapper() ) );
- xstream.registerConverter( new InsertElementsConverter( xstream.getMapper() ) );
- xstream.registerConverter( new FireAllRulesConverter( xstream.getMapper() ) );
- xstream.registerConverter( new StartProcessConvert( xstream.getMapper() ) );
- xstream.registerConverter( new SignalEventConverter( xstream.getMapper() ) );
- xstream.registerConverter( new CompleteWorkItemConverter( xstream.getMapper() ) );
- xstream.registerConverter( new AbortWorkItemConverter( xstream.getMapper() ) );
- xstream.registerConverter( new QueryConverter( xstream.getMapper() ) );
- xstream.registerConverter( new SetGlobalConverter( xstream.getMapper() ) );
- xstream.registerConverter( new GetGlobalConverter( xstream.getMapper() ) );
- xstream.registerConverter( new GetObjectsConverter( xstream.getMapper() ) );
- xstream.registerConverter( new BatchExecutionResultConverter( xstream.getMapper() ) );
- xstream.registerConverter( new QueryResultsConverter( xstream.getMapper() ) );
- xstream.registerConverter( new FactHandleConverter(xstream.getMapper()));
-
- return xstream;
- }
-
- public static interface ElementNames {
- public String getIn();
-
- public String getInOut();
-
- public String getOut();
- }
-
- public static class JsonElementNames
- implements
- ElementNames {
- private String in = "in";
- private String inOut = "inOut";
- private String out = "out";
-
- public String getIn() {
- return in;
- }
-
- public String getInOut() {
- return inOut;
- }
-
- public String getOut() {
- return out;
- }
- }
-
- public static class XmlElementNames
- implements
- ElementNames {
- private String in = "in";
- private String inOut = "in-out";
- private String out = "out";
-
- public String getIn() {
- return in;
- }
-
- public String getInOut() {
- return inOut;
- }
-
- public String getOut() {
- return out;
- }
- }
-
- public static class InsertConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public InsertConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- InsertObjectCommand cmd = (InsertObjectCommand) object;
- if ( cmd.getOutIdentifier() != null ) {
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
-
- writer.addAttribute( "return-object",
- Boolean.toString( cmd.isReturnObject() ) );
-
- }
- writeItem( cmd.getObject(),
- context,
- writer );
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String identifierOut = reader.getAttribute( "out-identifier" );
- String returnObject = reader.getAttribute( "return-object" );
-
- reader.moveDown();
- Object object = readItem( reader,
- context,
- null );
- reader.moveUp();
- InsertObjectCommand cmd = new InsertObjectCommand( object );
- if ( identifierOut != null ) {
- cmd.setOutIdentifier( identifierOut );
- if ( returnObject != null ) {
- cmd.setReturnObject( Boolean.parseBoolean( returnObject ) );
- }
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( InsertObjectCommand.class );
- }
-
- }
-
- public static class FactHandleConverter extends AbstractCollectionConverter
- implements
- Converter {
- public FactHandleConverter(Mapper mapper) {
- super(mapper);
- }
-
- public boolean canConvert(Class aClass) {
- return FactHandle.class.isAssignableFrom(aClass);
- }
-
- public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
- FactHandle fh = (FactHandle) object;
- //writer.startNode("fact-handle");
- writer.addAttribute("externalForm", fh.toExternalForm());
- //writer.endNode();
- }
-
- public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) {
- throw new UnsupportedOperationException("Unable to unmarshal fact handles.");
- }
- }
-
- public static class ModifyConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public ModifyConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- ModifyCommand cmd = (ModifyCommand) object;
-
- writer.addAttribute( "factHandle",
- cmd.getFactHandle().toExternalForm() );
-
- for ( Setter setter : cmd.getSetters() ) {
- writer.startNode( "set" );
- writer.addAttribute( "accessor",
- setter.getAccessor() );
- writer.addAttribute( "value",
- setter.getValue() );
- writer.endNode();
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( "factHandle" ) );
-
- List<Setter> setters = new ArrayList();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- Setter setter = CommandFactory.newSetter( reader.getAttribute( "accessor" ),
- reader.getAttribute( "value" ) );
- setters.add( setter );
- reader.moveUp();
- }
-
- Command cmd = CommandFactory.newModify( factHandle,
- setters );
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( ModifyCommand.class );
- }
-
- }
-
- public static class RetractConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public RetractConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- RetractCommand cmd = (RetractCommand) object;
-
- writer.addAttribute( "factHandle",
- cmd.getFactHandle().toExternalForm() );
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( "factHandle" ) );
-
- Command cmd = CommandFactory.newRetract( factHandle );
-
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( RetractCommand.class );
- }
- }
-
- public static class InsertElementsConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public InsertElementsConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- InsertElementsCommand cmd = (InsertElementsCommand) object;
-
- if ( cmd.getOutIdentifier() != null ) {
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
-
- writer.addAttribute( "return-objects",
- Boolean.toString( cmd.isReturnObject() ) );
-
- }
-
- for ( Object element : cmd.getObjects() ) {
- writeItem( element,
- context,
- writer );
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String identifierOut = reader.getAttribute( "out-identifier" );
- String returnObject = reader.getAttribute( "return-objects" );
-
- List objects = new ArrayList();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- Object object = readItem( reader,
- context,
- null );
- reader.moveUp();
- objects.add( object );
- }
-
- InsertElementsCommand cmd = new InsertElementsCommand( objects );
- if ( identifierOut != null ) {
- cmd.setOutIdentifier( identifierOut );
- if ( returnObject != null ) {
- cmd.setReturnObject( Boolean.parseBoolean( returnObject ) );
- }
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( InsertElementsCommand.class );
- }
-
- }
-
- public static class SetGlobalConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public SetGlobalConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- SetGlobalCommand cmd = (SetGlobalCommand) object;
-
- writer.addAttribute( "identifier",
- cmd.getIdentifier() );
-
- if ( cmd.getOutIdentifier() != null ) {
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
- } else if ( cmd.isOut() ) {
- writer.addAttribute( "out",
- Boolean.toString( cmd.isOut() ) );
- }
-
- writeItem( cmd.getObject(),
- context,
- writer );
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String identifier = reader.getAttribute( "identifier" );
- String out = reader.getAttribute( "out" );
- String identifierOut = reader.getAttribute( "out-identifier" );
-
- reader.moveDown();
- Object object = readItem( reader,
- context,
- null );
- reader.moveUp();
- SetGlobalCommand cmd = new SetGlobalCommand( identifier,
- object );
- if ( identifierOut != null ) {
- cmd.setOutIdentifier( identifierOut );
- } else if ( out != null ) {
- cmd.setOut( Boolean.parseBoolean( out ) );
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( SetGlobalCommand.class );
- }
- }
-
- public static class GetObjectConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public GetObjectConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- GetObjectCommand cmd = (GetObjectCommand) object;
-
- writer.addAttribute( "factHandle",
- cmd.getFactHandle().toExternalForm() );
-
- if ( cmd.getOutIdentifier() != null ) {
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( "factHandle" ) );
- String identifierOut = reader.getAttribute( "out-identifier" );
-
- GetObjectCommand cmd = new GetObjectCommand( factHandle );
- if ( identifierOut != null ) {
- cmd.setOutIdentifier( identifierOut );
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( GetObjectCommand.class );
- }
- }
-
- public static class GetGlobalConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public GetGlobalConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- GetGlobalCommand cmd = (GetGlobalCommand) object;
- writer.addAttribute( "identifier",
- cmd.getIdentifier() );
-
- if ( cmd.getOutIdentifier() != null ) {
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String identifier = reader.getAttribute( "identifier" );
- String identifierOut = reader.getAttribute( "out-identifier" );
-
- GetGlobalCommand cmd = new GetGlobalCommand( identifier );
- if ( identifierOut != null ) {
- cmd.setOutIdentifier( identifierOut );
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( GetGlobalCommand.class );
- }
- }
-
- public static class GetObjectsConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public GetObjectsConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- GetObjectsCommand cmd = (GetObjectsCommand) object;
-
- if ( cmd.getOutIdentifier() != null ) {
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String identifierOut = reader.getAttribute( "out-identifier" );
-
- GetObjectsCommand cmd = new GetObjectsCommand();
- if ( identifierOut != null ) {
- cmd.setOutIdentifier( identifierOut );
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( GetObjectsCommand.class );
- }
- }
-
- public static class FireAllRulesConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public FireAllRulesConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- FireAllRulesCommand cmd = (FireAllRulesCommand) object;
-
- if ( cmd.getMax() != -1 ) {
- writer.addAttribute( "max",
- Integer.toString( cmd.getMax() ) );
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String max = reader.getAttribute( "max" );
-
- FireAllRulesCommand cmd = null;
-
- if ( max != null ) {
- cmd = new FireAllRulesCommand( Integer.parseInt( max ) );
- } else {
- cmd = new FireAllRulesCommand();
- }
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( FireAllRulesCommand.class );
- }
- }
-
- public static class QueryConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public QueryConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- QueryCommand cmd = (QueryCommand) object;
- writer.addAttribute( "out-identifier",
- cmd.getOutIdentifier() );
- writer.addAttribute( "name",
- cmd.getName() );
- if ( cmd.getArguments() != null ) {
- for ( Object arg : cmd.getArguments() ) {
- writeItem( arg,
- context,
- writer );
- }
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- List<String> outs = new ArrayList<String>();
-
- // Query cmd = null;
- String outIdentifier = reader.getAttribute( "out-identifier" );
- String name = reader.getAttribute( "name" );
- List<Object> args = new ArrayList<Object>();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- Object arg = readItem( reader,
- context,
- null );
- args.add( arg );
- reader.moveUp();
- }
- QueryCommand cmd = new QueryCommand( outIdentifier,
- name,
- args.toArray( new Object[args.size()] ) );
-
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( QueryCommand.class );
- }
- }
-
- public static class StartProcessConvert extends AbstractCollectionConverter
- implements
- Converter {
-
- public StartProcessConvert(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- StartProcessCommand cmd = (StartProcessCommand) object;
- writer.addAttribute( "processId",
- cmd.getProcessId() );
-
- for ( Entry<String, Object> entry : cmd.getParameters().entrySet() ) {
- writer.startNode( "parameter" );
- writer.addAttribute( "identifier",
- entry.getKey() );
- writeItem( entry.getValue(),
- context,
- writer );
- writer.endNode();
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String processId = reader.getAttribute( "processId" );
-
- HashMap<String, Object> params = new HashMap<String, Object>();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- String identifier = reader.getAttribute( "identifier" );
- reader.moveDown();
- Object value = readItem( reader,
- context,
- null );
- reader.moveUp();
- params.put( identifier,
- value );
- reader.moveUp();
- }
- StartProcessCommand cmd = new StartProcessCommand();
- cmd.setProcessId( processId );
- cmd.setParameters( params );
-
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( StartProcessCommand.class );
- }
- }
-
- public static class SignalEventConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public SignalEventConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- SignalEventCommand cmd = (SignalEventCommand) object;
- long processInstanceId = cmd.getProcessInstanceId();
- String eventType = cmd.getEventType();
- Object event = cmd.getEvent();
-
- if ( processInstanceId != -1 ) {
- writer.addAttribute( "process-instance-id",
- Long.toString( processInstanceId ) );
- }
-
- writer.addAttribute( "event-type",
- eventType );
-
- writeItem( event,
- context,
- writer );
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String processInstanceId = reader.getAttribute( "process-instance-id" );
- String eventType = reader.getAttribute( "event-type" );
-
- reader.moveDown();
- Object event = readItem( reader,
- context,
- null );
- reader.moveUp();
-
- Command cmd;
- if ( processInstanceId != null ) {
- cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ),
- eventType,
- event );
- } else {
- cmd = CommandFactory.newSignalEvent( eventType,
- event );
- }
-
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( SignalEventCommand.class );
- }
-
- }
-
- public static class CompleteWorkItemConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public CompleteWorkItemConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object;
- writer.addAttribute( "id",
- Long.toString( cmd.getWorkItemId() ) );
-
- for ( Entry<String, Object> entry : cmd.getResults().entrySet() ) {
- writer.startNode( "result" );
- writer.addAttribute( "identifier",
- entry.getKey() );
- writeItem( entry.getValue(),
- context,
- writer );
- writer.endNode();
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String id = reader.getAttribute( "id" );
-
- Map<String, Object> results = new HashMap<String, Object>();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- String identifier = reader.getAttribute( "identifier" );
- reader.moveDown();
- Object value = readItem( reader,
- context,
- null );
- reader.moveUp();
- results.put( identifier,
- value );
- reader.moveUp();
- }
-
- Command cmd = CommandFactory.newCompleteWorkItem( Long.parseLong( id ),
- results );
-
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( CompleteWorkItemCommand.class );
- }
- }
-
- public static class AbortWorkItemConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public AbortWorkItemConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- AbortWorkItemCommand cmd = (AbortWorkItemCommand) object;
- writer.addAttribute( "id",
- Long.toString( cmd.getWorkItemId() ) );
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- String id = reader.getAttribute( "id" );
- Command cmd = CommandFactory.newAbortWorkItem( Long.parseLong( id ) );
-
- return cmd;
- }
-
- public boolean canConvert(Class clazz) {
- return clazz.equals( AbortWorkItemCommand.class );
- }
+ public XStream newXStreamMarshaller() {
+ return newXStreamMarshaller( new XStream() );
}
- public static class BatchExecutionResultConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public BatchExecutionResultConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- ExecutionResults result = (ExecutionResults) object;
- for ( String identifier : result.getIdentifiers() ) {
- writer.startNode( "result" );
- writer.addAttribute( "identifier",
- identifier );
- Object value = result.getValue( identifier );
- writeItem( value,
- context,
- writer );
- writer.endNode();
- }
-
- for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) {
-
- Object handle = result.getFactHandle( identifier );
- if ( handle instanceof FactHandle ) {
- writer.startNode( "fact-handle" );
- writer.addAttribute( "identifier",
- identifier );
- writer.addAttribute( "externalForm",
- ((FactHandle) handle).toExternalForm() );
-
- writer.endNode();
- } else if ( handle instanceof Collection ) {
- writer.startNode( "fact-handles" );
- writer.addAttribute( "identifier",
- identifier );
- for ( FactHandle factHandle : (Collection<FactHandle>) handle ) {
- writer.startNode( "fact-handle" );
- writer.addAttribute( "externalForm",
- ((FactHandle) factHandle).toExternalForm() );
- writer.endNode();
- }
-
- writer.endNode();
- }
-
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- ExecutionResultImpl result = new ExecutionResultImpl();
- Map results = result.getResults();
- Map facts = result.getFactHandles();
-
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- if ( reader.getNodeName().equals( "result" ) ) {
- String identifier = reader.getAttribute( "identifier" );
- reader.moveDown();
- Object value = readItem( reader,
- context,
- null );
- results.put( identifier,
- value );
- reader.moveUp();
- reader.moveUp();
- } else if ( reader.getNodeName().equals( "fact-handle" ) ) {
- String identifier = reader.getAttribute( "identifier" );
- facts.put( identifier,
- new DisconnectedFactHandle( reader.getAttribute( "externalForm" ) ) );
- } else if ( reader.getNodeName().equals( "fact-handles" ) ) {
- String identifier = reader.getAttribute( "identifier" );
- List<FactHandle> list = new ArrayList();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- list.add( new DisconnectedFactHandle( reader.getAttribute( "externalForm" ) ) );
- reader.moveUp();
- }
- facts.put( identifier,
- list );
- } else {
- throw new IllegalArgumentException( "Element '" + reader.getNodeName() + "' is not supported here" );
- }
- }
-
- return result;
- }
-
- public boolean canConvert(Class clazz) {
- return ExecutionResults.class.isAssignableFrom( clazz );
- }
+ public XStream newJSonMarshaller() {
+ return XStreamJSon.newJSonMarshaller();
}
- public static class QueryResultsConverter extends AbstractCollectionConverter
- implements
- Converter {
-
- public QueryResultsConverter(Mapper mapper) {
- super( mapper );
- }
-
- public void marshal(Object object,
- HierarchicalStreamWriter writer,
- MarshallingContext context) {
- QueryResults results = (QueryResults) object;
-
- // write out identifiers
- List<String> originalIds = Arrays.asList( results.getIdentifiers() );
- List<String> actualIds = new ArrayList();
- if ( results instanceof NativeQueryResults ) {
- for ( String identifier : originalIds ) {
- // we don't want to marshall the query parameters
- Declaration declr = ((NativeQueryResults) results).getDeclarations().get( identifier );
- ObjectType objectType = declr.getPattern().getObjectType();
- if ( objectType instanceof ClassObjectType ) {
- if ( ((ClassObjectType) objectType).getClassType() == DroolsQuery.class ) {
- continue;
- }
- }
- actualIds.add( identifier );
- }
- }
-
- String[] identifiers = actualIds.toArray( new String[actualIds.size()] );
-
- writer.startNode( "identifiers" );
- for ( int i = 0; i < identifiers.length; i++ ) {
- writer.startNode( "identifier" );
- writer.setValue( identifiers[i] );
- writer.endNode();
- }
- writer.endNode();
-
- for ( QueryResultsRow result : results ) {
- writer.startNode( "row" );
- for ( int i = 0; i < identifiers.length; i++ ) {
- Object value = result.get( identifiers[i] );
- FactHandle factHandle = result.getFactHandle( identifiers[i] );
- writeItem( value,
- context,
- writer );
- writer.startNode( "fact-handle" );
- writer.addAttribute( "externalForm",
- ((FactHandle) factHandle).toExternalForm() );
- writer.endNode();
- }
- writer.endNode();
- }
- }
-
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- reader.moveDown();
- List<String> list = new ArrayList<String>();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- list.add( reader.getValue() );
- reader.moveUp();
- }
- reader.moveUp();
-
- HashMap<String, Integer> identifiers = new HashMap<String, Integer>();
- for ( int i = 0; i < list.size(); i++ ) {
- identifiers.put( list.get( i ),
- i );
- }
-
- ArrayList<ArrayList<Object>> results = new ArrayList();
- ArrayList<ArrayList<FactHandle>> resultHandles = new ArrayList();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- ArrayList objects = new ArrayList();
- ArrayList<FactHandle> handles = new ArrayList();
- while ( reader.hasMoreChildren() ) {
- reader.moveDown();
- Object object = readItem( reader,
- context,
- null );
- reader.moveUp();
-
- reader.moveDown();
- FactHandle handle = new DisconnectedFactHandle( reader.getAttribute( "externalForm" ) );
- reader.moveUp();
-
- objects.add( object );
- handles.add( handle );
- }
- results.add( objects );
- resultHandles.add( handles );
- reader.moveUp();
- }
-
- return new FlatQueryResults( identifiers,
- results,
- resultHandles );
- }
-
- public boolean canConvert(Class clazz) {
- return QueryResults.class.isAssignableFrom( clazz );
- }
+ public XStream newXStreamMarshaller(XStream xstream) {
+ return XStreamXML.newXStreamMarshaller(xstream);
}
+
}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsList.java b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsList.java
new file mode 100644
index 00000000000..d741f2181b2
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsList.java
@@ -0,0 +1,17 @@
+package org.drools.runtime.help.impl;
+
+import java.util.List;
+
+public class CommandsList {
+ private List<CommandsObjectContainer> commands;
+
+ public List<CommandsObjectContainer> getCommands() {
+ return commands;
+ }
+
+ public void setCommands(List<CommandsObjectContainer> commands) {
+ this.commands = commands;
+ }
+
+
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsObjectContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsObjectContainer.java
new file mode 100644
index 00000000000..c1d064e4ef3
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsObjectContainer.java
@@ -0,0 +1,14 @@
+package org.drools.runtime.help.impl;
+
+public class CommandsObjectContainer {
+
+ private Object containedObject;
+
+ public CommandsObjectContainer(Object object) {
+ this.containedObject = object;
+ }
+
+ public Object getContainedObject() {
+ return containedObject;
+ }
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/IdentifiersContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/IdentifiersContainer.java
new file mode 100644
index 00000000000..25a4591fbbb
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/IdentifiersContainer.java
@@ -0,0 +1,28 @@
+package org.drools.runtime.help.impl;
+
+import org.drools.runtime.rule.FactHandle;
+
+public class IdentifiersContainer {
+
+ private String identifier;
+ private int index;
+
+ public IdentifiersContainer() {
+
+ }
+
+ public IdentifiersContainer(String identifier,
+ int index) {
+ this.identifier = identifier;
+ this.index = index;
+ }
+
+ public String getIdentifier() {
+ return identifier;
+ }
+
+ public int getIndex() {
+ return index;
+ }
+
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/ObjectsObjectContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/ObjectsObjectContainer.java
new file mode 100644
index 00000000000..efc6d7e396a
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/ObjectsObjectContainer.java
@@ -0,0 +1,14 @@
+package org.drools.runtime.help.impl;
+
+public class ObjectsObjectContainer {
+
+ private Object containedObject;
+
+ public ObjectsObjectContainer(Object object) {
+ this.containedObject = object;
+ }
+
+ public Object getContainedObject() {
+ return containedObject;
+ }
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/ParameterContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/ParameterContainer.java
new file mode 100644
index 00000000000..e67c9d91812
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/ParameterContainer.java
@@ -0,0 +1,34 @@
+package org.drools.runtime.help.impl;
+
+public class ParameterContainer {
+
+ private String identifier;
+ private Object object;
+
+ public ParameterContainer() {
+
+ }
+
+ public ParameterContainer(String identifier,
+ Object object) {
+ this.identifier = identifier;
+ this.object = object;
+ }
+
+ public String getIdentifier() {
+ return identifier;
+ }
+
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ public Object getObject() {
+ return object;
+ }
+
+ public void setObject(Object object) {
+ this.object = object;
+ }
+
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/RowItemContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/RowItemContainer.java
new file mode 100644
index 00000000000..2102607d2c0
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/RowItemContainer.java
@@ -0,0 +1,37 @@
+package org.drools.runtime.help.impl;
+
+import org.drools.runtime.rule.FactHandle;
+
+
+public class RowItemContainer {
+
+ private FactHandle factHandle;
+ private Object object;
+
+ public RowItemContainer() {
+
+ }
+
+ public RowItemContainer(FactHandle factHandle,
+ Object object) {
+ super();
+ this.factHandle = factHandle;
+ this.object = object;
+ }
+
+ public FactHandle getFactHandle() {
+ return factHandle;
+ }
+
+ public void setFactHandle(FactHandle factHandle) {
+ this.factHandle = factHandle;
+ }
+
+ public Object getObject() {
+ return object;
+ }
+
+ public void setObject(Object object) {
+ this.object = object;
+ }
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/WorkItemResultsContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/WorkItemResultsContainer.java
new file mode 100644
index 00000000000..f7579c9f380
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/WorkItemResultsContainer.java
@@ -0,0 +1,34 @@
+package org.drools.runtime.help.impl;
+
+public class WorkItemResultsContainer {
+
+ private String identifier;
+ private Object object;
+
+ public WorkItemResultsContainer() {
+
+ }
+
+ public WorkItemResultsContainer(String identifier,
+ Object object) {
+ this.identifier = identifier;
+ this.object = object;
+ }
+
+ public String getIdentifier() {
+ return identifier;
+ }
+
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ public Object getObject() {
+ return object;
+ }
+
+ public void setObject(Object object) {
+ this.object = object;
+ }
+
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamHelper.java b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamHelper.java
new file mode 100644
index 00000000000..ab56dbd88b2
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamHelper.java
@@ -0,0 +1,72 @@
+package org.drools.runtime.help.impl;
+
+import org.drools.command.runtime.BatchExecutionCommand;
+import org.drools.command.runtime.GetGlobalCommand;
+import org.drools.command.runtime.SetGlobalCommand;
+import org.drools.command.runtime.process.AbortWorkItemCommand;
+import org.drools.command.runtime.process.CompleteWorkItemCommand;
+import org.drools.command.runtime.process.SignalEventCommand;
+import org.drools.command.runtime.process.StartProcessCommand;
+import org.drools.command.runtime.rule.FireAllRulesCommand;
+import org.drools.command.runtime.rule.GetObjectCommand;
+import org.drools.command.runtime.rule.GetObjectsCommand;
+import org.drools.command.runtime.rule.InsertElementsCommand;
+import org.drools.command.runtime.rule.InsertObjectCommand;
+import org.drools.command.runtime.rule.ModifyCommand;
+import org.drools.command.runtime.rule.QueryCommand;
+import org.drools.command.runtime.rule.RetractCommand;
+import org.drools.command.runtime.rule.ModifyCommand.SetterImpl;
+import org.drools.common.DefaultFactHandle;
+import org.drools.common.DisconnectedFactHandle;
+import org.drools.runtime.impl.ExecutionResultImpl;
+import org.drools.runtime.rule.impl.FlatQueryResults;
+import org.drools.runtime.rule.impl.NativeQueryResults;
+
+import com.thoughtworks.xstream.XStream;
+
+public class XStreamHelper {
+ public static void setAliases(XStream xstream) {
+ xstream.alias( "batch-execution",
+ BatchExecutionCommand.class );
+ xstream.alias( "insert",
+ InsertObjectCommand.class );
+ xstream.alias( "modify",
+ ModifyCommand.class );
+ xstream.alias( "setters",
+ SetterImpl.class );
+ xstream.alias( "retract",
+ RetractCommand.class );
+ xstream.alias( "insert-elements",
+ InsertElementsCommand.class );
+ xstream.alias( "start-process",
+ StartProcessCommand.class );
+ xstream.alias( "signal-event",
+ SignalEventCommand.class );
+ xstream.alias( "complete-work-item",
+ CompleteWorkItemCommand.class );
+ xstream.alias( "abort-work-item",
+ AbortWorkItemCommand.class );
+ xstream.alias( "set-global",
+ SetGlobalCommand.class );
+ xstream.alias( "get-global",
+ GetGlobalCommand.class );
+ xstream.alias( "get-object",
+ GetObjectCommand.class );
+ xstream.alias( "get-objects",
+ GetObjectsCommand.class );
+ xstream.alias( "execution-results",
+ ExecutionResultImpl.class );
+ xstream.alias( "fire-all-rules",
+ FireAllRulesCommand.class );
+ xstream.alias( "query",
+ QueryCommand.class );
+ xstream.alias( "query-results",
+ FlatQueryResults.class );
+ xstream.alias( "query-results",
+ NativeQueryResults.class );
+ xstream.alias( "fact-handle",
+ DefaultFactHandle.class );
+ xstream.alias( "fact-handle",
+ DisconnectedFactHandle.class );
+ }
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamJSon.java b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamJSon.java
new file mode 100644
index 00000000000..1842feaa509
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamJSon.java
@@ -0,0 +1,1355 @@
+package org.drools.runtime.help.impl;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.drools.command.Command;
+import org.drools.command.CommandFactory;
+import org.drools.command.Setter;
+import org.drools.command.impl.GenericCommand;
+import org.drools.command.runtime.BatchExecutionCommand;
+import org.drools.command.runtime.GetGlobalCommand;
+import org.drools.command.runtime.SetGlobalCommand;
+import org.drools.command.runtime.process.AbortWorkItemCommand;
+import org.drools.command.runtime.process.CompleteWorkItemCommand;
+import org.drools.command.runtime.process.SignalEventCommand;
+import org.drools.command.runtime.process.StartProcessCommand;
+import org.drools.command.runtime.rule.FireAllRulesCommand;
+import org.drools.command.runtime.rule.GetObjectCommand;
+import org.drools.command.runtime.rule.GetObjectsCommand;
+import org.drools.command.runtime.rule.InsertElementsCommand;
+import org.drools.command.runtime.rule.InsertObjectCommand;
+import org.drools.command.runtime.rule.ModifyCommand;
+import org.drools.command.runtime.rule.QueryCommand;
+import org.drools.command.runtime.rule.RetractCommand;
+import org.drools.common.DisconnectedFactHandle;
+import org.drools.runtime.ExecutionResults;
+import org.drools.runtime.impl.ExecutionResultImpl;
+import org.drools.runtime.rule.FactHandle;
+import org.drools.runtime.rule.QueryResults;
+import org.drools.runtime.rule.QueryResultsRow;
+import org.drools.runtime.rule.impl.FlatQueryResults;
+
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.converters.Converter;
+import com.thoughtworks.xstream.converters.MarshallingContext;
+import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
+import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
+import com.thoughtworks.xstream.core.util.HierarchicalStreams;
+import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
+import com.thoughtworks.xstream.io.HierarchicalStreamReader;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
+import com.thoughtworks.xstream.mapper.Mapper;
+
+public class XStreamJSon {
+ public static XStream newJSonMarshaller() {
+ JettisonMappedXmlDriver jet = new JettisonMappedXmlDriver();
+ XStream xstream = new XStream( jet );
+
+ XStreamHelper.setAliases( xstream );
+
+ xstream.alias( "commands",
+ CommandsObjectContainer.class );
+ xstream.alias( "objects",
+ ObjectsObjectContainer.class );
+ xstream.alias( "item",
+ RowItemContainer.class );
+ xstream.alias( "parameters",
+ ParameterContainer.class );
+ xstream.alias( "results",
+ WorkItemResultsContainer.class );
+
+ xstream.setMode( XStream.NO_REFERENCES );
+
+ xstream.registerConverter( new JSonFactHandleConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonBatchExecutionResultConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonInsertConverter( xstream.getMapper(),
+ xstream.getReflectionProvider() ) );
+ xstream.registerConverter( new JSonFireAllRulesConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonBatchExecutionCommandConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new CommandsContainerConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonGetObjectConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonRetractConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonModifyConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonSetGlobalConverter( xstream.getMapper(),
+ xstream.getReflectionProvider() ) );
+ xstream.registerConverter( new JSonInsertElementsConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonGetGlobalConverter( xstream.getMapper(),
+ xstream.getReflectionProvider() ) );
+ xstream.registerConverter( new JSonGetObjectsConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonQueryConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonQueryResultsConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new RowItemConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonStartProcessConvert( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonSignalEventConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonCompleteWorkItemConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new JSonAbortWorkItemConverter( xstream.getMapper() ) );
+
+ return xstream;
+ }
+
+ public static class CommandsContainerConverter extends AbstractCollectionConverter {
+ public CommandsContainerConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public boolean canConvert(Class type) {
+ return CommandsObjectContainer.class.isAssignableFrom( type );
+
+ }
+
+ @Override
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ CommandsObjectContainer container = (CommandsObjectContainer) object;
+
+ writeItem( container.getContainedObject(),
+ context,
+ writer );
+ }
+
+ @Override
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ throw new UnsupportedOperationException();
+ }
+
+ }
+
+ public static class RowItemConverter extends AbstractCollectionConverter {
+ public RowItemConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public boolean canConvert(Class type) {
+ return RowItemContainer.class.isAssignableFrom( type );
+
+ }
+
+ @Override
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ RowItemContainer container = (RowItemContainer) object;
+
+ writer.startNode( "external-form" );
+ writer.setValue( container.getFactHandle().toExternalForm() );
+ writer.endNode();
+
+ writer.startNode( "object" );
+ writeItem( container.getObject(),
+ context,
+ writer );
+ writer.endNode();
+ }
+
+ @Override
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String externalForm = null;
+ Object object = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "external-form".equals( nodeName ) ) {
+ externalForm = reader.getValue();
+ } else if ( "object".equals( nodeName ) ) {
+ reader.moveDown();
+ object = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ }
+ reader.moveUp();
+ }
+ return new RowItemContainer( new DisconnectedFactHandle( externalForm ),
+ object );
+ }
+
+ }
+
+ // public static class ModifyEntriesContainerConverter extends AbstractCollectionConverter {
+ // public ModifyEntriesContainerConverter(Mapper mapper) {
+ // super( mapper );
+ // }
+ //
+ // public boolean canConvert(Class type) {
+ // return ModifyEntriesContainer.class.isAssignableFrom( type );
+ //
+ // }
+ //
+ // @Override
+ // public void marshal(Object object,
+ // HierarchicalStreamWriter writer,
+ // MarshallingContext context) {
+ // ModifyEntriesContainer container = (ModifyEntriesContainer) object;
+ //
+ // writer.startNode( "accessor" );
+ // writer.setValue( container.getAccessor() );
+ // writer.endNode();
+ //
+ // writer.startNode( "value" );
+ // writer.setValue( container.getValue() );
+ // writer.endNode();
+ // }
+ //
+ // @Override
+ // public Object unmarshal(HierarchicalStreamReader reader,
+ // UnmarshallingContext context) {
+ // throw new UnsupportedOperationException();
+ // }
+ //
+ // }
+
+ public static class JSonBatchExecutionCommandConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonBatchExecutionCommandConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ BatchExecutionCommand cmds = (BatchExecutionCommand) object;
+ if ( cmds.getLookup() != null ) {
+ writer.startNode( "lookup" );
+ writer.setValue( cmds.getLookup() );
+ writer.endNode();
+ }
+ List<GenericCommand< ? >> list = cmds.getCommands();
+
+ for ( GenericCommand cmd : list ) {
+ writeItem( new CommandsObjectContainer( cmd ),
+ context,
+ writer );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ List<GenericCommand< ? >> list = new ArrayList<GenericCommand< ? >>();
+ String lookup = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ if ( "commands".equals( reader.getNodeName() ) ) {
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ GenericCommand cmd = (GenericCommand) readItem( reader,
+ context,
+ null );
+ list.add( cmd );
+ reader.moveUp();
+ }
+ } else if ( "lookup".equals( reader.getNodeName() ) ) {
+ lookup = reader.getValue();
+ } else {
+ throw new IllegalArgumentException( "batch-execution does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
+ }
+ reader.moveUp();
+ }
+ return new BatchExecutionCommand( list,
+ lookup );
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( BatchExecutionCommand.class );
+ }
+ }
+
+ public static class JSonInsertConverter extends BaseConverter
+ implements
+ Converter {
+
+ public JSonInsertConverter(Mapper mapper,
+ ReflectionProvider reflectionProvider) {
+ super( mapper,
+ reflectionProvider );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ InsertObjectCommand cmd = (InsertObjectCommand) object;
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+
+ writer.startNode( "return-object" );
+ writer.setValue( Boolean.toString( cmd.isReturnObject() ) );
+ writer.endNode();
+ }
+ writeValue( writer,
+ context,
+ "object",
+ cmd.getObject() );
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ InsertObjectCommand cmd = new InsertObjectCommand();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "out-identifier".equals( nodeName ) ) {
+ cmd.setOutIdentifier( reader.getValue() );
+ } else if ( "return-object".equals( nodeName ) ) {
+ cmd.setReturnObject( Boolean.parseBoolean( reader.getValue() ) );
+ } else if ( "object".equals( nodeName ) ) {
+ cmd.setObject( readValue( reader,
+ context,
+ cmd.getObject(),
+ "object" ) );
+ }
+ reader.moveUp();
+
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( InsertObjectCommand.class );
+ }
+
+ }
+
+ public static class JSonFactHandleConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+ public JSonFactHandleConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public boolean canConvert(Class aClass) {
+ return FactHandle.class.isAssignableFrom( aClass );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext marshallingContext) {
+ FactHandle fh = (FactHandle) object;
+ writer.startNode( "external-form" );
+ writer.setValue( fh.toExternalForm() );
+ writer.endNode();
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext unmarshallingContext) {
+ reader.moveDown();
+ DisconnectedFactHandle factHandle = new DisconnectedFactHandle( reader.getValue() );
+ reader.moveUp();
+ return factHandle;
+ }
+ }
+
+ public static class JSonFireAllRulesConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonFireAllRulesConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ FireAllRulesCommand cmd = (FireAllRulesCommand) object;
+
+ if ( cmd.getMax() != -1 ) {
+ writer.startNode( "max" );
+ writer.setValue( Integer.toString( cmd.getMax() ) );
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String max = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ if ( "max".equals( reader.getNodeName() ) ) {
+ max = reader.getValue();
+ } else {
+ throw new IllegalArgumentException( "fire-all-rules does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
+ }
+ reader.moveUp();
+ }
+
+ FireAllRulesCommand cmd = null;
+
+ if ( max != null ) {
+ cmd = new FireAllRulesCommand( Integer.parseInt( max ) );
+ } else {
+ cmd = new FireAllRulesCommand();
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( FireAllRulesCommand.class );
+ }
+ }
+
+ public static class JSonGetObjectConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonGetObjectConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ GetObjectCommand cmd = (GetObjectCommand) object;
+ writer.startNode( "fact-handle" );
+ writer.setValue( cmd.getFactHandle().toExternalForm() );
+ writer.endNode();
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ FactHandle factHandle = null;
+ String outIdentifier = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String name = reader.getNodeName();
+ if ( "fact-handle".equals( name ) ) {
+ factHandle = new DisconnectedFactHandle( reader.getValue() );
+ } else if ( "out-identifier".equals( "out-identifier" ) ) {
+ outIdentifier = reader.getValue();
+ }
+ reader.moveUp();
+ }
+
+ GetObjectCommand cmd = new GetObjectCommand( factHandle );
+ if ( outIdentifier != null ) {
+ cmd.setOutIdentifier( outIdentifier );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( GetObjectCommand.class );
+ }
+ }
+
+ public static class JSonRetractConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonRetractConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ RetractCommand cmd = (RetractCommand) object;
+ writer.startNode( "fact-handle" );
+ writer.setValue( cmd.getFactHandle().toExternalForm() );
+ writer.endNode();
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ reader.moveDown();
+ FactHandle factHandle = new DisconnectedFactHandle( reader.getValue() );
+ reader.moveUp();
+
+ Command cmd = CommandFactory.newRetract( factHandle );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( RetractCommand.class );
+ }
+ }
+
+ public static class JSonModifyConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonModifyConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ ModifyCommand cmd = (ModifyCommand) object;
+
+ writer.startNode( "fact-handle" );
+ writer.setValue( cmd.getFactHandle().toExternalForm() );
+ writer.endNode();
+
+ List<Setter> setters = cmd.getSetters();
+ for ( Setter setter : setters ) {
+ writeItem( setter,
+ context,
+ writer );
+
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ reader.moveDown();
+ FactHandle factHandle = new DisconnectedFactHandle( reader.getValue() );
+ reader.moveUp();
+
+ List<Setter> setters = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+
+ reader.moveDown();
+ String accessor = reader.getValue();
+ reader.moveUp();
+
+ reader.moveDown();
+ String value = reader.getValue();
+ reader.moveUp();
+
+ Setter setter = CommandFactory.newSetter( accessor,
+ value );
+ setters.add( setter );
+
+ reader.moveUp();
+ }
+
+ Command cmd = CommandFactory.newModify( factHandle,
+ setters );
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( ModifyCommand.class );
+ }
+
+ }
+
+ public static class JSonInsertElementsConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonInsertElementsConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ InsertElementsCommand cmd = (InsertElementsCommand) object;
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+
+ writer.startNode( "return-objects" );
+ writer.setValue( Boolean.toString( cmd.isReturnObject() ) );
+ writer.endNode();
+
+ }
+
+ for ( Object element : cmd.getObjects() ) {
+ writeItem( new ObjectsObjectContainer( element ),
+ context,
+ writer );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ List objects = new ArrayList();
+ String outIdentifier = null;
+ String returnObjects = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "objects".equals( nodeName ) ) {
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ Object o = readItem( reader,
+ context,
+ null );
+ objects.add( o );
+ reader.moveUp();
+ }
+ } else if ( "out-identifier".equals( nodeName ) ) {
+ outIdentifier = reader.getValue();
+ } else if ( "return-objects".equals( nodeName ) ) {
+ returnObjects = reader.getValue();
+ } else {
+ throw new IllegalArgumentException( "insert-elements does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
+ }
+ reader.moveUp();
+ }
+ InsertElementsCommand cmd = new InsertElementsCommand( objects );
+ if ( outIdentifier != null ) {
+ cmd.setOutIdentifier( outIdentifier );
+ if ( outIdentifier != null ) {
+ cmd.setReturnObject( Boolean.parseBoolean( returnObjects ) );
+ }
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( InsertElementsCommand.class );
+ }
+ }
+
+ public static class JSonBatchExecutionResultConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonBatchExecutionResultConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ ExecutionResults result = (ExecutionResults) object;
+ writer.startNode( "results" );
+ if ( !result.getIdentifiers().isEmpty() ) {
+ for ( String identifier : result.getIdentifiers() ) {
+ writer.startNode( "result" );
+
+ writer.startNode( "identifier" );
+ writer.setValue( identifier );
+ writer.endNode();
+
+ writer.startNode( "value" );
+ Object value = result.getValue( identifier );
+ writeItem( value,
+ context,
+ writer );
+ writer.endNode();
+
+ writer.endNode();
+ }
+ }
+
+ for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) {
+ Object handle = result.getFactHandle( identifier );
+ if ( handle instanceof FactHandle ) {
+ writer.startNode( "fact-handle" );
+
+ writer.startNode( "identifier" );
+ writer.setValue( identifier );
+ writer.endNode();
+
+ writer.startNode( "external-form" );
+ writer.setValue( ((FactHandle) handle).toExternalForm() );
+ writer.endNode();
+
+ writer.endNode();
+ } else if ( handle instanceof Collection ) {
+ writer.startNode( "fact-handles" );
+
+ writer.startNode( "identifier" );
+ writer.setValue( identifier );
+ writer.endNode();
+
+ //writer.startNode( "xxx" );
+ for ( FactHandle factHandle : (Collection<FactHandle>) handle ) {
+ writeItem( factHandle.toExternalForm(),
+ context,
+ writer );
+ }
+ //writer.endNode();
+
+ writer.endNode();
+ }
+ }
+
+ writer.endNode();
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ ExecutionResultImpl result = new ExecutionResultImpl();
+ Map results = result.getResults();
+ Map facts = result.getFactHandles();
+
+ reader.moveDown();
+ if ( "results".equals( reader.getNodeName() ) ) {
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+
+ if ( reader.getNodeName().equals( "result" ) ) {
+ reader.moveDown();
+ String identifier = reader.getValue();
+ reader.moveUp();
+
+ reader.moveDown();
+ reader.moveDown();
+ Object value = readItem( reader,
+ context,
+ null );
+ results.put( identifier,
+ value );
+ reader.moveUp();
+ reader.moveUp();
+ } else if ( reader.getNodeName().equals( "fact-handle" ) ) {
+ reader.moveDown();
+ String identifier = reader.getValue();
+ reader.moveUp();
+
+ reader.moveDown();
+ String externalForm = reader.getValue();
+ reader.moveUp();
+
+ facts.put( identifier,
+ new DisconnectedFactHandle( externalForm ) );
+ } else if ( reader.getNodeName().equals( "fact-handles" ) ) {
+ List list = new ArrayList();
+ String identifier = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ identifier = reader.getValue();
+ reader.moveUp();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ FactHandle factHandle = new DisconnectedFactHandle( (String) readItem( reader,
+ context,
+ null ) );
+ list.add( factHandle );
+ reader.moveUp();
+ }
+ }
+ facts.put( identifier,
+ list );
+ } else {
+ throw new IllegalArgumentException( "Element '" + reader.getNodeName() + "' is not supported here" );
+ }
+ reader.moveUp();
+ }
+ } else {
+ throw new IllegalArgumentException( "Element '" + reader.getNodeName() + "' is not supported here" );
+ }
+ reader.moveUp();
+
+ return result;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return ExecutionResults.class.isAssignableFrom( clazz );
+ }
+ }
+
+ public static abstract class BaseConverter {
+ protected Mapper mapper;
+ protected ReflectionProvider reflectionProvider;
+
+ public BaseConverter(Mapper mapper,
+ ReflectionProvider reflectionProvider) {
+ super();
+ this.mapper = mapper;
+ this.reflectionProvider = reflectionProvider;
+ }
+
+ protected void writeValue(HierarchicalStreamWriter writer,
+ MarshallingContext context,
+ String fieldName,
+ Object object) {
+ writer.startNode( fieldName );
+ String name = this.mapper.serializedClass( object.getClass() );
+ ExtendedHierarchicalStreamWriterHelper.startNode( writer,
+ name,
+ Mapper.Null.class );
+ context.convertAnother( object );
+ writer.endNode();
+ writer.endNode();
+ }
+
+ protected Object readValue(HierarchicalStreamReader reader,
+ UnmarshallingContext context,
+ Object object,
+ Object fieldName) {
+ reader.moveDown();
+ Class type = HierarchicalStreams.readClassType( reader,
+ this.mapper );
+ Object o = context.convertAnother( null,
+ type );
+
+ reader.moveUp();
+ return o;
+ }
+ }
+
+ public static class JSonSetGlobalConverter extends BaseConverter
+ implements
+ Converter {
+
+ public JSonSetGlobalConverter(Mapper mapper,
+ ReflectionProvider reflectionProvider) {
+ super( mapper,
+ reflectionProvider );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ SetGlobalCommand cmd = (SetGlobalCommand) object;
+
+ writer.startNode( "identifier" );
+ writer.setValue( cmd.getIdentifier() );
+ writer.endNode();
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+ } else if ( cmd.isOut() ) {
+ writer.startNode( "out" );
+ writer.setValue( Boolean.toString( cmd.isOut() ) );
+ writer.endNode();
+ }
+ writeValue( writer,
+ context,
+ "object",
+ cmd.getObject() );
+
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifier = null;
+ String out = null;
+ String outIdentifier = null;
+ Object object = null;
+ SetGlobalCommand cmd = new SetGlobalCommand();
+
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "identifier".equals( nodeName ) ) {
+ identifier = reader.getValue();
+ } else if ( "out".equals( nodeName ) ) {
+ out = reader.getValue();
+ } else if ( "out-identifier".equals( nodeName ) ) {
+ outIdentifier = reader.getValue();
+ } else if ( "object".equals( nodeName ) ) {
+ cmd.setObject( readValue( reader,
+ context,
+ cmd.getObject(),
+ "object" ) );
+ }
+ reader.moveUp();
+ }
+
+ cmd.setIdentifier( identifier );
+
+ if ( outIdentifier != null ) {
+ cmd.setOutIdentifier( outIdentifier );
+ } else if ( out != null ) {
+ cmd.setOut( Boolean.parseBoolean( out ) );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( SetGlobalCommand.class );
+ }
+
+ }
+
+ public static class JSonGetGlobalConverter extends BaseConverter
+ implements
+ Converter {
+
+ public JSonGetGlobalConverter(Mapper mapper,
+ ReflectionProvider reflectionProvider) {
+ super( mapper,
+ reflectionProvider );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ GetGlobalCommand cmd = (GetGlobalCommand) object;
+
+ writer.startNode( "identifier" );
+ writer.setValue( cmd.getIdentifier() );
+ writer.endNode();
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+ }
+
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifier = null;
+ String outIdentifier = null;
+ GetGlobalCommand cmd = new GetGlobalCommand();
+
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "identifier".equals( nodeName ) ) {
+ identifier = reader.getValue();
+ } else if ( "out-identifier".equals( nodeName ) ) {
+ outIdentifier = reader.getValue();
+ }
+ reader.moveUp();
+ }
+
+ cmd.setIdentifier( identifier );
+
+ if ( outIdentifier != null ) {
+ cmd.setOutIdentifier( outIdentifier );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( GetGlobalCommand.class );
+ }
+ }
+
+ public static class JSonGetObjectsConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonGetObjectsConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ GetObjectsCommand cmd = (GetObjectsCommand) object;
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String outIdentifier = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ if ( "out-identifier".equals( reader.getNodeName() ) ) {
+ outIdentifier = reader.getValue();
+ }
+ reader.moveUp();
+ }
+
+ GetObjectsCommand cmd = new GetObjectsCommand();
+ if ( outIdentifier != null ) {
+ cmd.setOutIdentifier( outIdentifier );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( GetObjectsCommand.class );
+ }
+ }
+
+ public static class JSonQueryConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonQueryConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ QueryCommand cmd = (QueryCommand) object;
+
+ writer.startNode( "out-identifier" );
+ writer.setValue( cmd.getOutIdentifier() );
+ writer.endNode();
+
+ writer.startNode( "name" );
+ writer.setValue( cmd.getName() );
+ writer.endNode();
+
+ if ( cmd.getArguments() != null && cmd.getArguments().size() > 0 ) {
+ writer.startNode( "args" );
+ for ( Object arg : cmd.getArguments() ) {
+ writeItem( arg,
+ context,
+ writer );
+ }
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ List<String> outs = new ArrayList<String>();
+
+ String outIdentifier = null;
+ String name = null;
+ List<Object> args = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "out-identifier".equals( nodeName ) ) {
+ outIdentifier = reader.getValue();
+ } else if ( "name".equals( nodeName ) ) {
+ name = reader.getValue();
+ } else if ( "args".equals( nodeName ) ) {
+ reader.moveDown();
+ args = new ArrayList<Object>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ Object arg = readItem( reader,
+ context,
+ null );
+ args.add( arg );
+ reader.moveUp();
+ }
+ reader.moveUp();
+ }
+ reader.moveUp();
+ }
+
+ QueryCommand cmd = new QueryCommand( outIdentifier,
+ name,
+ (args != null) ? args.toArray( new Object[args.size()] ) : null );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( QueryCommand.class );
+ }
+ }
+
+ public static class JSonQueryResultsConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonQueryResultsConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ QueryResults results = (QueryResults) object;
+
+ // write out identifiers
+ String[] identifiers = results.getIdentifiers();
+
+ writer.startNode( "identifiers" );
+ for ( int i = 0; i < identifiers.length; i++ ) {
+ writeItem( identifiers[i],
+ context,
+ writer );
+ }
+ writer.endNode();
+
+ for ( QueryResultsRow result : results ) {
+ writer.startNode( "row" );
+ for ( int i = 0; i < identifiers.length; i++ ) {
+ Object value = result.get( identifiers[i] );
+ FactHandle factHandle = result.getFactHandle( identifiers[i] );
+ writeItem( new RowItemContainer( factHandle,
+ value ),
+ context,
+ writer );
+ }
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ reader.moveDown();
+ List<String> list = new ArrayList<String>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ list.add( (String) readItem( reader,
+ context,
+ null ) );
+ reader.moveUp();
+ }
+ reader.moveUp();
+
+ HashMap<String, Integer> identifiers = new HashMap<String, Integer>();
+ for ( int i = 0; i < list.size(); i++ ) {
+ identifiers.put( list.get( i ),
+ i );
+ }
+
+ ArrayList<ArrayList<Object>> results = new ArrayList();
+ ArrayList<ArrayList<FactHandle>> resultHandles = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ ArrayList objects = new ArrayList();
+ ArrayList<FactHandle> handles = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ RowItemContainer container = (RowItemContainer) readItem( reader,
+ context,
+ null );
+
+ objects.add( container.getObject() );
+ handles.add( container.getFactHandle() );
+ reader.moveUp();
+ }
+ results.add( objects );
+ resultHandles.add( handles );
+ reader.moveUp();
+ }
+
+ return new FlatQueryResults( identifiers,
+ results,
+ resultHandles );
+ }
+
+ public boolean canConvert(Class clazz) {
+ return QueryResults.class.isAssignableFrom( clazz );
+ }
+ }
+
+ public static class JSonStartProcessConvert extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonStartProcessConvert(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ StartProcessCommand cmd = (StartProcessCommand) object;
+ writer.startNode( "process-id" );
+ writer.setValue( cmd.getProcessId() );
+ writer.endNode();
+
+ for ( Entry<String, Object> entry : cmd.getParameters().entrySet() ) {
+ writeItem( new ParameterContainer( entry.getKey(),
+ entry.getValue() ),
+ context,
+ writer );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ reader.moveDown();
+ String processId = reader.getValue();
+ reader.moveUp();
+
+ HashMap<String, Object> params = new HashMap<String, Object>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ ParameterContainer parameterContainer = (ParameterContainer) readItem( reader,
+ context,
+ null );
+ params.put( parameterContainer.getIdentifier(),
+ parameterContainer.getObject() );
+ reader.moveUp();
+ }
+
+ StartProcessCommand cmd = new StartProcessCommand();
+ cmd.setProcessId( processId );
+ cmd.setParameters( params );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( StartProcessCommand.class );
+ }
+ }
+
+ public static class JSonSignalEventConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonSignalEventConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ SignalEventCommand cmd = (SignalEventCommand) object;
+ long processInstanceId = cmd.getProcessInstanceId();
+ String eventType = cmd.getEventType();
+ Object event = cmd.getEvent();
+
+ if ( processInstanceId != -1 ) {
+ writer.startNode( "process-instance-id" );
+ writer.setValue( Long.toString( processInstanceId ) );
+ writer.endNode();
+ }
+
+ writer.addAttribute( "event-type",
+ eventType );
+
+ writer.startNode( "event-type" );
+ writer.setValue( eventType );
+ writer.endNode();
+
+ writer.startNode( "object" );
+ writeItem( event,
+ context,
+ writer );
+ writer.endNode();
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String processInstanceId = null;
+ String eventType = null;
+ Object event = null;
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "process-instance-id".equals( nodeName ) ) {
+ processInstanceId = reader.getValue();
+ } else if ( "event-type".equals( nodeName ) ) {
+ eventType = reader.getValue();
+ } else if ( "object".equals( nodeName ) ) {
+ reader.moveDown();
+ event = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ }
+ reader.moveUp();
+ }
+
+ Command cmd;
+ if ( processInstanceId != null ) {
+ cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ),
+ eventType,
+ event );
+ } else {
+ cmd = CommandFactory.newSignalEvent( eventType,
+ event );
+ }
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( SignalEventCommand.class );
+ }
+
+ }
+
+ public static class JSonCompleteWorkItemConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonCompleteWorkItemConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object;
+
+ writer.startNode( "id" );
+ writer.setValue( Long.toString( cmd.getWorkItemId() ) );
+ writer.endNode();
+
+ for ( Entry<String, Object> entry : cmd.getResults().entrySet() ) {
+ writeItem( new WorkItemResultsContainer( entry.getKey(),
+ entry.getValue() ),
+ context,
+ writer );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String id = null;
+ Map<String, Object> results = new HashMap<String, Object>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String nodeName = reader.getNodeName();
+ if ( "id".equals( nodeName ) ) {
+ id = reader.getValue();
+ } else if ( "results".equals( nodeName ) ) {
+ while ( reader.hasMoreChildren() ) {
+ WorkItemResultsContainer res = (WorkItemResultsContainer) readItem( reader,
+ context,
+ null );
+ results.put( res.getIdentifier(),
+ res.getObject() );
+ }
+ }
+ reader.moveUp();
+ }
+
+ return new CompleteWorkItemCommand( Long.parseLong( id ),
+ results );
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( CompleteWorkItemCommand.class );
+ }
+ }
+
+ public static class JSonAbortWorkItemConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public JSonAbortWorkItemConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ AbortWorkItemCommand cmd = (AbortWorkItemCommand) object;
+ writer.startNode( "id" );
+ writer.setValue( Long.toString( cmd.getWorkItemId() ) );
+ writer.endNode();
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ reader.moveDown();
+ String id = reader.getValue();
+ reader.moveUp();
+
+ Command cmd = CommandFactory.newAbortWorkItem( Long.parseLong( id ) );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( AbortWorkItemCommand.class );
+ }
+ }
+}
diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamXML.java b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamXML.java
new file mode 100644
index 00000000000..497d05aa480
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamXML.java
@@ -0,0 +1,964 @@
+package org.drools.runtime.help.impl;
+
+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.Map.Entry;
+
+import org.drools.base.ClassObjectType;
+import org.drools.base.DroolsQuery;
+import org.drools.command.Command;
+import org.drools.command.CommandFactory;
+import org.drools.command.Setter;
+import org.drools.command.runtime.BatchExecutionCommand;
+import org.drools.command.runtime.GetGlobalCommand;
+import org.drools.command.runtime.SetGlobalCommand;
+import org.drools.command.runtime.process.AbortWorkItemCommand;
+import org.drools.command.runtime.process.CompleteWorkItemCommand;
+import org.drools.command.runtime.process.SignalEventCommand;
+import org.drools.command.runtime.process.StartProcessCommand;
+import org.drools.command.runtime.rule.FireAllRulesCommand;
+import org.drools.command.runtime.rule.GetObjectCommand;
+import org.drools.command.runtime.rule.GetObjectsCommand;
+import org.drools.command.runtime.rule.InsertElementsCommand;
+import org.drools.command.runtime.rule.InsertObjectCommand;
+import org.drools.command.runtime.rule.ModifyCommand;
+import org.drools.command.runtime.rule.QueryCommand;
+import org.drools.command.runtime.rule.RetractCommand;
+import org.drools.common.DisconnectedFactHandle;
+import org.drools.rule.Declaration;
+import org.drools.runtime.ExecutionResults;
+import org.drools.runtime.impl.ExecutionResultImpl;
+import org.drools.runtime.rule.FactHandle;
+import org.drools.runtime.rule.QueryResults;
+import org.drools.runtime.rule.QueryResultsRow;
+import org.drools.runtime.rule.impl.FlatQueryResults;
+import org.drools.runtime.rule.impl.NativeQueryResults;
+import org.drools.spi.ObjectType;
+
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.converters.Converter;
+import com.thoughtworks.xstream.converters.MarshallingContext;
+import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
+import com.thoughtworks.xstream.io.HierarchicalStreamReader;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
+import com.thoughtworks.xstream.mapper.Mapper;
+
+public class XStreamXML {
+
+ public static XStream newXStreamMarshaller(XStream xstream) {
+ XStreamHelper.setAliases( xstream );
+
+ xstream.processAnnotations( BatchExecutionCommand.class );
+ xstream.addImplicitCollection( BatchExecutionCommand.class,
+ "commands" );
+
+ xstream.registerConverter( new InsertConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new RetractConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new ModifyConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new GetObjectConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new InsertElementsConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new FireAllRulesConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new StartProcessConvert( xstream.getMapper() ) );
+ xstream.registerConverter( new SignalEventConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new CompleteWorkItemConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new AbortWorkItemConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new QueryConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new SetGlobalConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new GetGlobalConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new GetObjectsConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new BatchExecutionResultConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new QueryResultsConverter( xstream.getMapper() ) );
+ xstream.registerConverter( new FactHandleConverter( xstream.getMapper() ) );
+
+ return xstream;
+ }
+
+
+ public static class InsertConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public InsertConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ InsertObjectCommand cmd = (InsertObjectCommand) object;
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+
+ writer.addAttribute( "return-object",
+ Boolean.toString( cmd.isReturnObject() ) );
+
+ }
+ writeItem( cmd.getObject(),
+ context,
+ writer );
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifierOut = reader.getAttribute( "out-identifier" );
+ String returnObject = reader.getAttribute( "return-object" );
+
+ reader.moveDown();
+ Object object = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ InsertObjectCommand cmd = new InsertObjectCommand( object );
+ if ( identifierOut != null ) {
+ cmd.setOutIdentifier( identifierOut );
+ if ( returnObject != null ) {
+ cmd.setReturnObject( Boolean.parseBoolean( returnObject ) );
+ }
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( InsertObjectCommand.class );
+ }
+
+ }
+
+ public static class FactHandleConverter
+ implements
+ Converter {
+ private Mapper mapper;
+
+ public FactHandleConverter(Mapper mapper) {
+ this.mapper = mapper;
+ }
+
+ public boolean canConvert(Class aClass) {
+ return FactHandle.class.isAssignableFrom( aClass );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext marshallingContext) {
+ FactHandle fh = (FactHandle) object;
+ //writer.startNode("fact-handle");
+ writer.addAttribute( "external-form",
+ fh.toExternalForm() );
+ //writer.endNode();
+ }
+
+ public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader,
+ UnmarshallingContext unmarshallingContext) {
+ throw new UnsupportedOperationException( "Unable to unmarshal fact handles." );
+ }
+ }
+
+ public static class ModifyConverter
+ implements
+ Converter {
+
+ public ModifyConverter(Mapper mapper) {
+
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ ModifyCommand cmd = (ModifyCommand) object;
+
+ writer.addAttribute( "fact-handle",
+ cmd.getFactHandle().toExternalForm() );
+
+ for ( Setter setter : cmd.getSetters() ) {
+ writer.startNode( "set" );
+ writer.addAttribute( "accessor",
+ setter.getAccessor() );
+ writer.addAttribute( "value",
+ setter.getValue() );
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( "fact-handle" ) );
+
+ List<Setter> setters = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ Setter setter = CommandFactory.newSetter( reader.getAttribute( "accessor" ),
+ reader.getAttribute( "value" ) );
+ setters.add( setter );
+ reader.moveUp();
+ }
+
+ Command cmd = CommandFactory.newModify( factHandle,
+ setters );
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( ModifyCommand.class );
+ }
+
+ }
+
+ public static class RetractConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public RetractConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ RetractCommand cmd = (RetractCommand) object;
+
+ writer.addAttribute( "fact-handle",
+ cmd.getFactHandle().toExternalForm() );
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( "fact-handle" ) );
+
+ Command cmd = CommandFactory.newRetract( factHandle );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( RetractCommand.class );
+ }
+ }
+
+ public static class InsertElementsConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public InsertElementsConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ InsertElementsCommand cmd = (InsertElementsCommand) object;
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+
+ writer.addAttribute( "return-objects",
+ Boolean.toString( cmd.isReturnObject() ) );
+
+ }
+
+ for ( Object element : cmd.getObjects() ) {
+ writeItem( element,
+ context,
+ writer );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifierOut = reader.getAttribute( "out-identifier" );
+ String returnObject = reader.getAttribute( "return-objects" );
+
+ List objects = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ Object object = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ objects.add( object );
+ }
+
+ InsertElementsCommand cmd = new InsertElementsCommand( objects );
+ if ( identifierOut != null ) {
+ cmd.setOutIdentifier( identifierOut );
+ if ( returnObject != null ) {
+ cmd.setReturnObject( Boolean.parseBoolean( returnObject ) );
+ }
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( InsertElementsCommand.class );
+ }
+
+ }
+
+ public static class SetGlobalConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public SetGlobalConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ SetGlobalCommand cmd = (SetGlobalCommand) object;
+
+ writer.addAttribute( "identifier",
+ cmd.getIdentifier() );
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+ } else if ( cmd.isOut() ) {
+ writer.addAttribute( "out",
+ Boolean.toString( cmd.isOut() ) );
+ }
+
+ writeItem( cmd.getObject(),
+ context,
+ writer );
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifier = reader.getAttribute( "identifier" );
+ String out = reader.getAttribute( "out" );
+ String identifierOut = reader.getAttribute( "out-identifier" );
+
+ reader.moveDown();
+ Object object = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ SetGlobalCommand cmd = new SetGlobalCommand( identifier,
+ object );
+ if ( identifierOut != null ) {
+ cmd.setOutIdentifier( identifierOut );
+ } else if ( out != null ) {
+ cmd.setOut( Boolean.parseBoolean( out ) );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( SetGlobalCommand.class );
+ }
+ }
+
+ public static class GetObjectConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public GetObjectConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ GetObjectCommand cmd = (GetObjectCommand) object;
+
+ writer.addAttribute( "fact-handle",
+ cmd.getFactHandle().toExternalForm() );
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( "fact-handle" ) );
+ String identifierOut = reader.getAttribute( "out-identifier" );
+
+ GetObjectCommand cmd = new GetObjectCommand( factHandle );
+ if ( identifierOut != null ) {
+ cmd.setOutIdentifier( identifierOut );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( GetObjectCommand.class );
+ }
+ }
+
+ public static class GetGlobalConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public GetGlobalConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ GetGlobalCommand cmd = (GetGlobalCommand) object;
+
+ writer.addAttribute( "identifier",
+ cmd.getIdentifier() );
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifier = reader.getAttribute( "identifier" );
+ String identifierOut = reader.getAttribute( "out-identifier" );
+
+ GetGlobalCommand cmd = new GetGlobalCommand( identifier );
+ if ( identifierOut != null ) {
+ cmd.setOutIdentifier( identifierOut );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( GetGlobalCommand.class );
+ }
+ }
+
+ public static class GetObjectsConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public GetObjectsConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ GetObjectsCommand cmd = (GetObjectsCommand) object;
+
+ if ( cmd.getOutIdentifier() != null ) {
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String identifierOut = reader.getAttribute( "out-identifier" );
+
+ GetObjectsCommand cmd = new GetObjectsCommand();
+ if ( identifierOut != null ) {
+ cmd.setOutIdentifier( identifierOut );
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( GetObjectsCommand.class );
+ }
+ }
+
+ public static class FireAllRulesConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public FireAllRulesConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ FireAllRulesCommand cmd = (FireAllRulesCommand) object;
+
+ if ( cmd.getMax() != -1 ) {
+ writer.addAttribute( "max",
+ Integer.toString( cmd.getMax() ) );
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String max = reader.getAttribute( "max" );
+
+ FireAllRulesCommand cmd = null;
+
+ if ( max != null ) {
+ cmd = new FireAllRulesCommand( Integer.parseInt( max ) );
+ } else {
+ cmd = new FireAllRulesCommand();
+ }
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( FireAllRulesCommand.class );
+ }
+ }
+
+ public static class QueryConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public QueryConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ QueryCommand cmd = (QueryCommand) object;
+ writer.addAttribute( "out-identifier",
+ cmd.getOutIdentifier() );
+ writer.addAttribute( "name",
+ cmd.getName() );
+ if ( cmd.getArguments() != null ) {
+ for ( Object arg : cmd.getArguments() ) {
+ writeItem( arg,
+ context,
+ writer );
+ }
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ List<String> outs = new ArrayList<String>();
+
+ // Query cmd = null;
+ String outIdentifier = reader.getAttribute( "out-identifier" );
+ String name = reader.getAttribute( "name" );
+ List<Object> args = new ArrayList<Object>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ Object arg = readItem( reader,
+ context,
+ null );
+ args.add( arg );
+ reader.moveUp();
+ }
+ QueryCommand cmd = new QueryCommand( outIdentifier,
+ name,
+ args.toArray( new Object[args.size()] ) );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( QueryCommand.class );
+ }
+ }
+
+ public static class StartProcessConvert extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public StartProcessConvert(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ StartProcessCommand cmd = (StartProcessCommand) object;
+ writer.addAttribute( "processId",
+ cmd.getProcessId() );
+
+ for ( Entry<String, Object> entry : cmd.getParameters().entrySet() ) {
+ writer.startNode( "parameter" );
+ writer.addAttribute( "identifier",
+ entry.getKey() );
+ writeItem( entry.getValue(),
+ context,
+ writer );
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String processId = reader.getAttribute( "processId" );
+
+ HashMap<String, Object> params = new HashMap<String, Object>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String identifier = reader.getAttribute( "identifier" );
+ reader.moveDown();
+ Object value = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ params.put( identifier,
+ value );
+ reader.moveUp();
+ }
+ StartProcessCommand cmd = new StartProcessCommand();
+ cmd.setProcessId( processId );
+ cmd.setParameters( params );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( StartProcessCommand.class );
+ }
+ }
+
+ public static class SignalEventConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public SignalEventConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ SignalEventCommand cmd = (SignalEventCommand) object;
+ long processInstanceId = cmd.getProcessInstanceId();
+ String eventType = cmd.getEventType();
+ Object event = cmd.getEvent();
+
+ if ( processInstanceId != -1 ) {
+ writer.addAttribute( "process-instance-id",
+ Long.toString( processInstanceId ) );
+ }
+
+ writer.addAttribute( "event-type",
+ eventType );
+
+ writeItem( event,
+ context,
+ writer );
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String processInstanceId = reader.getAttribute( "process-instance-id" );
+ String eventType = reader.getAttribute( "event-type" );
+
+ reader.moveDown();
+ Object event = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+
+ Command cmd;
+ if ( processInstanceId != null ) {
+ cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ),
+ eventType,
+ event );
+ } else {
+ cmd = CommandFactory.newSignalEvent( eventType,
+ event );
+ }
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( SignalEventCommand.class );
+ }
+
+ }
+
+ public static class CompleteWorkItemConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public CompleteWorkItemConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object;
+ writer.addAttribute( "id",
+ Long.toString( cmd.getWorkItemId() ) );
+
+ for ( Entry<String, Object> entry : cmd.getResults().entrySet() ) {
+ writer.startNode( "result" );
+ writer.addAttribute( "identifier",
+ entry.getKey() );
+ writeItem( entry.getValue(),
+ context,
+ writer );
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String id = reader.getAttribute( "id" );
+
+ Map<String, Object> results = new HashMap<String, Object>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ String identifier = reader.getAttribute( "identifier" );
+ reader.moveDown();
+ Object value = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+ results.put( identifier,
+ value );
+ reader.moveUp();
+ }
+
+ Command cmd = CommandFactory.newCompleteWorkItem( Long.parseLong( id ),
+ results );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( CompleteWorkItemCommand.class );
+ }
+ }
+
+ public static class AbortWorkItemConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public AbortWorkItemConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ AbortWorkItemCommand cmd = (AbortWorkItemCommand) object;
+ writer.addAttribute( "id",
+ Long.toString( cmd.getWorkItemId() ) );
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ String id = reader.getAttribute( "id" );
+ Command cmd = CommandFactory.newAbortWorkItem( Long.parseLong( id ) );
+
+ return cmd;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return clazz.equals( AbortWorkItemCommand.class );
+ }
+ }
+
+ public static class BatchExecutionResultConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public BatchExecutionResultConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ ExecutionResults result = (ExecutionResults) object;
+ for ( String identifier : result.getIdentifiers() ) {
+ writer.startNode( "result" );
+ writer.addAttribute( "identifier",
+ identifier );
+ Object value = result.getValue( identifier );
+ writeItem( value,
+ context,
+ writer );
+ writer.endNode();
+ }
+
+ for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) {
+ Object handle = result.getFactHandle( identifier );
+ if ( handle instanceof FactHandle ) {
+ writer.startNode( "fact-handle" );
+ writer.addAttribute( "identifier",
+ identifier );
+ writer.addAttribute( "external-form",
+ ((FactHandle) handle).toExternalForm() );
+
+ writer.endNode();
+ } else if ( handle instanceof Collection ) {
+ writer.startNode( "fact-handles" );
+ writer.addAttribute( "identifier",
+ identifier );
+ for ( FactHandle factHandle : (Collection<FactHandle>) handle ) {
+ writer.startNode( "fact-handle" );
+ writer.addAttribute( "external-form",
+ ((FactHandle) factHandle).toExternalForm() );
+ writer.endNode();
+ }
+
+ writer.endNode();
+ }
+
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ ExecutionResultImpl result = new ExecutionResultImpl();
+ Map results = result.getResults();
+ Map facts = result.getFactHandles();
+
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ if ( reader.getNodeName().equals( "result" ) ) {
+ String identifier = reader.getAttribute( "identifier" );
+ reader.moveDown();
+ Object value = readItem( reader,
+ context,
+ null );
+ results.put( identifier,
+ value );
+ reader.moveUp();
+ reader.moveUp();
+ } else if ( reader.getNodeName().equals( "fact-handle" ) ) {
+ String identifier = reader.getAttribute( "identifier" );
+ facts.put( identifier,
+ new DisconnectedFactHandle( reader.getAttribute( "external-form" ) ) );
+ } else if ( reader.getNodeName().equals( "fact-handles" ) ) {
+ String identifier = reader.getAttribute( "identifier" );
+ List<FactHandle> list = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ list.add( new DisconnectedFactHandle( reader.getAttribute( "external-form" ) ) );
+ reader.moveUp();
+ }
+ facts.put( identifier,
+ list );
+ } else {
+ throw new IllegalArgumentException( "Element '" + reader.getNodeName() + "' is not supported here" );
+ }
+ }
+
+ return result;
+ }
+
+ public boolean canConvert(Class clazz) {
+ return ExecutionResults.class.isAssignableFrom( clazz );
+ }
+ }
+
+ public static class QueryResultsConverter extends AbstractCollectionConverter
+ implements
+ Converter {
+
+ public QueryResultsConverter(Mapper mapper) {
+ super( mapper );
+ }
+
+ public void marshal(Object object,
+ HierarchicalStreamWriter writer,
+ MarshallingContext context) {
+ QueryResults results = (QueryResults) object;
+
+ // write out identifiers
+ List<String> originalIds = Arrays.asList( results.getIdentifiers() );
+ List<String> actualIds = new ArrayList();
+ if ( results instanceof NativeQueryResults ) {
+ for ( String identifier : originalIds ) {
+ // we don't want to marshall the query parameters
+ Declaration declr = ((NativeQueryResults) results).getDeclarations().get( identifier );
+ ObjectType objectType = declr.getPattern().getObjectType();
+ if ( objectType instanceof ClassObjectType ) {
+ if ( ((ClassObjectType) objectType).getClassType() == DroolsQuery.class ) {
+ continue;
+ }
+ }
+ actualIds.add( identifier );
+ }
+ }
+
+ String[] identifiers = actualIds.toArray( new String[actualIds.size()] );
+
+ writer.startNode( "identifiers" );
+ for ( int i = 0; i < identifiers.length; i++ ) {
+ writer.startNode( "identifier" );
+ writer.setValue( identifiers[i] );
+ writer.endNode();
+ }
+ writer.endNode();
+
+ for ( QueryResultsRow result : results ) {
+ writer.startNode( "row" );
+ for ( int i = 0; i < identifiers.length; i++ ) {
+ Object value = result.get( identifiers[i] );
+ FactHandle factHandle = result.getFactHandle( identifiers[i] );
+ writeItem( value,
+ context,
+ writer );
+ writer.startNode( "fact-handle" );
+ writer.addAttribute( "external-form",
+ ((FactHandle) factHandle).toExternalForm() );
+ writer.endNode();
+ }
+ writer.endNode();
+ }
+ }
+
+ public Object unmarshal(HierarchicalStreamReader reader,
+ UnmarshallingContext context) {
+ reader.moveDown();
+ List<String> list = new ArrayList<String>();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ list.add( reader.getValue() );
+ reader.moveUp();
+ }
+ reader.moveUp();
+
+ HashMap<String, Integer> identifiers = new HashMap<String, Integer>();
+ for ( int i = 0; i < list.size(); i++ ) {
+ identifiers.put( list.get( i ),
+ i );
+ }
+
+ ArrayList<ArrayList<Object>> results = new ArrayList();
+ ArrayList<ArrayList<FactHandle>> resultHandles = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ ArrayList objects = new ArrayList();
+ ArrayList<FactHandle> handles = new ArrayList();
+ while ( reader.hasMoreChildren() ) {
+ reader.moveDown();
+ Object object = readItem( reader,
+ context,
+ null );
+ reader.moveUp();
+
+ reader.moveDown();
+ FactHandle handle = new DisconnectedFactHandle( reader.getAttribute( "external-form" ) );
+ reader.moveUp();
+
+ objects.add( object );
+ handles.add( handle );
+ }
+ results.add( objects );
+ resultHandles.add( handles );
+ reader.moveUp();
+ }
+
+ return new FlatQueryResults( identifiers,
+ results,
+ resultHandles );
+ }
+
+ public boolean canConvert(Class clazz) {
+ return QueryResults.class.isAssignableFrom( clazz );
+ }
+ }
+}
|
846a05c7d078a6ba05f6ab3643ce6f382de784bc
|
drools
|
JBRULES-2817 Make the KnowledgeAgent Tests more- robust and faster--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@36213 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/agent/BaseKnowledgeAgentTest.java b/drools-compiler/src/test/java/org/drools/agent/BaseKnowledgeAgentTest.java
new file mode 100644
index 00000000000..6533b96e76a
--- /dev/null
+++ b/drools-compiler/src/test/java/org/drools/agent/BaseKnowledgeAgentTest.java
@@ -0,0 +1,312 @@
+package org.drools.agent;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.drools.KnowledgeBase;
+import org.drools.core.util.DroolsStreamUtils;
+import org.drools.core.util.FileManager;
+import org.drools.core.util.IoUtils;
+import org.drools.core.util.StringUtils;
+import org.drools.event.knowledgeagent.AfterChangeSetAppliedEvent;
+import org.drools.event.knowledgeagent.AfterChangeSetProcessedEvent;
+import org.drools.event.knowledgeagent.AfterResourceProcessedEvent;
+import org.drools.event.knowledgeagent.BeforeChangeSetAppliedEvent;
+import org.drools.event.knowledgeagent.BeforeChangeSetProcessedEvent;
+import org.drools.event.knowledgeagent.BeforeResourceProcessedEvent;
+import org.drools.event.knowledgeagent.KnowledgeAgentEventListener;
+import org.drools.event.knowledgeagent.KnowledgeBaseUpdatedEvent;
+import org.drools.event.knowledgeagent.ResourceCompilationFailedEvent;
+import org.drools.io.Resource;
+import org.drools.io.ResourceFactory;
+import org.drools.io.impl.ResourceChangeNotifierImpl;
+import org.drools.io.impl.ResourceChangeScannerImpl;
+import org.mortbay.jetty.Server;
+import org.mortbay.jetty.handler.ResourceHandler;
+
+import junit.framework.TestCase;
+
+public abstract class BaseKnowledgeAgentTest extends TestCase {
+ FileManager fileManager;
+ Server server;
+ ResourceChangeScannerImpl scanner;
+
+ @Override
+ protected void setUp() throws Exception {
+ this.fileManager = new FileManager();
+ this.fileManager.setUp();
+ ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset();
+
+ ResourceFactory.getResourceChangeNotifierService().start();
+
+ // we don't start the scanner, as we call it manually;
+ this.scanner = (ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService();
+
+ this.server = new Server( IoUtils.findPort() );
+ ResourceHandler resourceHandler = new ResourceHandler();
+ resourceHandler.setResourceBase( fileManager.getRootDirectory().getPath() );
+
+ this.server.setHandler( resourceHandler );
+
+ this.server.start();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ fileManager.tearDown();
+ ResourceFactory.getResourceChangeNotifierService().stop();
+ ((ResourceChangeNotifierImpl) ResourceFactory.getResourceChangeNotifierService()).reset();
+ ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset();
+
+ server.stop();
+ }
+
+
+
+ public int getPort() {
+ return this.server.getConnectors()[0].getLocalPort();
+ }
+
+
+ public void scan(KnowledgeAgent kagent) {
+ // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers
+ final CountDownLatch latch = new CountDownLatch( 1 );
+
+ KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() {
+
+ public void resourceCompilationFailed(ResourceCompilationFailedEvent event) {
+ }
+
+ public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) {
+ }
+
+ public void beforeResourceProcessed(BeforeResourceProcessedEvent event) {
+ }
+
+ public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) {
+ }
+
+ public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) {
+ }
+
+ public void afterResourceProcessed(AfterResourceProcessedEvent event) {
+ }
+
+ public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) {
+ }
+
+ public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) {
+ latch.countDown();
+ }
+ };
+
+ kagent.addEventListener( l );
+
+ this.scanner.scan();
+
+ try {
+ latch.await( 10, TimeUnit.SECONDS );
+ } catch ( InterruptedException e ) {
+ throw new RuntimeException( "Unable to wait for latch countdown", e);
+ }
+
+ if ( latch.getCount() > 0 ) {
+ throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" );
+ }
+
+ kagent.removeEventListener( l );
+ }
+
+ void applyChangeSet(KnowledgeAgent kagent, String xml) {
+ // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers
+ final CountDownLatch latch = new CountDownLatch( 1 );
+
+ KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() {
+
+ public void resourceCompilationFailed(ResourceCompilationFailedEvent event) {
+ }
+
+ public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) {
+ }
+
+ public void beforeResourceProcessed(BeforeResourceProcessedEvent event) {
+ }
+
+ public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) {
+ }
+
+ public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) {
+ }
+
+ public void afterResourceProcessed(AfterResourceProcessedEvent event) {
+ }
+
+ public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) {
+ }
+
+ public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) {
+ latch.countDown();
+ }
+ };
+
+ kagent.addEventListener( l );
+
+ kagent.applyChangeSet( ResourceFactory.newByteArrayResource( xml.getBytes() ) );
+
+ try {
+ latch.await( 10, TimeUnit.SECONDS );
+ } catch ( InterruptedException e ) {
+ throw new RuntimeException( "Unable to wait for latch countdown", e);
+ }
+
+ if ( latch.getCount() > 0 ) {
+ throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" );
+ }
+
+ kagent.removeEventListener( l );
+ }
+
+ void applyChangeSet(KnowledgeAgent kagent, Resource r) {
+ // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers
+ final CountDownLatch latch = new CountDownLatch( 1 );
+
+ KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() {
+
+ public void resourceCompilationFailed(ResourceCompilationFailedEvent event) {
+ }
+
+ public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) {
+ }
+
+ public void beforeResourceProcessed(BeforeResourceProcessedEvent event) {
+ }
+
+ public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) {
+ }
+
+ public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) {
+ }
+
+ public void afterResourceProcessed(AfterResourceProcessedEvent event) {
+ }
+
+ public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) {
+ }
+
+ public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) {
+ latch.countDown();
+ }
+ };
+
+ kagent.addEventListener( l );
+
+ kagent.applyChangeSet( r );
+
+ try {
+ latch.await( 10, TimeUnit.SECONDS );
+ } catch ( InterruptedException e ) {
+ throw new RuntimeException( "Unable to wait for latch countdown", e);
+ }
+
+ if ( latch.getCount() > 0 ) {
+ throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" );
+ }
+
+ kagent.removeEventListener( l );
+ }
+
+
+ public static void writePackage(Object pkg,
+ File p1file )throws IOException, FileNotFoundException {
+ if ( p1file.exists() ) {
+ // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds
+ // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
+ try {
+ Thread.sleep( 1000 );
+ } catch (Exception e) {
+ throw new RuntimeException( "Unable to sleep" );
+ }
+ }
+ FileOutputStream out = new FileOutputStream( p1file );
+ try {
+ DroolsStreamUtils.streamOut( out,
+ pkg );
+ } finally {
+ out.close();
+ }
+ }
+
+ public KnowledgeAgent createKAgent(KnowledgeBase kbase) {
+ return createKAgent( kbase, true );
+ }
+ public KnowledgeAgent createKAgent(KnowledgeBase kbase, boolean newInsatnce) {
+ KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
+ aconf.setProperty( "drools.agent.scanDirectories",
+ "true" );
+ aconf.setProperty( "drools.agent.scanResources",
+ "true" );
+ aconf.setProperty( "drools.agent.newInstance",
+ Boolean.toString( newInsatnce ) );
+
+ KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("test agent",
+ kbase,
+ aconf );
+
+ assertEquals( "test agent",
+ kagent.getName() );
+
+ return kagent;
+ }
+
+
+ public String createVersionedRule(String packageName, String ruleName, String attribute, String version) {
+ StringBuilder rule = new StringBuilder();
+ if ( StringUtils.isEmpty( packageName ) ) {
+ rule.append( "package org.drools.test\n" );
+ } else {
+ rule.append( "package " );
+ rule.append( packageName );
+ rule.append( "\n" );
+ }
+ rule.append( "global java.util.List list\n" );
+ rule.append( "rule " );
+ rule.append( ruleName );
+ rule.append( "\n" );
+ if ( !StringUtils.isEmpty( attribute ) ) {
+ rule.append( attribute +"\n" );
+ }
+ rule.append( "when\n" );
+ rule.append( "then\n" );
+ if ( StringUtils.isEmpty( version ) ) {
+ rule.append( "list.add( drools.getRule().getName() );\n" );
+ } else {
+ rule.append("list.add( drools.getRule().getName()+\"-V" + version + "\");\n");
+ }
+ rule.append( "end\n" );
+
+ return rule.toString();
+ }
+
+ public String createVersionedRule(String ruleName, String version) {
+ return createVersionedRule( null, ruleName, null, version );
+ }
+
+ public String createDefaultRule(String name) {
+ return createDefaultRule( name,
+ null );
+ }
+
+ public String createDefaultRule(String ruleName,
+ String packageName) {
+ return createVersionedRule( null, ruleName, null, null );
+ }
+
+ public String createAttributeRule(String ruleName,
+ String attribute) {
+ return createVersionedRule( null, ruleName, attribute, null );
+ }
+}
diff --git a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java
index 300214a0ffd..b82c18a3759 100644
--- a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java
+++ b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java
@@ -22,45 +22,7 @@
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ResourceHandler;
-public class KnowledgeAgentBinaryDiffTests extends TestCase {
-
- FileManager fileManager;
- private Server server;
-
- @Override
- protected void setUp() throws Exception {
- fileManager = new FileManager();
- fileManager.setUp();
- ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset();
- ResourceFactory.getResourceChangeNotifierService().start();
- ResourceFactory.getResourceChangeScannerService().start();
-
- this.server = new Server(0);
- ResourceHandler resourceHandler = new ResourceHandler();
- resourceHandler.setResourceBase(fileManager.getRootDirectory().getPath());
- System.out.println("root : " + fileManager.getRootDirectory().getPath());
-
- server.setHandler(resourceHandler);
-
- server.start();
-
- System.out.println("Server running on port "+this.getPort());
- }
-
- private int getPort(){
- return this.server.getConnectors()[0].getLocalPort();
- }
-
- @Override
- protected void tearDown() throws Exception {
- fileManager.tearDown();
- ResourceFactory.getResourceChangeNotifierService().stop();
- ResourceFactory.getResourceChangeScannerService().stop();
- ((ResourceChangeNotifierImpl) ResourceFactory.getResourceChangeNotifierService()).reset();
- ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset();
-
- server.stop();
- }
+public class KnowledgeAgentBinaryDiffTests extends BaseKnowledgeAgentTest {
public void testDifferentDateExpires() throws Exception {
@@ -293,19 +255,9 @@ public void assertRuleAttribute(String attribute, Rule rule) {
}
public void testDifferentLHS() throws Exception {
+ File f1 = fileManager.write( "rule1.drl",
+ createDefaultRule( "rule1" ) );
- String header1 = "";
- header1 += "package org.drools.test\n";
- header1 += "global java.util.List list\n\n";
-
- String rule1 = this.createCommonRule("rule1");
-
-
- File f1 = fileManager.newFile("rule1.drl");
- Writer output = new BufferedWriter(new FileWriter(f1));
- output.write(header1);
- output.write(rule1);
- output.close();
String xml = "";
xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'";
@@ -315,15 +267,13 @@ public void testDifferentLHS() throws Exception {
xml += " <resource source='http://localhost:"+this.getPort()+"/rule1.drl' type='DRL' />";
xml += " </add> ";
xml += "</change-set>";
- File fxml = fileManager.newFile("changeset.xml");
- output = new BufferedWriter(new FileWriter(fxml));
- output.write(xml);
- output.close();
+ File fxml = fileManager.write( "changeset.xml",
+ xml );
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
- KnowledgeAgent kagent = this.createKAgent(kbase);
-
- kagent.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL()));
+ KnowledgeAgent kagent = this.createKAgent(kbase, false);
+
+ applyChangeSet( kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL()) );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
List<String> list = new ArrayList<String>();
@@ -335,25 +285,11 @@ public void testDifferentLHS() throws Exception {
assertTrue(list.contains("rule1"));
list.clear();
-
- // have to sleep here as linux lastModified does not do milliseconds
- // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
- Thread.sleep(2000);
-
- //String rule1v3 = this.createCommonRule("rule1","3");
- String rule1v2 = "";
- rule1v2 += "rule rule1\n";
- rule1v2 += "when\n";
- rule1v2 += "\tString()\n";
- rule1v2 += "then\n";
- rule1v2 += "list.add( drools.getRule().getName()+\"-V2\");\n";
- rule1v2 += "end\n";
-
- output = new BufferedWriter(new FileWriter(f1));
- output.write(header1);
- output.write(rule1v2);
- output.close();
- Thread.sleep(3000);
+
+ File f2 = fileManager.write( "rule1.drl",
+ createVersionedRule( "rule1", "2" ) );
+
+ scan(kagent);
// Use the same session for incremental build test
ksession = kbase.newStatefulKnowledgeSession();
@@ -365,24 +301,14 @@ public void testDifferentLHS() throws Exception {
assertEquals(1, list.size());
assertTrue(list.contains("rule1-V2"));
- kagent.monitorResourceChangeEvents(false);
+ kagent.dispose();
}
public void testDifferentConsequences() throws Exception {
- String header1 = "";
- header1 += "package org.drools.test\n";
- header1 += "global java.util.List list\n\n";
-
- String rule1 = this.createCommonRule("rule1");
-
-
- File f1 = fileManager.newFile("rule1.drl");
- Writer output = new BufferedWriter(new FileWriter(f1));
- output.write(header1);
- output.write(rule1);
- output.close();
+ File f1 = fileManager.write( "rule1.drl",
+ createDefaultRule( "rule1" ) );
String xml = "";
xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'";
@@ -392,15 +318,13 @@ public void testDifferentConsequences() throws Exception {
xml += " <resource source='http://localhost:"+this.getPort()+"/rule1.drl' type='DRL' />";
xml += " </add> ";
xml += "</change-set>";
- File fxml = fileManager.newFile("changeset.xml");
- output = new BufferedWriter(new FileWriter(fxml));
- output.write(xml);
- output.close();
+ File fxml = fileManager.write( "changeset.xml",
+ xml );
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
- KnowledgeAgent kagent = this.createKAgent(kbase);
-
- kagent.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL()));
+ KnowledgeAgent kagent = this.createKAgent(kbase, false);
+
+ applyChangeSet( kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL()) );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
List<String> list = new ArrayList<String>();
@@ -413,17 +337,10 @@ public void testDifferentConsequences() throws Exception {
list.clear();
- // have to sleep here as linux lastModified does not do milliseconds
- // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
- Thread.sleep(2000);
-
- String rule1v2 = this.createCommonRule("rule1", "2");
-
- output = new BufferedWriter(new FileWriter(f1));
- output.write(header1);
- output.write(rule1v2);
- output.close();
- Thread.sleep(3000);
+ fileManager.write( "rule1.drl",
+ createVersionedRule( "rule1", "2" ) );
+
+ scan( kagent );
// Use the same session for incremental build test
ksession = kbase.newStatefulKnowledgeSession();
@@ -435,37 +352,12 @@ public void testDifferentConsequences() throws Exception {
assertEquals(1, list.size());
assertTrue(list.contains("rule1-V2"));
- kagent.monitorResourceChangeEvents(false);
+ kagent.dispose();
}
-
-
-
-
-
-//
-
- private void differentRuleAttributeTest(String attribute1, String attribute2,RuleAttributeAsserter asserter) throws Exception {
-
- String header1 = "";
- header1 += "package org.drools.test\n";
- header1 += "global java.util.List list\n\n";
-
- String rule1 = "";
- rule1 += "rule rule1\n";
- rule1 += attribute1+"\n";
- rule1 += "when\n";
- rule1 += "\tString()\n";
- rule1 += "then\n";
- rule1 += "list.add( drools.getRule().getName());\n";
- rule1 += "end\n";
-
-
- File f1 = fileManager.newFile("rule1.drl");
- Writer output = new BufferedWriter(new FileWriter(f1));
- output.write(header1);
- output.write(rule1);
- output.close();
+ private void differentRuleAttributeTest(String attribute1, String attribute2,RuleAttributeAsserter asserter) throws Exception {
+ File f1 = fileManager.write( "rule1.drl",
+ createAttributeRule( "rule1", attribute1 ) );
String xml = "";
xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'";
@@ -475,97 +367,30 @@ private void differentRuleAttributeTest(String attribute1, String attribute2,Rul
xml += " <resource source='http://localhost:"+this.getPort()+"/rule1.drl' type='DRL' />";
xml += " </add> ";
xml += "</change-set>";
- File fxml = fileManager.newFile("changeset.xml");
- output = new BufferedWriter(new FileWriter(fxml));
- output.write(xml);
- output.close();
+ File fxml = fileManager.write( "changeset.xml",
+ xml );
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
- KnowledgeAgent kagent = this.createKAgent(kbase);
+ KnowledgeAgent kagent = this.createKAgent(kbase, false);
- kagent.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL()));
+ applyChangeSet( kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL()));
org.drools.rule.Rule rule = (org.drools.rule.Rule) kagent.getKnowledgeBase().getRule("org.drools.test", "rule1");
assertNotNull(rule);
asserter.assertRuleAttribute(attribute1, rule);
-
- // have to sleep here as linux lastModified does not do milliseconds
- // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
- Thread.sleep(2000);
-
- String rule1v2 = "";
- rule1v2 += "rule rule1\n";
- rule1v2 += attribute2+"\n";
- rule1v2 += "when\n";
- rule1v2 += "\tString()\n";
- rule1v2 += "then\n";
- rule1v2 += "list.add( drools.getRule().getName());\n";
- rule1v2 += "end\n";
-
- output = new BufferedWriter(new FileWriter(f1));
- output.write(header1);
- output.write(rule1v2);
- output.close();
- Thread.sleep(3000);
-
+ File f2 = fileManager.write( "rule1.drl",
+ createAttributeRule( "rule1", attribute2 ) );
+
+ scan( kagent );
+
rule = (org.drools.rule.Rule) kagent.getKnowledgeBase().getRule("org.drools.test", "rule1");
assertNotNull(rule);
asserter.assertRuleAttribute(attribute2, rule);
- kagent.monitorResourceChangeEvents(false);
+ kagent.dispose();
}
-
- private KnowledgeAgent createKAgent(KnowledgeBase kbase) {
- ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration();
- sconf.setProperty("drools.resource.scanner.interval", "2");
- ResourceFactory.getResourceChangeScannerService().configure(sconf);
-
- //System.setProperty(KnowledgeAgentFactory.PROVIDER_CLASS_NAME_PROPERTY_NAME, "org.drools.agent.impl.KnowledgeAgentProviderImpl");
-
- KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
- aconf.setProperty("drools.agent.scanDirectories", "true");
- aconf.setProperty("drools.agent.scanResources", "true");
- // Testing incremental build here
- aconf.setProperty("drools.agent.newInstance", "false");
-
-
-
- KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent(
- "test agent", kbase, aconf);
-
- assertEquals("test agent", kagent.getName());
-
- return kagent;
- }
-
- private String createCommonRule(String ruleName) {
- StringBuilder sb = new StringBuilder();
- sb.append("rule ");
- sb.append(ruleName);
- sb.append("\n");
- sb.append("when\n");
- sb.append("then\n");
- sb.append("list.add( drools.getRule().getName() );\n");
- sb.append("end\n");
-
- return sb.toString();
- }
-
- private String createCommonRule(String ruleName, String version) {
- StringBuilder sb = new StringBuilder();
- sb.append("rule ");
- sb.append(ruleName);
- sb.append("\n");
- sb.append("when\n");
- sb.append("then\n");
- sb.append("list.add( drools.getRule().getName()+\"-V" + version + "\");\n");
- sb.append("end\n");
-
- return sb.toString();
- }
-
}
diff --git a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java
index 785d746f045..53abceefc03 100644
--- a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java
+++ b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java
@@ -42,193 +42,9 @@
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ResourceHandler;
-public class KnowledgeAgentTest extends TestCase {
+public class KnowledgeAgentTest extends BaseKnowledgeAgentTest {
- FileManager fileManager;
- private Server server;
-
- private ResourceChangeScannerImpl scanner;
-
- @Override
- protected void setUp() throws Exception {
- this.fileManager = new FileManager();
- this.fileManager.setUp();
- ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset();
-
- ResourceFactory.getResourceChangeNotifierService().start();
-
- // we don't start the scanner, as we call it manually;
- this.scanner = (ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService();
-
- this.server = new Server( IoUtils.findPort() );
- ResourceHandler resourceHandler = new ResourceHandler();
- resourceHandler.setResourceBase( fileManager.getRootDirectory().getPath() );
-
- this.server.setHandler( resourceHandler );
-
- this.server.start();
- }
-
- @Override
- protected void tearDown() throws Exception {
- fileManager.tearDown();
- ResourceFactory.getResourceChangeNotifierService().stop();
- ((ResourceChangeNotifierImpl) ResourceFactory.getResourceChangeNotifierService()).reset();
- ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset();
-
- server.stop();
- }
-
- private int getPort() {
- return this.server.getConnectors()[0].getLocalPort();
- }
-
- private void scan(KnowledgeAgent kagent) {
- // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers
- final CountDownLatch latch = new CountDownLatch( 1 );
-
- KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() {
-
- public void resourceCompilationFailed(ResourceCompilationFailedEvent event) {
- }
-
- public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) {
- }
-
- public void beforeResourceProcessed(BeforeResourceProcessedEvent event) {
- }
-
- public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) {
- }
-
- public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) {
- }
-
- public void afterResourceProcessed(AfterResourceProcessedEvent event) {
- }
-
- public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) {
- }
-
- public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) {
- latch.countDown();
- }
- };
-
- kagent.addEventListener( l );
-
- this.scanner.scan();
-
- try {
- latch.await( 10, TimeUnit.SECONDS );
- } catch ( InterruptedException e ) {
- throw new RuntimeException( "Unable to wait for latch countdown", e);
- }
-
- if ( latch.getCount() > 0 ) {
- throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" );
- }
-
- kagent.removeEventListener( l );
- }
-
- void applyChangeSet(KnowledgeAgent kagent, String xml) {
- // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers
- final CountDownLatch latch = new CountDownLatch( 1 );
-
- KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() {
-
- public void resourceCompilationFailed(ResourceCompilationFailedEvent event) {
- }
-
- public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) {
- }
-
- public void beforeResourceProcessed(BeforeResourceProcessedEvent event) {
- }
-
- public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) {
- }
-
- public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) {
- }
-
- public void afterResourceProcessed(AfterResourceProcessedEvent event) {
- }
-
- public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) {
- }
-
- public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) {
- latch.countDown();
- }
- };
-
- kagent.addEventListener( l );
-
- kagent.applyChangeSet( ResourceFactory.newByteArrayResource( xml.getBytes() ) );
-
- try {
- latch.await( 10, TimeUnit.SECONDS );
- } catch ( InterruptedException e ) {
- throw new RuntimeException( "Unable to wait for latch countdown", e);
- }
-
- if ( latch.getCount() > 0 ) {
- throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" );
- }
-
- kagent.removeEventListener( l );
- }
-
- void applyChangeSet(KnowledgeAgent kagent, Resource r) {
- // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers
- final CountDownLatch latch = new CountDownLatch( 1 );
-
- KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() {
-
- public void resourceCompilationFailed(ResourceCompilationFailedEvent event) {
- }
-
- public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) {
- }
-
- public void beforeResourceProcessed(BeforeResourceProcessedEvent event) {
- }
-
- public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) {
- }
-
- public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) {
- }
-
- public void afterResourceProcessed(AfterResourceProcessedEvent event) {
- }
-
- public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) {
- }
-
- public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) {
- latch.countDown();
- }
- };
-
- kagent.addEventListener( l );
-
- kagent.applyChangeSet( r );
-
- try {
- latch.await( 10, TimeUnit.SECONDS );
- } catch ( InterruptedException e ) {
- throw new RuntimeException( "Unable to wait for latch countdown", e);
- }
-
- if ( latch.getCount() > 0 ) {
- throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" );
- }
-
- kagent.removeEventListener( l );
- }
+
public void testModifyFileUrl() throws Exception {
@@ -861,70 +677,4 @@ public void testStatelessWithCommands() throws Exception {
assertTrue( list.contains( "rule2" ) );
}
- private static void writePackage(Object pkg,
- File p1file )throws IOException, FileNotFoundException {
- if ( p1file.exists() ) {
- // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds
- // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
- try {
- Thread.sleep( 1000 );
- } catch (Exception e) {
- throw new RuntimeException( "Unable to sleep" );
- }
- }
- FileOutputStream out = new FileOutputStream( p1file );
- try {
- DroolsStreamUtils.streamOut( out,
- pkg );
- } finally {
- out.close();
- }
- }
-
- private KnowledgeAgent createKAgent(KnowledgeBase kbase) {
- KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
- aconf.setProperty( "drools.agent.scanDirectories",
- "true" );
- aconf.setProperty( "drools.agent.scanResources",
- "true" );
- aconf.setProperty( "drools.agent.newInstance",
- "true" );
-
- KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("test agent",
- kbase,
- aconf );
-
- assertEquals( "test agent",
- kagent.getName() );
-
- return kagent;
- }
-
- private String createDefaultRule(String name) {
- return this.createDefaultRule( name,
- null );
- }
-
- private String createDefaultRule(String name,
- String packageName) {
- StringBuilder rule = new StringBuilder();
- if ( packageName == null ) {
- rule.append( "package org.drools.test\n" );
- } else {
- rule.append( "package " );
- rule.append( packageName );
- rule.append( "\n" );
- }
- rule.append( "global java.util.List list\n" );
- rule.append( "rule " );
- rule.append( name );
- rule.append( "\n" );
- rule.append( "when\n" );
- rule.append( "then\n" );
- rule.append( "list.add( drools.getRule().getName() );\n" );
- rule.append( "end\n" );
-
- return rule.toString();
- }
-
}
diff --git a/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java b/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
index ef830e29d09..1fb5c11c704 100644
--- a/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
+++ b/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
@@ -110,6 +110,10 @@ public void unsubscribeNotifier(ResourceChangeNotifier notifier,
// exist
}
}
+ }
+
+ public Map<Resource, Set<ResourceChangeNotifier>> getResources() {
+ return resources;
}
public void scan() {
@@ -161,6 +165,7 @@ public void scan() {
// detect if Resource has been removed
long lastModified = ((InternalResource) resource).getLastModified();
long lastRead = ((InternalResource) resource).getLastRead();
+
if ( lastModified == 0 ) {
this.listener.debug( "ResourceChangeScanner removed resource=" + resource );
removed.add( resource );
|
7147c843964a89cc4950ef8b9dc58cfe69aa974f
|
kotlin
|
Fix for KT-9897: Cannot pop operand off an empty- stack" with -= on ArrayList element-- -KT-9897 Fixed-
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java
index 9e39ca54dae40..7a421644f0c20 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java
@@ -835,7 +835,10 @@ public static void pop(@NotNull MethodVisitor v, @NotNull Type type) {
}
public static void dup(@NotNull InstructionAdapter v, @NotNull Type type) {
- int size = type.getSize();
+ dup(v, type.getSize());
+ }
+
+ private static void dup(@NotNull InstructionAdapter v, int size) {
if (size == 2) {
v.dup2();
}
@@ -847,6 +850,36 @@ else if (size == 1) {
}
}
+ public static void dup(@NotNull InstructionAdapter v, @NotNull Type topOfStack, @NotNull Type afterTop) {
+ if (topOfStack.getSize() == 0 && afterTop.getSize() == 0) {
+ return;
+ }
+
+ if (topOfStack.getSize() == 0) {
+ dup(v, afterTop);
+ }
+ else if (afterTop.getSize() == 0) {
+ dup(v, topOfStack);
+ }
+ else if (afterTop.getSize() == 1) {
+ if (topOfStack.getSize() == 1) {
+ dup(v, 2);
+ }
+ else {
+ v.dup2X1();
+ v.pop2();
+ v.dupX2();
+ v.dupX2();
+ v.pop();
+ v.dup2X1();
+ }
+ }
+ else {
+ //Note: it's possible to write dup3 and dup4
+ throw new UnsupportedOperationException("Don't know how generate dup3/dup4 for: " + topOfStack + " and " + afterTop);
+ }
+ }
+
public static void writeKotlinSyntheticClassAnnotation(@NotNull ClassBuilder v, @NotNull GenerationState state) {
AnnotationVisitor av = v.newAnnotation(asmDescByFqNameWithoutInnerClasses(KOTLIN_SYNTHETIC_CLASS), true);
JvmCodegenUtil.writeAbiVersion(av);
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java
index 875d3d24bbdf3..03ff9b57ef631 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java
@@ -771,12 +771,12 @@ public static class CollectionElementReceiver extends StackValue {
private final boolean isGetter;
private final ExpressionCodegen codegen;
private final ArgumentGenerator argumentGenerator;
- final List<ResolvedValueArgument> valueArguments;
+ private final List<ResolvedValueArgument> valueArguments;
private final FrameMap frame;
private final StackValue receiver;
private final ResolvedCall<FunctionDescriptor> resolvedGetCall;
private final ResolvedCall<FunctionDescriptor> resolvedSetCall;
- DefaultCallMask mask;
+ private DefaultCallMask mask;
public CollectionElementReceiver(
@NotNull Callable callable,
@@ -1424,6 +1424,11 @@ public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
currentExtensionReceiver
.moveToTopOfStack(hasExtensionReceiver ? type : currentExtensionReceiver.type, v, dispatchReceiver.type.getSize());
}
+
+ @Override
+ public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
+ AsmUtil.dup(v, extensionReceiver.type, dispatchReceiver.type);
+ }
}
public abstract static class StackValueWithSimpleReceiver extends StackValue {
diff --git a/compiler/testData/codegen/box/extensionProperties/kt9897.kt b/compiler/testData/codegen/box/extensionProperties/kt9897.kt
new file mode 100644
index 0000000000000..728323b1c649d
--- /dev/null
+++ b/compiler/testData/codegen/box/extensionProperties/kt9897.kt
@@ -0,0 +1,41 @@
+object Test {
+ var z = "0"
+ var l = 0L
+
+ fun changeObject(): String {
+ "1".someProperty += 1
+ return z
+ }
+
+ fun changeLong(): Long {
+ 2L.someProperty -= 1
+ return l
+ }
+
+ var String.someProperty: Int
+ get() {
+ return this.length
+ }
+ set(left) {
+ z += this + left
+ }
+
+ var Long.someProperty: Long
+ get() {
+ return l
+ }
+ set(left) {
+ l += this + left
+ }
+
+}
+
+fun box(): String {
+ val changeObject = Test.changeObject()
+ if (changeObject != "012") return "fail 1: $changeObject"
+
+ val changeLong = Test.changeLong()
+ if (changeLong != 1L) return "fail 1: $changeLong"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt b/compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt
new file mode 100644
index 0000000000000..9ff0dd42c2291
--- /dev/null
+++ b/compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt
@@ -0,0 +1,38 @@
+var z = "0"
+var l = 0L
+
+fun changeObject(): String {
+ "1".someProperty += 1
+ return z
+}
+
+fun changeLong(): Long {
+ 2L.someProperty -= 1
+ return l
+}
+
+var String.someProperty: Int
+ get() {
+ return this.length
+ }
+ set(left) {
+ z += this + left
+ }
+
+var Long.someProperty: Long
+ get() {
+ return l
+ }
+ set(left) {
+ l += this + left
+ }
+
+fun box(): String {
+ val changeObject = changeObject()
+ if (changeObject != "012") return "fail 1: $changeObject"
+
+ val changeLong = changeLong()
+ if (changeLong != 1L) return "fail 1: $changeLong"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt b/compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt
new file mode 100644
index 0000000000000..66559576b7bc7
--- /dev/null
+++ b/compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt
@@ -0,0 +1,41 @@
+object Test {
+ var z = "0"
+ var l = 0L
+
+ fun changeObject(): String {
+ "1".someProperty += 1
+ return z
+ }
+
+ fun changeLong(): Long {
+ 2L.someProperty -= 1
+ return l
+ }
+
+ @JvmStatic var String.someProperty: Int
+ get() {
+ return this.length
+ }
+ set(left) {
+ z += this + left
+ }
+
+ @JvmStatic var Long.someProperty: Long
+ get() {
+ return l
+ }
+ set(left) {
+ l += this + left
+ }
+
+}
+
+fun box(): String {
+ val changeObject = Test.changeObject()
+ if (changeObject != "012") return "fail 1: $changeObject"
+
+ val changeLong = Test.changeLong()
+ if (changeLong != 1L) return "fail 1: $changeLong"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
index f9b23efc1bfff..982367afb326e 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
@@ -3883,6 +3883,18 @@ public void testInClassWithSetter() throws Exception {
doTest(fileName);
}
+ @TestMetadata("kt9897.kt")
+ public void testKt9897() throws Exception {
+ String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/extensionProperties/kt9897.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("kt9897_topLevel.kt")
+ public void testKt9897_topLevel() throws Exception {
+ String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt");
+ doTest(fileName);
+ }
+
@TestMetadata("topLevel.kt")
public void testTopLevel() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/extensionProperties/topLevel.kt");
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java
index 18c59b627891e..1ae3240bb9dc3 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java
@@ -2299,6 +2299,12 @@ public void testInline() throws Exception {
doTestWithStdlib(fileName);
}
+ @TestMetadata("kt9897_static.kt")
+ public void testKt9897_static() throws Exception {
+ String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt");
+ doTestWithStdlib(fileName);
+ }
+
@TestMetadata("postfixInc.kt")
public void testPostfixInc() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/jvmStatic/postfixInc.kt");
|
04e5bace99ae09e0b43d3eea7806ca6bf654da94
|
tapiji
|
Improves performance of building resource / cleans up projects.
Fixes Issue 76.
Touches resources after creating a new resource bundle entry.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.apache.commons.io/build.properties b/org.apache.commons.io/build.properties
index 876835f3..1ac73bad 100644
--- a/org.apache.commons.io/build.properties
+++ b/org.apache.commons.io/build.properties
@@ -1,4 +1,3 @@
-source.. = .
output.. = .
bin.includes = META-INF/,\
org/
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
index f0f98c83..f2285e9f 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
@@ -1,12 +1,12 @@
/*******************************************************************************
- * Copyright (c) 2008 Stefan Mücke and others.
+ * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan Mücke - initial API and implementation
+ * Stefan M�cke - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.nls.internal.ui.editor;
@@ -113,10 +113,12 @@ public LocalizationLabelProvider(Object columnConfig) {
this.columnConfig = columnConfig;
}
+ @Override
public String getText(Object element) {
ResourceBundleKey key = (ResourceBundleKey) element;
- if (columnConfig == KEY)
+ if (columnConfig == KEY) {
return key.getName();
+ }
Locale locale = (Locale) columnConfig;
String value;
try {
@@ -125,8 +127,9 @@ public String getText(Object element) {
value = null;
MessagesEditorPlugin.log(e);
}
- if (value == null)
+ if (value == null) {
value = "";
+ }
return value;
}
}
@@ -139,6 +142,7 @@ public EditEntryAction() {
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
ResourceBundleKey key = getSelectedEntry();
if (key == null) {
@@ -146,7 +150,8 @@ public void run() {
}
Shell shell = Display.getCurrent().getActiveShell();
Locale[] locales = getLocales();
- EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(shell, locales);
+ EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(
+ shell, locales);
dialog.setResourceBundleKey(key);
if (dialog.open() == Window.OK) {
updateLabels();
@@ -156,24 +161,28 @@ public void run() {
private class ConfigureColumnsAction extends Action {
public ConfigureColumnsAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/conf_columns.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/conf_columns.gif"));
setToolTipText("Configure Columns");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
Shell shell = Display.getCurrent().getActiveShell();
String[] values = new String[columnConfigs.length];
for (int i = 0; i < columnConfigs.length; i++) {
String config = columnConfigs[i].toString();
- if (config.equals("")) //$NON-NLS-1$
+ if (config.equals("")) {
config = "default"; //$NON-NLS-1$
+ }
values[i] = config;
}
- ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell, values);
+ ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell,
+ values);
if (dialog.open() == Window.OK) {
String[] result = dialog.getResult();
Object[] newConfigs = new Object[result.length];
@@ -193,14 +202,16 @@ public void run() {
private class EditFilterOptionsAction extends Action {
public EditFilterOptionsAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/filter_obj.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/filter_obj.gif"));
setToolTipText("Edit Filter Options");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
Shell shell = Display.getCurrent().getActiveShell();
FilterOptionsDialog dialog = new FilterOptionsDialog(shell);
@@ -215,14 +226,16 @@ public void run() {
private class RefreshAction extends Action {
public RefreshAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/refresh.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/refresh.gif"));
setToolTipText("Refresh");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
MessagesEditorPlugin.disposeModel();
entryList = new ResourceBundleKeyList(new ResourceBundleKey[0]);
@@ -232,11 +245,14 @@ public void run() {
}
}
- private class BundleStringComparator implements Comparator<ResourceBundleKey> {
+ private class BundleStringComparator implements
+ Comparator<ResourceBundleKey> {
private final Locale locale;
+
public BundleStringComparator(Locale locale) {
this.locale = locale;
}
+
public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
String value1 = null;
String value2 = null;
@@ -250,53 +266,59 @@ public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
} catch (CoreException e) {
MessagesEditorPlugin.log(e);
}
- if (value1 == null)
+ if (value1 == null) {
value1 = ""; //$NON-NLS-1$
- if (value2 == null)
+ }
+ if (value2 == null) {
value2 = ""; //$NON-NLS-1$
+ }
return value1.compareToIgnoreCase(value2);
}
}
private class ExportAction extends Action {
public ExportAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/export.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/export.gif"));
setToolTipText("Export Current View to CSV or HTML File");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
Shell shell = Display.getCurrent().getActiveShell();
FileDialog dialog = new FileDialog(shell);
dialog.setText("Export File");
- dialog.setFilterExtensions(new String[] {"*.*", "*.htm; *.html", "*.txt; *.csv"});
- dialog.setFilterNames(new String[] {"All Files (*.*)", "HTML File (*.htm; *.html)",
- "Tabulator Separated File (*.txt; *.csv)"});
+ dialog.setFilterExtensions(new String[] { "*.*", "*.htm; *.html",
+ "*.txt; *.csv" });
+ dialog.setFilterNames(new String[] { "All Files (*.*)",
+ "HTML File (*.htm; *.html)",
+ "Tabulator Separated File (*.txt; *.csv)" });
final String filename = dialog.open();
if (filename != null) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
File file = new File(filename);
try {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(file),
- "UTF8")); //$NON-NLS-1$
+ BufferedWriter writer = new BufferedWriter(
+ new OutputStreamWriter(
+ new FileOutputStream(file), "UTF8")); //$NON-NLS-1$
boolean isHtml = filename.endsWith(".htm") || filename.endsWith(".html"); //$NON-NLS-1$ //$NON-NLS-2$
if (isHtml) {
writer.write("" //$NON-NLS-1$
- + "<html>\r\n" //$NON-NLS-1$
- + "<head>\r\n" //$NON-NLS-1$
- + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
- + "<style>\r\n" //$NON-NLS-1$
- + "table {width:100%;}\r\n" //$NON-NLS-1$
- + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
- + "</style>\r\n" //$NON-NLS-1$
- + "</head>\r\n" //$NON-NLS-1$
- + "<body>\r\n" //$NON-NLS-1$
- + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
+ + "<html>\r\n" //$NON-NLS-1$
+ + "<head>\r\n" //$NON-NLS-1$
+ + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
+ + "<style>\r\n" //$NON-NLS-1$
+ + "table {width:100%;}\r\n" //$NON-NLS-1$
+ + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
+ + "</style>\r\n" //$NON-NLS-1$
+ + "</head>\r\n" //$NON-NLS-1$
+ + "<body>\r\n" //$NON-NLS-1$
+ + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
}
int size = entryList.getSize();
@@ -313,8 +335,9 @@ public void run() {
writer.write("<tr><td>"); //$NON-NLS-1$
}
Object config = configs[j];
- if (!isHtml && j > 0)
+ if (!isHtml && j > 0) {
writer.write("\t"); //$NON-NLS-1$
+ }
if (config == KEY) {
writer.write(key.getName());
} else {
@@ -332,7 +355,8 @@ public void run() {
} else {
valueCount++;
}
- writer.write(EditResourceBundleEntriesDialog.escape(value));
+ writer.write(EditResourceBundleEntriesDialog
+ .escape(value));
}
if (isHtml) {
writer.write("</td></tr>\r\n"); //$NON-NLS-1$
@@ -350,23 +374,21 @@ public void run() {
}
writer.close();
Shell shell = Display.getCurrent().getActiveShell();
- MessageDialog.openInformation(
- shell,
- "Finished",
- "File written successfully.\n\nNumber of entries written: "
- + entryList.getSize()
- + "\nNumber of translations: "
- + valueCount
- + " ("
- + missingCount
- + " missing)");
+ MessageDialog.openInformation(shell, "Finished",
+ "File written successfully.\n\nNumber of entries written: "
+ + entryList.getSize()
+ + "\nNumber of translations: "
+ + valueCount + " (" + missingCount
+ + " missing)");
} catch (IOException e) {
Shell shell = Display.getCurrent().getActiveShell();
- ErrorDialog.openError(shell, "Error", "Error saving file.", new Status(
- IStatus.ERROR,
- MessagesEditorPlugin.PLUGIN_ID,
- e.getMessage(),
- e));
+ ErrorDialog.openError(
+ shell,
+ "Error",
+ "Error saving file.",
+ new Status(IStatus.ERROR,
+ MessagesEditorPlugin.PLUGIN_ID, e
+ .getMessage(), e));
}
}
});
@@ -376,7 +398,8 @@ public void run() {
public static final String ID = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
- protected static final Object KEY = "key"; // used to indicate the key column
+ protected static final Object KEY = "key"; // used to indicate the key
+ // column
private static final String PREF_SECTION_NAME = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
private static final String PREF_SORT_ORDER = "sortOrder"; //$NON-NLS-1$
@@ -400,7 +423,7 @@ public void run() {
protected Composite queryComposite;
protected Text queryText;
- // Results
+ // Results
private Section resultsSection;
private Composite tableComposite;
protected TableViewer tableViewer;
@@ -413,7 +436,8 @@ public void run() {
protected FilterOptions filterOptions;
/**
- * Column configuration. Values may be either <code>KEY</code> or a {@link Locale}.
+ * Column configuration. Values may be either <code>KEY</code> or a
+ * {@link Locale}.
*/
protected Object[] columnConfigs;
/**
@@ -428,6 +452,7 @@ public void run() {
public boolean contains(ISchedulingRule rule) {
return rule == this;
}
+
public boolean isConflicting(ISchedulingRule rule) {
return rule == this;
}
@@ -439,7 +464,8 @@ public LocalizationEditor() {
}
public ResourceBundleKey getSelectedEntry() {
- IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
+ IStructuredSelection selection = (IStructuredSelection) tableViewer
+ .getSelection();
if (selection.size() == 1) {
return (ResourceBundleKey) selection.getFirstElement();
}
@@ -459,7 +485,8 @@ public void createPartControl(Composite parent) {
form.setSeparatorVisible(true);
form.setText("Localization");
- form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor("obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
+ form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor(
+ "obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
toolkit.adapt(form);
toolkit.paintBordersFor(form);
final Composite body = form.getBody();
@@ -492,8 +519,10 @@ public void createPartControl(Composite parent) {
toolkit.createLabel(queryComposite, "Search:");
// Query text
- queryText = toolkit.createText(queryComposite, "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
+ queryText = toolkit.createText(queryComposite,
+ "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
queryText.addKeyListener(new KeyAdapter() {
+ @Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN) {
table.setFocus();
@@ -523,13 +552,16 @@ public void modifyText(ModifyEvent e) {
toolkit.adapt(control);
// Results section
- resultsSection = toolkit.createSection(body, ExpandableComposite.TITLE_BAR
- | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
- resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
+ resultsSection = toolkit.createSection(body,
+ ExpandableComposite.TITLE_BAR
+ | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
+ resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true, 2, 1));
resultsSection.setText("Localization Strings");
toolkit.adapt(resultsSection);
- final Composite resultsComposite = toolkit.createComposite(resultsSection, SWT.NONE);
+ final Composite resultsComposite = toolkit.createComposite(
+ resultsSection, SWT.NONE);
toolkit.adapt(resultsComposite);
final GridLayout gridLayout2 = new GridLayout();
gridLayout2.marginTop = 1;
@@ -539,8 +571,10 @@ public void modifyText(ModifyEvent e) {
resultsComposite.setLayout(gridLayout2);
filteredLabel = new Label(resultsSection, SWT.NONE);
- filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- filteredLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
+ filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER,
+ false, false));
+ filteredLabel.setForeground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_RED));
filteredLabel.setText(""); //$NON-NLS-1$
toolkit.paintBordersFor(resultsComposite);
@@ -548,9 +582,11 @@ public void modifyText(ModifyEvent e) {
resultsSection.setTextClient(filteredLabel);
tableComposite = toolkit.createComposite(resultsComposite, SWT.NONE);
- tableComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
+ tableComposite.setData(FormToolkit.KEY_DRAW_BORDER,
+ FormToolkit.TREE_BORDER);
toolkit.adapt(tableComposite);
- tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
// Table
createTableViewer();
@@ -563,7 +599,7 @@ public void modifyText(ModifyEvent e) {
filterOptions.pluginPatterns = new String[0];
filterOptions.keysWithMissingEntriesOnly = false;
sortOrder = KEY;
- columnConfigs = new Object[] {KEY, new Locale(""), new Locale("de")}; //$NON-NLS-1$ //$NON-NLS-2$
+ columnConfigs = new Object[] { KEY, new Locale(""), new Locale("de") }; //$NON-NLS-1$ //$NON-NLS-2$
// Load configuration
try {
@@ -578,7 +614,8 @@ public void modifyText(ModifyEvent e) {
}
protected void updateFilterLabel() {
- if (filterOptions.filterPlugins || filterOptions.keysWithMissingEntriesOnly) {
+ if (filterOptions.filterPlugins
+ || filterOptions.keysWithMissingEntriesOnly) {
filteredLabel.setText("(filtered)");
} else {
filteredLabel.setText(""); //$NON-NLS-1$
@@ -588,10 +625,12 @@ protected void updateFilterLabel() {
private void loadSettings() {
// TODO Move this to the preferences?
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault().getDialogSettings();
+ IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
- if (section == null)
+ if (section == null) {
return;
+ }
// Sort order
String sortOrderString = section.get(PREF_SORT_ORDER);
@@ -610,7 +649,8 @@ private void loadSettings() {
// Columns
String columns = section.get(PREF_COLUMNS);
if (columns != null) {
- String[] cols = columns.substring(1, columns.length() - 1).split(","); //$NON-NLS-1$
+ String[] cols = columns.substring(1, columns.length() - 1).split(
+ ","); //$NON-NLS-1$
columnConfigs = new Object[cols.length];
for (int i = 0; i < cols.length; i++) {
String value = cols[i].trim();
@@ -633,7 +673,8 @@ private void loadSettings() {
this.filterOptions.filterPlugins = "true".equals(filterOptions); //$NON-NLS-1$
String patterns = section.get(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS);
if (patterns != null) {
- String[] split = patterns.substring(1, patterns.length() - 1).split(","); //$NON-NLS-1$
+ String[] split = patterns.substring(1, patterns.length() - 1)
+ .split(","); //$NON-NLS-1$
for (int i = 0; i < split.length; i++) {
split[i] = split[i].trim();
}
@@ -641,11 +682,12 @@ private void loadSettings() {
}
this.filterOptions.keysWithMissingEntriesOnly = "true".equals(section.get(PREF_FILTER_OPTIONS_MISSING_ONLY)); //$NON-NLS-1$
- // TODO Save column widths
+ // TODO Save column widths
}
private void saveSettings() {
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault().getDialogSettings();
+ IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
if (section == null) {
section = dialogSettings.addNewSection(PREF_SECTION_NAME);
@@ -657,13 +699,17 @@ private void saveSettings() {
section.put(PREF_COLUMNS, Arrays.toString(columnConfigs));
// Filter options
- section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS, filterOptions.filterPlugins);
- section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS, Arrays.toString(filterOptions.pluginPatterns));
- section.put(PREF_FILTER_OPTIONS_MISSING_ONLY, filterOptions.keysWithMissingEntriesOnly);
+ section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS,
+ filterOptions.filterPlugins);
+ section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS,
+ Arrays.toString(filterOptions.pluginPatterns));
+ section.put(PREF_FILTER_OPTIONS_MISSING_ONLY,
+ filterOptions.keysWithMissingEntriesOnly);
}
private void createTableViewer() {
- table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION | SWT.MULTI);
+ table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION
+ | SWT.MULTI);
tableViewer = new TableViewer(table);
table.setHeaderVisible(true);
toolkit.adapt(table);
@@ -674,9 +720,12 @@ private void createTableViewer() {
public void updateElement(int index) {
tableViewer.replace(entryList.getKey(index), index);
}
+
public void dispose() {
}
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {
}
});
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
@@ -696,7 +745,8 @@ public void menuAboutToShow(IMenuManager menu) {
});
Menu contextMenu = menuManager.createContextMenu(table);
table.setMenu(contextMenu);
- getSite().registerContextMenu(menuManager, getSite().getSelectionProvider());
+ getSite().registerContextMenu(menuManager,
+ getSite().getSelectionProvider());
}
protected void fillContextMenu(IMenuManager menu) {
@@ -706,8 +756,10 @@ protected void fillContextMenu(IMenuManager menu) {
menu.add(new Separator());
}
MenuManager showInSubMenu = new MenuManager("&Show In");
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN.create(window);
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN
+ .create(window);
showInSubMenu.add(item);
menu.add(showInSubMenu);
}
@@ -726,7 +778,8 @@ public void doSaveAs() {
}
@Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
setSite(site);
setInput(input);
this.input = (LocalizationEditorInput) input;
@@ -784,14 +837,15 @@ public void run() {
strPattern = "*".concat(strPattern); //$NON-NLS-1$
}
- ResourceBundleModel model = MessagesEditorPlugin.getModel(new NullProgressMonitor());
+ ResourceBundleModel model = MessagesEditorPlugin
+ .getModel(new NullProgressMonitor());
Locale[] locales = getLocales();
// Collect keys
ResourceBundleKey[] keys;
if (!filterOptions.filterPlugins
- || filterOptions.pluginPatterns == null
- || filterOptions.pluginPatterns.length == 0) {
+ || filterOptions.pluginPatterns == null
+ || filterOptions.pluginPatterns.length == 0) {
// Ensure the bundles are loaded
for (Locale locale : locales) {
@@ -812,7 +866,8 @@ public void run() {
String[] patterns = filterOptions.pluginPatterns;
StringMatcher[] matchers = new StringMatcher[patterns.length];
for (int i = 0; i < matchers.length; i++) {
- matchers[i] = new StringMatcher(patterns[i], true, false);
+ matchers[i] = new StringMatcher(patterns[i], true,
+ false);
}
int size = 0;
@@ -833,14 +888,17 @@ public void run() {
size += family.getKeyCount();
}
- ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(size);
+ ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(
+ size);
for (ResourceBundleFamily family : families) {
// Ensure the bundles are loaded
for (Locale locale : locales) {
try {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
+ ResourceBundle bundle = family
+ .getBundle(locale);
+ if (bundle != null) {
bundle.load();
+ }
} catch (CoreException e) {
MessagesEditorPlugin.log(e);
}
@@ -851,25 +909,30 @@ public void run() {
filteredKeys.add(key);
}
}
- keys = filteredKeys.toArray(new ResourceBundleKey[filteredKeys.size()]);
+ keys = filteredKeys
+ .toArray(new ResourceBundleKey[filteredKeys.size()]);
}
// Filter keys
ArrayList<ResourceBundleKey> filtered = new ArrayList<ResourceBundleKey>();
- StringMatcher keyMatcher = new StringMatcher(keyPattern, true, false);
- StringMatcher strMatcher = new StringMatcher(strPattern, true, false);
+ StringMatcher keyMatcher = new StringMatcher(keyPattern, true,
+ false);
+ StringMatcher strMatcher = new StringMatcher(strPattern, true,
+ false);
for (ResourceBundleKey key : keys) {
- if (monitor.isCanceled())
+ if (monitor.isCanceled()) {
return Status.OK_STATUS;
+ }
// Missing entries
if (filterOptions.keysWithMissingEntriesOnly) {
boolean hasMissingEntry = false;
// Check all columns for missing values
for (Object config : columnConfigs) {
- if (config == KEY)
+ if (config == KEY) {
continue;
+ }
Locale locale = (Locale) config;
String value = null;
try {
@@ -882,8 +945,9 @@ public void run() {
break;
}
}
- if (!hasMissingEntry)
+ if (!hasMissingEntry) {
continue;
+ }
}
// Match key
@@ -894,8 +958,9 @@ public void run() {
// Match entries
for (Object config : columnConfigs) {
- if (config == KEY)
+ if (config == KEY) {
continue;
+ }
Locale locale = (Locale) config;
String value = null;
try {
@@ -910,11 +975,14 @@ public void run() {
}
}
- ResourceBundleKey[] array = filtered.toArray(new ResourceBundleKey[filtered.size()]);
+ ResourceBundleKey[] array = filtered
+ .toArray(new ResourceBundleKey[filtered.size()]);
if (sortOrder == KEY) {
Arrays.sort(array, new Comparator<ResourceBundleKey>() {
- public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
- return o1.getName().compareToIgnoreCase(o2.getName());
+ public int compare(ResourceBundleKey o1,
+ ResourceBundleKey o2) {
+ return o1.getName().compareToIgnoreCase(
+ o2.getName());
}
});
} else {
@@ -923,8 +991,9 @@ public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
}
entryList = new ResourceBundleKeyList(array);
- if (monitor.isCanceled())
+ if (monitor.isCanceled()) {
return Status.OK_STATUS;
+ }
final ResourceBundleKeyList entryList2 = entryList;
Display.getDefault().syncExec(new Runnable() {
@@ -968,7 +1037,8 @@ public void updateLabels() {
}
/**
- * @param columnConfigs an array containing <code>KEY</code> and {@link Locale} values
+ * @param columnConfigs
+ * an array containing <code>KEY</code> and {@link Locale} values
*/
public void setColumns(Object[] columnConfigs) {
this.columnConfigs = columnConfigs;
@@ -992,10 +1062,12 @@ public void updateColumns() {
// Create columns
for (Object config : columnConfigs) {
- if (config == null)
+ if (config == null) {
continue;
+ }
- final TableViewerColumn viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
+ final TableViewerColumn viewerColumn = new TableViewerColumn(
+ tableViewer, SWT.NONE);
TableColumn column = viewerColumn.getColumn();
if (config == KEY) {
column.setText("Key");
@@ -1005,14 +1077,16 @@ public void updateColumns() {
column.setText("Default Bundle");
} else {
String displayName = locale.getDisplayName();
- if (displayName.equals("")) //$NON-NLS-1$
+ if (displayName.equals("")) {
displayName = locale.toString();
+ }
column.setText(displayName);
localesToUnload.remove(locale);
}
}
- viewerColumn.setLabelProvider(new LocalizationLabelProvider(config));
+ viewerColumn
+ .setLabelProvider(new LocalizationLabelProvider(config));
tableColumnLayout.setColumnData(column, new ColumnWeightData(33));
columns.add(column);
column.addSelectionListener(new SelectionAdapter() {
@@ -1040,8 +1114,9 @@ public void widgetSelected(SelectionEvent e) {
sortOrder = KEY; // fall back to default sort order
}
int index = configs.indexOf(sortOrder);
- if (index != -1)
+ if (index != -1) {
table.setSortColumn(columns.get(index));
+ }
refresh();
}
@@ -1051,18 +1126,22 @@ public void widgetSelected(SelectionEvent e) {
*/
@SuppressWarnings("unchecked")
@Override
- public Object getAdapter(Class adapter) {
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
if (IShowInSource.class == adapter) {
return new IShowInSource() {
public ShowInContext getShowInContext() {
ResourceBundleKey entry = getSelectedEntry();
- if (entry == null)
+ if (entry == null) {
return null;
- ResourceBundle bundle = entry.getParent().getBundle(new Locale(""));
- if (bundle == null)
+ }
+ ResourceBundle bundle = entry.getParent().getBundle(
+ new Locale(""));
+ if (bundle == null) {
return null;
+ }
Object resource = bundle.getUnderlyingResource();
- return new ShowInContext(resource, new StructuredSelection(resource));
+ return new ShowInContext(resource, new StructuredSelection(
+ resource));
}
};
}
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 748769ae..47a17e98 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
@@ -23,7 +23,7 @@ public class Activator extends AbstractUIPlugin {
// The shared instance
private static Activator plugin;
-
+
/**
* The constructor
*/
@@ -32,7 +32,10 @@ public Activator() {
/*
* (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
@@ -41,7 +44,10 @@ public void start(BundleContext context) throws Exception {
/*
* (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
@@ -50,7 +56,7 @@ public void stop(BundleContext context) throws Exception {
/**
* Returns the shared instance
- *
+ *
* @return the shared instance
*/
public static Activator getDefault() {
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 f73022dd..2dea9d53 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
@@ -30,27 +30,25 @@
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
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 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 (element instanceof IFolder || element instanceof IFile) {
+ IResource resource = (IResource) element;
if (!InternationalizationNature.hasNature(resource.getProject()))
- return false;
+ return false;
try {
- ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(resource.getProject());
if (!manager.isResourceExclusionListenerRegistered(this))
manager.registerResourceExclusionListener(this);
if (ResourceBundleManager.isResourceExcluded(resource)) {
@@ -62,7 +60,7 @@ public boolean decorate(Object element) {
}
return needsDecoration;
}
-
+
@Override
public void addListener(ILabelProviderListener listener) {
label_provider_listener.add(listener);
@@ -70,7 +68,8 @@ public void addListener(ILabelProviderListener listener) {
@Override
public void dispose() {
- ResourceBundleManager.unregisterResourceExclusionListenerFromAllManagers (this);
+ ResourceBundleManager
+ .unregisterResourceExclusionListenerFromAllManagers(this);
}
@Override
@@ -85,7 +84,8 @@ public void removeListener(ILabelProviderListener listener) {
@Override
public void exclusionChanged(ResourceExclusionEvent event) {
- LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(this, event.getChangedResources().toArray());
+ LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(
+ this, event.getChangedResources().toArray());
for (ILabelProviderListener l : label_provider_listener)
l.labelProviderChanged(labelEvent);
}
@@ -93,9 +93,11 @@ public void exclusionChanged(ResourceExclusionEvent event) {
@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);
+ DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(
+ image,
+ Activator
+ .getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
+ IDecoration.TOP_RIGHT);
return overlayIcon.createImage();
} else {
return image;
@@ -110,6 +112,4 @@ public String decorateText(String text, Object element) {
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 6647543d..f4cb1ee1 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
@@ -35,11 +35,10 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
-
-public class AddLanguageDialoge extends Dialog{
+public class AddLanguageDialoge extends Dialog {
private Locale locale;
private Shell shell;
-
+
private Text titelText;
private Text descriptionText;
private Combo cmbLanguage;
@@ -47,116 +46,122 @@ public class AddLanguageDialoge extends Dialog{
private Text country;
private Text variant;
-
-
-
- public AddLanguageDialoge(Shell parentShell){
+ public AddLanguageDialoge(Shell parentShell) {
super(parentShell);
shell = parentShell;
}
-
+
@Override
- protected Control createDialogArea(Composite parent) {
+ 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);
+ 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.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.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.");
+ 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));
-
+ 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){
+
+ for (Locale l : locales) {
localeNames.add(l.getDisplayName());
localeSet.add(l);
}
-
+
Collections.sort(localeNames);
-
- String[] s= new String[localeNames.size()];
+
+ 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));
-
+ 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 {
+ } 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));
+
+ 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);
+
+ 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());
-
+ 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 64b7feda..6d348525 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
@@ -20,50 +20,47 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
-public class CreatePatternDialoge extends Dialog{
+public class CreatePatternDialoge extends Dialog {
private String pattern;
private Text patternText;
-
-
+
public CreatePatternDialoge(Shell shell) {
- this(shell,"");
+ this(shell, "");
}
-
+
public CreatePatternDialoge(Shell shell, String pattern) {
super(shell);
this.pattern = pattern;
-// setShellStyle(SWT.RESIZE);
+ // setShellStyle(SWT.RESIZE);
}
@Override
- protected Control createDialogArea(Composite parent) {
+ 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));
-
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
+
Label descriptionLabel = new Label(composite, SWT.NONE);
descriptionLabel.setText("Enter a regular expression:");
-
+
patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
gData.widthHint = 400;
gData.heightHint = 60;
patternText.setLayoutData(gData);
patternText.setText(pattern);
-
-
return composite;
}
@Override
protected void okPressed() {
- pattern = patternText.getText();
-
+ pattern = patternText.getText();
+
super.okPressed();
}
-
- public String getPattern(){
+
+ 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 75d865cb..643aab99 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
@@ -37,106 +37,115 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
-
public class CreateResourceBundleEntryDialog extends TitleAreaDialog {
private static int WIDTH_LEFT_COLUMN = 100;
-
+
private static final String DEFAULT_KEY = "defaultkey";
-
+
private String projectName;
-
+
private Text txtKey;
private Combo cmbRB;
private Text txtDefaultText;
private Combo cmbLanguage;
-
+
private Button okButton;
private Button cancelButton;
-
+
/*** Dialog Model ***/
String selectedRB = "";
String selectedLocale = "";
String selectedKey = "";
String selectedDefaultText = "";
-
+
/*** MODIFY LISTENER ***/
ModifyListener rbModifyListener;
-
+
public class DialogConfiguration {
String projectName;
-
+
String preselectedKey;
String preselectedMessage;
String preselectedBundle;
String preselectedLocale;
-
+
public String getProjectName() {
return projectName;
}
+
public void setProjectName(String projectName) {
this.projectName = projectName;
}
+
public String getPreselectedKey() {
return preselectedKey;
}
+
public void setPreselectedKey(String preselectedKey) {
this.preselectedKey = preselectedKey;
}
+
public String getPreselectedMessage() {
return preselectedMessage;
}
+
public void setPreselectedMessage(String preselectedMessage) {
this.preselectedMessage = preselectedMessage;
}
+
public String getPreselectedBundle() {
return preselectedBundle;
}
+
public void setPreselectedBundle(String preselectedBundle) {
this.preselectedBundle = preselectedBundle;
}
+
public String getPreselectedLocale() {
return preselectedLocale;
}
+
public void setPreselectedLocale(String preselectedLocale) {
this.preselectedLocale = preselectedLocale;
}
-
+
}
-
+
public CreateResourceBundleEntryDialog(Shell parentShell) {
super(parentShell);
}
-
+
public void setDialogConfiguration(DialogConfiguration config) {
String preselectedKey = config.getPreselectedKey();
- this.selectedKey = preselectedKey != null ? preselectedKey.trim() : preselectedKey;
+ this.selectedKey = preselectedKey != null ? preselectedKey.trim()
+ : preselectedKey;
if ("".equals(this.selectedKey)) {
this.selectedKey = DEFAULT_KEY;
}
-
+
this.selectedDefaultText = config.getPreselectedMessage();
this.selectedRB = config.getPreselectedBundle();
this.selectedLocale = config.getPreselectedLocale();
this.projectName = config.getProjectName();
}
- public String getSelectedResourceBundle () {
+ public String getSelectedResourceBundle() {
return selectedRB;
}
-
- public String getSelectedKey () {
+
+ public String getSelectedKey() {
return selectedKey;
}
-
+
@Override
protected Control createDialogArea(Composite parent) {
Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructRBSection (dialogArea);
- constructDefaultSection (dialogArea);
- initContent ();
+ initLayout(dialogArea);
+ constructRBSection(dialogArea);
+ constructDefaultSection(dialogArea);
+ initContent();
return dialogArea;
}
@@ -144,9 +153,10 @@ protected void initContent() {
cmbRB.removeAll();
int iSel = -1;
int index = 0;
-
- Collection<String> availableBundles = ResourceBundleManager.getManager(projectName).getResourceBundleNames();
-
+
+ Collection<String> availableBundles = ResourceBundleManager.getManager(
+ projectName).getResourceBundleNames();
+
for (String bundle : availableBundles) {
cmbRB.add(bundle);
if (bundle.equals(selectedRB)) {
@@ -154,17 +164,17 @@ protected void initContent() {
iSel = index;
cmbRB.setEnabled(false);
}
- index ++;
+ 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();
@@ -173,19 +183,18 @@ public void modifyText(ModifyEvent e) {
};
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();
}
@@ -193,23 +202,25 @@ public void widgetDefaultSelected(SelectionEvent e) {
updateAvailableLanguages();
validate();
}
-
- protected void updateAvailableLanguages () {
+
+ protected void updateAvailableLanguages() {
cmbLanguage.removeAll();
String selectedBundle = cmbRB.getText();
-
+
if ("".equals(selectedBundle.trim())) {
return;
}
-
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
+
+ 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();
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
if (displayName.equals(selectedLocale))
iSel = index;
if (displayName.equals(""))
@@ -219,12 +230,12 @@ protected void updateAvailableLanguages () {
cmbLanguage.select(iSel);
index++;
}
-
+
if (locales.size() > 0) {
cmbLanguage.select(0);
selectedLocale = cmbLanguage.getText();
}
-
+
cmbLanguage.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
@@ -233,126 +244,150 @@ public void modifyText(ModifyEvent e) {
}
});
}
-
+
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));
+ 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");
-
+
+ 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);
+ 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 = 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));
+ // 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));
+ 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 = 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));
+ 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.");
-
+
+ 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);
+ 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 = new Text(group, SWT.MULTI | SWT.BORDER);
txtDefaultText.setText(selectedDefaultText);
- txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
+ 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));
+ 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));
+
+ 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);
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
// Insert new Resource-Bundle reference
- Locale locale = LocaleUtils.getLocaleByDisplayName( manager.getProvidedLocales(selectedRB), selectedLocale); // new Locale(""); // retrieve locale
-
+ Locale locale = LocaleUtils.getLocaleByDisplayName(
+ manager.getProvidedLocales(selectedRB), selectedLocale); // new
+ // Locale("");
+ // //
+ // retrieve
+ // locale
+
try {
- manager.addResourceBundleEntry (selectedRB, selectedKey, locale, selectedDefaultText);
+ manager.addResourceBundleEntry(selectedRB, selectedKey, locale,
+ selectedDefaultText);
} catch (ResourceBundleException e) {
Logger.logError(e);
}
}
-
+
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
@@ -366,45 +401,47 @@ public void 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 () {
+ 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);
-
+ 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)
+ else if (!keyValidChar)
errorMessage = "The specified resource key contains invalid characters.";
- else if (! keyValid)
+ else if (!keyValid)
errorMessage = "The specified resource key is already existing.";
- else if (! rbValid)
+ else if (!rbValid)
errorMessage = "The specified Resource-Bundle does not exist.";
- else if (! localeValid)
+ else if (!localeValid)
errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
- else if (! textValid)
+ else if (!textValid)
errorMessage = "No default translation specified.";
else {
if (okButton != null)
@@ -417,26 +454,26 @@ else if (! textValid)
}
@Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
+ 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();
- }
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
});
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
+
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
+ 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 3b3513e0..6a503f64 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
@@ -24,18 +24,17 @@
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ListDialog;
-
-public class FragmentProjectSelectionDialog extends ListDialog{
+public class FragmentProjectSelectionDialog extends ListDialog {
private IProject hostproject;
private List<IProject> allProjects;
-
-
- public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, List<IProject> fragmentprojects){
+
+ public FragmentProjectSelectionDialog(Shell parent, IProject hostproject,
+ List<IProject> fragmentprojects) {
super(parent);
this.hostproject = hostproject;
this.allProjects = new ArrayList<IProject>(fragmentprojects);
- allProjects.add(0,hostproject);
-
+ allProjects.add(0, hostproject);
+
init();
}
@@ -45,7 +44,7 @@ private void init() {
this.setTitle("Project Selector");
this.setContentProvider(new IProjectContentProvider());
this.setLabelProvider(new IProjectLabelProvider());
-
+
this.setInput(allProjects);
}
@@ -56,8 +55,7 @@ public IProject getSelectedProject() {
return null;
}
-
- //private classes--------------------------------------------------------
+ // private classes--------------------------------------------------------
class IProjectContentProvider implements IStructuredContentProvider {
@Override
@@ -69,43 +67,45 @@ public Object[] getElements(Object inputElement) {
@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);
+ 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]";
+ 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
@@ -117,8 +117,8 @@ public boolean isLabelProperty(Object element, String property) {
@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 15b93f24..841c7290 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
@@ -24,10 +24,10 @@
public class GenerateBundleAccessorDialog extends TitleAreaDialog {
private static int WIDTH_LEFT_COLUMN = 100;
-
+
private Text bundleAccessor;
private Text packageName;
-
+
public GenerateBundleAccessorDialog(Shell parentShell) {
super(parentShell);
}
@@ -35,10 +35,10 @@ public GenerateBundleAccessorDialog(Shell parentShell) {
@Override
protected Control createDialogArea(Composite parent) {
Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructBASection (dialogArea);
- //constructDefaultSection (dialogArea);
- initContent ();
+ initLayout(dialogArea);
+ constructBASection(dialogArea);
+ // constructDefaultSection (dialogArea);
+ initContent();
return dialogArea;
}
@@ -48,93 +48,99 @@ protected void initLayout(Composite parent) {
}
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));
+ 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.");
-
+
+ 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);
+ 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));
-
+
+ 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));
+ 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));
+
+ packageName = new Text(group, SWT.BORDER);
+ packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ true, false, 1, 1));
}
-
- protected void initContent () {
+
+ 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));
- } */
+ * 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 3a0abf24..8f105f67 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
@@ -37,38 +37,37 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
-
public class QueryResourceBundleEntryDialog extends TitleAreaDialog {
private static int WIDTH_LEFT_COLUMN = 100;
private static int SEARCH_FULLTEXT = 0;
private static int SEARCH_KEY = 1;
-
+
private ResourceBundleManager manager;
private Collection<String> availableBundles;
- private int searchOption = SEARCH_FULLTEXT;
+ private 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) {
+
+ public QueryResourceBundleEntryDialog(Shell parentShell,
+ ResourceBundleManager manager, String bundleName) {
super(parentShell);
this.manager = manager;
// init available resource bundles
@@ -77,11 +76,11 @@ public QueryResourceBundleEntryDialog(Shell parentShell, ResourceBundleManager m
}
@Override
- protected Control createDialogArea(Composite parent) {
+ protected Control createDialogArea(Composite parent) {
Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructSearchSection (dialogArea);
- initContent ();
+ initLayout(dialogArea);
+ constructSearchSection(dialogArea);
+ initContent();
return dialogArea;
}
@@ -97,60 +96,63 @@ protected void initContent() {
}
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 ();
+ // updateAvailableLanguages();
+ updateResourceSelector();
}
-
+
@Override
public void widgetDefaultSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
+ // updateAvailableLanguages();
+ updateResourceSelector();
}
});
-
+
// init available translations
- //updateAvailableLanguages();
-
+ // updateAvailableLanguages();
+
// init resource selector
updateResourceSelector();
-
+
// update search options
updateSearchOptions();
}
-
- protected void updateResourceSelector () {
+
+ 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());
-
+
+ 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);
+ resourceSelector
+ .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
+ : ResourceSelector.DISPLAY_KEYS);
}
-
- protected void updateAvailableLanguages () {
+
+ 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) {
@@ -159,19 +161,19 @@ protected void updateAvailableLanguages () {
displayName = ResourceBundleManager.defaultLocaleTag;
cmbLanguage.add(displayName);
}
-
-// if (locales.size() > 0) {
-// cmbLanguage.select(0);
- updateSelectedLocale();
-// }
+
+ // if (locales.size() > 0) {
+ // cmbLanguage.select(0);
+ updateSelectedLocale();
+ // }
}
-
- protected void 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();
@@ -183,17 +185,18 @@ protected void updateSelectedLocale () {
}
}
}
-
+
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));
+
+ 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;
@@ -201,149 +204,168 @@ protected void constructSearchSection (Composite parent) {
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);
+
+ 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.");
-
+ 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));
+ 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() {
+
+ 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));
-
+ 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);
+ 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 = 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();
-// }
-// });
+ // 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);
+ 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));
-
+
+ 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));
+ 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 = 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);
+
+ 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));
-
+ 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);
+ 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);
+ 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);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1);
txtPreviewText.setLayoutData(lblTextGrid2);
}
@@ -352,7 +374,7 @@ protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Insert Resource-Bundle-Reference");
}
-
+
@Override
public void create() {
// TODO Auto-generated method stub
@@ -361,36 +383,37 @@ public void create() {
this.setMessage("Please, specify details about the required Resource-Bundle reference");
}
- protected void updatePreviewLabel (String previewText) {
+ protected void updatePreviewLabel(String previewText) {
txtPreviewText.setText(previewText);
}
-
- protected void validate () {
+
+ 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)
+
+ if (selectedLocale != null)
localeValid = true;
-
+
if (manager.isResourceExisting(selectedRB, selectedKey))
keyValid = true;
-
+
// print Validation summary
String errorMessage = null;
- if (! rbValid)
+ 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)
+ // 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)
@@ -403,37 +426,37 @@ else if (! keyValid)
}
@Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
+ 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();
- }
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
});
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
+
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
+ setReturnCode(CANCEL);
close();
}
});
-
+
okButton.setEnabled(false);
cancelButton.setEnabled(true);
}
-
- public String getSelectedResourceBundle () {
+
+ public String getSelectedResourceBundle() {
return selectedRB;
}
-
- public String getSelectedResource () {
+
+ public String getSelectedResource() {
return selectedKey;
}
-
- public Locale getSelectedLocale () {
+
+ 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 f8aab884..4236bc9c 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
@@ -24,37 +24,36 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ListDialog;
-
-public class RemoveLanguageDialoge extends ListDialog{
+public class RemoveLanguageDialoge extends ListDialog {
private IProject project;
-
public RemoveLanguageDialoge(IProject project, Shell shell) {
super(shell);
- this.project=project;
-
+ this.project = project;
+
initDialog();
}
- protected void 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());
+
+ 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-------------------------------------------------------------------------------------
+
+ // private
+ // classes-------------------------------------------------------------------------------------
class RBContentProvider implements IStructuredContentProvider {
@Override
@@ -66,17 +65,17 @@ public Object[] getElements(Object inputElement) {
@Override
public void dispose() {
// TODO Auto-generated method stub
-
+
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// TODO Auto-generated method stub
-
+
}
-
+
}
-
+
class RBLabelProvider implements ILabelProvider {
@Override
@@ -88,21 +87,24 @@ public Image getImage(Object element) {
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();
+ 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
@@ -114,8 +116,8 @@ public boolean isLabelProperty(Object element, String property) {
@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 77fd50fa..81aeda92 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
@@ -36,47 +36,45 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
-
public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog {
private static int WIDTH_LEFT_COLUMN = 100;
private static int SEARCH_FULLTEXT = 0;
private static int SEARCH_KEY = 1;
-
+
private String projectName;
private String bundleName;
-
- private int searchOption = SEARCH_FULLTEXT;
+
+ private 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) {
+ protected Control createDialogArea(Composite parent) {
Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructSearchSection (dialogArea);
- initContent ();
+ initLayout(dialogArea);
+ constructSearchSection(dialogArea);
+ initContent();
return dialogArea;
}
@@ -84,7 +82,8 @@ protected void initContent() {
// init available resource bundles
cmbRB.removeAll();
int i = 0;
- for (String bundle : ResourceBundleManager.getManager(projectName).getResourceBundleNames()) {
+ for (String bundle : ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames()) {
cmbRB.add(bundle);
if (bundle.equals(preselectedRB)) {
cmbRB.select(i);
@@ -92,82 +91,88 @@ protected void initContent() {
}
i++;
}
-
- if (ResourceBundleManager.getManager(projectName).getResourceBundleNames().size() > 0) {
+
+ 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 ();
+ // updateAvailableLanguages();
+ updateResourceSelector();
}
-
+
@Override
public void widgetDefaultSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
+ // updateAvailableLanguages();
+ updateResourceSelector();
}
});
-
+
// init available translations
- //updateAvailableLanguages();
-
+ // updateAvailableLanguages();
+
// init resource selector
updateResourceSelector();
-
+
// update search options
updateSearchOptions();
}
-
- protected void updateResourceSelector () {
+
+ 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());
-
+
+ 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);
+ resourceSelector
+ .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
+ : ResourceSelector.DISPLAY_KEYS);
}
-
- protected void updateAvailableLanguages () {
+
+ 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);
+ 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();
-// }
+
+ // if (locales.size() > 0) {
+ // cmbLanguage.select(0);
+ updateSelectedLocale();
+ // }
}
-
- protected void updateSelectedLocale () {
+
+ protected void updateSelectedLocale() {
String selectedBundle = cmbRB.getText();
-
+
if (selectedBundle.trim().equals(""))
return;
-
- Set<Locale> locales = ResourceBundleManager.getManager(projectName).getProvidedLocales(selectedBundle);
+
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName)
+ .getProvidedLocales(selectedBundle);
Iterator<Locale> it = locales.iterator();
String selectedLocale = cmbLanguage.getText();
while (it.hasNext()) {
@@ -178,17 +183,18 @@ protected void updateSelectedLocale () {
}
}
}
-
+
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));
+
+ 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;
@@ -196,149 +202,168 @@ protected void constructSearchSection (Composite parent) {
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);
+
+ 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.");
-
+ 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));
+ 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() {
+
+ 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));
-
+ 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);
+ 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 = 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();
-// }
-// });
+ // 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));
-
+ // 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));
+ 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 = 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);
+
+ 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));
-
+ 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);
+ 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);
+ 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);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1);
txtPreviewText.setLayoutData(lblTextGrid2);
}
@@ -347,7 +372,7 @@ protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Select Resource-Bundle entry");
}
-
+
@Override
public void create() {
// TODO Auto-generated method stub
@@ -356,36 +381,39 @@ public void create() {
this.setMessage("Please, select a resource of a particular Resource-Bundle");
}
- protected void updatePreviewLabel (String previewText) {
+ protected void updatePreviewLabel(String previewText) {
txtPreviewText.setText(previewText);
}
-
- protected void validate () {
+
+ protected void validate() {
// Check Resource-Bundle ids
boolean rbValid = false;
boolean localeValid = false;
boolean keyValid = false;
-
- for (String rbId : ResourceBundleManager.getManager(projectName).getResourceBundleNames()) {
+
+ for (String rbId : ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames()) {
if (rbId.equals(selectedRB)) {
rbValid = true;
break;
}
}
-
- if (selectedLocale != null)
+
+ if (selectedLocale != null)
localeValid = true;
-
- if (ResourceBundleManager.getManager(projectName).isResourceExisting(selectedRB, selectedKey))
+
+ if (ResourceBundleManager.getManager(projectName).isResourceExisting(
+ selectedRB, selectedKey))
keyValid = true;
-
+
// print Validation summary
String errorMessage = null;
- if (! rbValid)
+ 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)
+ // 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)
@@ -398,47 +426,47 @@ else if (! keyValid)
}
@Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
+ 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();
- }
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
});
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
+
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
+ setReturnCode(CANCEL);
close();
}
});
-
+
okButton.setEnabled(false);
cancelButton.setEnabled(true);
}
-
- public String getSelectedResourceBundle () {
+
+ public String getSelectedResourceBundle() {
return selectedRB;
}
-
- public String getSelectedResource () {
+
+ public String getSelectedResource() {
return selectedKey;
}
-
- public Locale getSelectedLocale () {
+
+ 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 809da51d..9386e9d0 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
@@ -23,39 +23,39 @@
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ListDialog;
-
public class ResourceBundleSelectionDialog extends ListDialog {
private IProject project;
-
+
public ResourceBundleSelectionDialog(Shell parent, IProject project) {
super(parent);
this.project = project;
-
- initDialog ();
+
+ initDialog();
}
-
- protected void 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());
+ this.setInput(RBManager.getInstance(project)
+ .getMessagesBundleGroupNames());
else
this.setInput(RBManager.getAllMessagesBundleGroupNames());
}
-
- public String getSelectedBundleId () {
+
+ public String getSelectedBundleId() {
Object[] selection = this.getResult();
if (selection != null && selection.length > 0)
return (String) selection[0];
return null;
}
-
+
class RBContentProvider implements IStructuredContentProvider {
@Override
@@ -67,17 +67,17 @@ public Object[] getElements(Object inputElement) {
@Override
public void dispose() {
// TODO Auto-generated method stub
-
+
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// TODO Auto-generated method stub
-
+
}
-
+
}
-
+
class RBLabelProvider implements ILabelProvider {
@Override
@@ -95,13 +95,13 @@ public String getText(Object element) {
@Override
public void addListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
-
+
}
@Override
public void dispose() {
// TODO Auto-generated method stub
-
+
}
@Override
@@ -113,8 +113,8 @@ public boolean isLabelProperty(Object element, String property) {
@Override
public void removeListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
-
+
}
-
+
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
index 2478c658..13f6408d 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
@@ -17,7 +17,7 @@
public class PropertiesFileFilter extends ViewerFilter {
private boolean debugEnabled = true;
-
+
public PropertiesFileFilter() {
}
@@ -26,15 +26,15 @@ public PropertiesFileFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (debugEnabled)
return true;
-
+
if (element.getClass().getSimpleName().equals("CompilationUnit"))
return false;
-
+
if (!(element instanceof IFile))
return true;
-
+
IFile file = (IFile) element;
-
+
return file.getFileExtension().equalsIgnoreCase("properties");
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
index c4920bab..519021f4 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
@@ -17,8 +17,8 @@
import org.eclipse.jface.text.Position;
import org.eclipse.ui.texteditor.IMarkerUpdater;
-public class MarkerUpdater implements IMarkerUpdater {
-
+public class MarkerUpdater implements IMarkerUpdater {
+
@Override
public String getMarkerType() {
return "org.eclipse.core.resources.problemmarker";
@@ -32,16 +32,16 @@ public String[] getAttribute() {
@Override
public boolean updateMarker(IMarker marker, IDocument document,
- Position position) {
+ 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;
- }
+ 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/menus/InternationalizationMenu.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
index deee5816..435179dc 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
@@ -51,17 +51,17 @@
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;
-
public class InternationalizationMenu extends ContributionItem {
private boolean excludeMode = true;
private boolean internationalizationEnabled = false;
-
+
private MenuItem mnuToggleInt;
private MenuItem excludeResource;
private MenuItem addLanguage;
private MenuItem removeLanguage;
-
- public InternationalizationMenu() {}
+
+ public InternationalizationMenu() {
+ }
public InternationalizationMenu(String id) {
super(id);
@@ -69,13 +69,12 @@ public InternationalizationMenu(String id) {
@Override
public void fill(Menu menu, int index) {
- if (getSelectedProjects().size() == 0 ||
- !projectsSupported())
+ if (getSelectedProjects().size() == 0 || !projectsSupported())
return;
-
+
// Toggle Internatinalization
- mnuToggleInt = new MenuItem (menu, SWT.PUSH);
- mnuToggleInt.addSelectionListener(new SelectionAdapter () {
+ mnuToggleInt = new MenuItem(menu, SWT.PUSH);
+ mnuToggleInt.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
@@ -83,10 +82,10 @@ public void widgetSelected(SelectionEvent e) {
}
});
-
+
// Exclude Resource
- excludeResource = new MenuItem (menu, SWT.PUSH);
- excludeResource.addSelectionListener(new SelectionAdapter () {
+ excludeResource = new MenuItem(menu, SWT.PUSH);
+ excludeResource.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
@@ -94,97 +93,101 @@ public void widgetSelected(SelectionEvent e) {
}
});
-
+
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
+
+ // Remove Language
removeLanguage = new MenuItem(menu, SWT.PUSH);
removeLanguage.addSelectionListener(new SelectionAdapter() {
-
+
@Override
public void widgetSelected(SelectionEvent e) {
runRemoveLanguage();
}
-
+
});
-
- menu.addMenuListener(new MenuAdapter () {
- public void menuShown (MenuEvent e) {
- updateStateToggleInt (mnuToggleInt);
- //updateStateGenRBAccessor (generateAccessor);
- updateStateExclude (excludeResource);
- updateStateAddLanguage (addLanguage);
- updateStateRemoveLanguage (removeLanguage);
+
+ menu.addMenuListener(new MenuAdapter() {
+ public void menuShown(MenuEvent e) {
+ updateStateToggleInt(mnuToggleInt);
+ // updateStateGenRBAccessor (generateAccessor);
+ updateStateExclude(excludeResource);
+ updateStateAddLanguage(addLanguage);
+ updateStateRemoveLanguage(removeLanguage);
}
});
}
- protected void runGenRBAccessor () {
- GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(Display.getDefault().getActiveShell());
+ protected void runGenRBAccessor() {
+ GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(
+ Display.getDefault().getActiveShell());
if (dlg.open() != InputDialog.OK)
return;
}
-
- protected void updateStateGenRBAccessor (MenuItem menuItem) {
+
+ protected void updateStateGenRBAccessor(MenuItem menuItem) {
Collection<IPackageFragment> frags = getSelectedPackageFragments();
menuItem.setEnabled(frags.size() > 0);
}
-
- protected void updateStateToggleInt (MenuItem menuItem) {
+
+ 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);
-
+ internationalizationEnabled = InternationalizationNature
+ .hasNature(projects.iterator().next());
+ // menuItem.setSelection(enabled && internationalizationEnabled);
+
if (internationalizationEnabled)
menuItem.setText("Disable Internationalization");
- else
+ 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 ();
+ 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();) {
+ 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);
+ 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 ();
+
+ 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();) {
+ 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);
+ elem = ((IAdaptable) elem).getAdapter(IResource.class);
if (!(elem instanceof IResource))
continue;
}
@@ -193,44 +196,45 @@ private Collection<IProject> getSelectedProjects () {
if (!(elem instanceof IProject))
continue;
}
- if (((IProject)elem).isAccessible())
- projects.add ((IProject)elem);
-
+ if (((IProject) elem).isAccessible())
+ projects.add((IProject) elem);
+
}
}
return projects;
}
-
+
protected boolean projectsSupported() {
- Collection<IProject> projects = getSelectedProjects ();
+ Collection<IProject> projects = getSelectedProjects();
for (IProject project : projects) {
if (!InternationalizationNature.supportsNature(project))
return false;
}
-
+
return true;
}
-
- protected void runToggleInt () {
- Collection<IProject> projects = getSelectedProjects ();
+
+ protected void runToggleInt() {
+ Collection<IProject> projects = getSelectedProjects();
for (IProject project : projects) {
- toggleNature (project);
+ toggleNature(project);
}
}
-
- private void toggleNature (IProject project) {
- if (InternationalizationNature.hasNature (project)) {
- InternationalizationNature.removeNature (project);
+
+ private void toggleNature(IProject project) {
+ if (InternationalizationNature.hasNature(project)) {
+ InternationalizationNature.removeNature(project);
} else {
- InternationalizationNature.addNature (project);
+ InternationalizationNature.addNature(project);
}
- }
- protected void updateStateExclude (MenuItem menuItem) {
+ }
+
+ 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());
@@ -238,51 +242,56 @@ protected void updateStateExclude (MenuItem menuItem) {
if (!ResourceBundleManager.isResourceExcluded(res)) {
excludeMode = true;
}
- } catch (Exception e) { }
+ } catch (Exception e) {
+ }
}
-
+
if (!excludeMode)
menuItem.setText("Include Resource");
- else
+ 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 ();
+
+ 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();) {
+ 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);
+ resources.add((IResource) elem);
} else if (elem instanceof IJavaElement) {
- resources.add (((IJavaElement)elem).getResource());
+ resources.add(((IJavaElement) elem).getResource());
}
}
}
return resources;
}
-
- protected void runExclude () {
- final Collection<IResource> selectedResources = getSelectedResources ();
-
+
+ protected void runExclude() {
+ final Collection<IResource> selectedResources = getSelectedResources();
+
IWorkbench wb = PlatformUI.getWorkbench();
IProgressService ps = wb.getProgressService();
try {
ps.busyCursorWhile(new IRunnableWithProgress() {
public void run(IProgressMonitor pm) {
-
+
ResourceBundleManager manager = null;
- pm.beginTask("Including resources to Internationalization", selectedResources.size());
-
+ 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 (manager == null
+ || (manager.getProject() != res.getProject()))
+ manager = ResourceBundleManager.getManager(res
+ .getProject());
if (excludeMode)
manager.excludeResource(res, pm);
else
@@ -292,92 +301,112 @@ public void run(IProgressMonitor pm) {
pm.done();
}
});
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
- protected void updateStateAddLanguage(MenuItem menuItem){
+ 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;
+ 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()));
+
+ 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);
+
+ 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);
-
+ Display.getCurrent().getActiveShell(), project,
+ fragments);
+
if (fragmentDialog.open() == InputDialog.OK)
project = fragmentDialog.getSelectedProject();
}
-
+
final IProject selectedProject = project;
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
@Override
public void run() {
- LanguageUtils.addLanguageToProject(selectedProject, locale);
+ LanguageUtils.addLanguageToProject(selectedProject,
+ locale);
}
-
+
});
-
+
}
}
}
-
-
+
protected void updateStateRemoveLanguage(MenuItem menuItem) {
Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles=false;
- if (projects.size() == 1){
+ boolean hasResourceBundles = false;
+ if (projects.size() == 1) {
IProject project = projects.iterator().next();
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(project);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
+ 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*/);
+ 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()));
-
-
+ RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project,
+ new Shell(Display.getCurrent()));
+
if (dialog.open() == InputDialog.OK) {
final Locale locale = dialog.getSelectedLanguage();
- if (locale != null) {
- if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirm", "Do you really want remove all properties-files for "+locale.getDisplayName()+"?"))
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- LanguageUtils.removeLanguageFromProject(project, locale);
- }
- });
-
+ if (locale != null) {
+ if (MessageDialog.openConfirm(Display.getCurrent()
+ .getActiveShell(), "Confirm",
+ "Do you really want remove all properties-files for "
+ + locale.getDisplayName() + "?"))
+ BusyIndicator.showWhile(Display.getCurrent(),
+ new Runnable() {
+ @Override
+ public void run() {
+ LanguageUtils.removeLanguageFromProject(
+ project, locale);
+ }
+ });
+
}
}
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
index 961f1ac7..6c884d14 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
@@ -27,9 +27,9 @@
import org.eclipse.ui.IWorkbenchPreferencePage;
public class BuilderPreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
private static final int INDENT = 20;
-
+
private Button checkSameValueButton;
private Button checkMissingValueButton;
private Button checkMissingLanguageButton;
@@ -37,8 +37,7 @@ public class BuilderPreferencePage extends PreferencePage implements
private Button rbAuditButton;
private Button sourceAuditButton;
-
-
+
@Override
public void init(IWorkbench workbench) {
setPreferenceStore(Activator.getDefault().getPreferenceStore());
@@ -49,87 +48,106 @@ protected Control createContents(Composite parent) {
IPreferenceStore prefs = getPreferenceStore();
Composite composite = new Composite(parent, SWT.SHADOW_OUT);
- composite.setLayout(new GridLayout(1,false));
+ 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");
-
+ 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
+ .setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
+ rbAuditButton
+ .setText("Check ResourceBundles on the following problems:");
rbAuditButton.addSelectionListener(new SelectionAdapter() {
- @Override
+ @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.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");
-
+ 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");
-
+ 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));
+
+ 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_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());
-
+ 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) {
+
+ 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);
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
index eac76165..ef4f5d1d 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
@@ -37,17 +37,18 @@
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
-public class FilePreferencePage extends PreferencePage implements 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());
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
}
@Override
@@ -55,87 +56,100 @@ protected Control createContents(Composite parent) {
IPreferenceStore prefs = getPreferenceStore();
Composite composite = new Composite(parent, SWT.SHADOW_OUT);
- composite.setLayout(new GridLayout(2,false));
+ 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;
+ 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);
+ 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){
+ if (selection.length > 0) {
editPatternButton.setEnabled(true);
removePatternButton.setEnabled(true);
- }else{
+ } 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){
+
+ List<CheckItem> patternItems = TapiJIPreferences
+ .getNonRbPatternAsList();
+ for (CheckItem s : patternItems) {
s.toTableItem(table);
}
-
+
Composite sitebar = new Composite(composite, SWT.NONE);
- sitebar.setLayout(new GridLayout(1,false));
+ sitebar.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.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);
+ 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);
+
+ 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.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){
+ if (selection.length > 0) {
String pattern = selection[0].getText();
-
- CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(), pattern);
+
+ CreatePatternDialoge dialog = new CreatePatternDialoge(
+ Display.getDefault().getActiveShell(), pattern);
if (dialog.open() == InputDialog.OK) {
pattern = dialog.getPattern();
TableItem item = selection[0];
@@ -143,60 +157,65 @@ public void mouseDown(MouseEvent e) {
}
}
}
+
@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.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
+ true));
removePatternButton.setText("Remove");
removePatternButton.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
// TODO Auto-generated method stub
}
+
@Override
public void mouseDown(MouseEvent e) {
TableItem[] selection = table.getSelection();
if (selection.length > 0)
table.remove(table.indexOf(selection[0]));
}
+
@Override
public void mouseDoubleClick(MouseEvent e) {
// TODO Auto-generated method stub
}
});
-
+
composite.pack();
-
+
return composite;
}
@Override
protected void performDefaults() {
IPreferenceStore prefs = getPreferenceStore();
-
+
table.removeAll();
-
- List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs.getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
- for (CheckItem s : patterns){
+
+ List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs
+ .getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
+ for (CheckItem s : patterns) {
s.toTableItem(table);
}
}
-
+
@Override
public boolean performOk() {
IPreferenceStore prefs = getPreferenceStore();
- List<CheckItem> patterns =new LinkedList<CheckItem>();
- for (TableItem i : table.getItems()){
+ 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));
-
+
+ prefs.setValue(TapiJIPreferences.NON_RB_PATTERN,
+ TapiJIPreferences.convertListToString(patterns));
+
return super.performOk();
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
index 149ded96..412c782b 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
@@ -21,7 +21,7 @@
import org.eclipse.ui.IWorkbenchPreferencePage;
public class TapiHomePreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
@Override
public void init(IWorkbench workbench) {
@@ -32,12 +32,12 @@ public void init(IWorkbench workbench) {
@Override
protected Control createContents(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1,true));
+ composite.setLayout(new GridLayout(1, true));
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
+
Label description = new Label(composite, SWT.WRAP);
description.setText("See sub-pages for settings.");
-
+
return parent;
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/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 0608f27e..ce9f7485 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
@@ -54,8 +54,8 @@
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.UIJob;
-
-public class MessagesView extends ViewPart implements IResourceBundleChangedListener {
+public class MessagesView extends ViewPart implements
+ IResourceBundleChangedListener {
/**
* The ID of the view as specified by the extension.
@@ -65,124 +65,129 @@ public class MessagesView extends ViewPart implements IResourceBundleChangedList
// View State
private IMemento memento;
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.
+ * 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);
+
+ initLayout(parent);
+ initSearchBar(parent);
+ initMessagesTree(parent);
makeActions();
hookContextMenu();
contributeToActionBars();
- initListener (parent);
+ initListener(parent);
}
-
- protected void initListener (Composite 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 ();
+
+ protected void initLayout(Composite parent) {
+ GridLayout mainLayout = new GridLayout();
mainLayout.numColumns = 1;
parent.setLayout(mainLayout);
-
+
}
-
- protected void initSearchBar (Composite parent) {
+
+ 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);
+ 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);
+
+ 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));
+ 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 = 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;
+ // gdScaler.widthHint = 150;
lblScale.setLayoutData(gdScaler);
-
+
// Add a scale for specification of fuzzy Matching precision
- fuzzyScaler = new Scale (parentComp, SWT.None);
+ 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
+ .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;
@@ -190,44 +195,52 @@ public void handleEvent (Event event) {
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;
+
+ 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;
+ ((GridData) lblScale.getLayoutData()).heightHint = 0;
+ ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0;
}
lblScale.getParent().layout();
lblScale.getParent().getParent().layout();
}
-
+
protected void initMessagesTree(Composite parent) {
- if (viewState.getSelectedProjectName() != null && viewState.getSelectedProjectName().trim().length() > 0 ) {
+ if (viewState.getSelectedProjectName() != null
+ && viewState.getSelectedProjectName().trim().length() > 0) {
try {
- ResourceBundleManager.getManager(viewState.getSelectedProjectName())
- .registerResourceBundleChangeListener(viewState.getSelectedBundleId(), this);
-
- } catch (Exception e) {}
+ ResourceBundleManager.getManager(
+ viewState.getSelectedProjectName())
+ .registerResourceBundleChangeListener(
+ viewState.getSelectedBundleId(), this);
+
+ } catch (Exception e) {
+ }
}
- treeViewer = new PropertyKeySelectionTree(getViewSite(), getSite(), parent, SWT.NONE,
- viewState.getSelectedProjectName(), viewState.getSelectedBundleId(),
- viewState.getVisibleLocales());
- if (viewState.getSelectedProjectName() != null && viewState.getSelectedProjectName().trim().length() > 0 ) {
+ 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());
}
@@ -246,8 +259,8 @@ protected void initMessagesTree(Composite parent) {
public void setFocus() {
treeViewer.setFocus();
}
-
- protected void redrawTreeViewer () {
+
+ protected void redrawTreeViewer() {
parent.setRedraw(false);
treeViewer.dispose();
try {
@@ -263,19 +276,20 @@ protected void redrawTreeViewer () {
treeViewer.layout(true);
refreshSearchbarState();
}
-
+
/*** ACTIONS ***/
- private void makeVisibleLocalesActions () {
- if (viewState.getSelectedProjectName() == null) {
- return;
- }
-
+ private void makeVisibleLocalesActions() {
+ if (viewState.getSelectedProjectName() == null) {
+ return;
+ }
+
visibleLocaleActions = new ArrayList<Action>();
Set<Locale> locales = ResourceBundleManager.getManager(
- viewState.getSelectedProjectName()).getProvidedLocales(viewState.getSelectedBundleId());
+ viewState.getSelectedProjectName()).getProvidedLocales(
+ viewState.getSelectedBundleId());
List<Locale> visibleLocales = treeViewer.getVisibleLocales();
for (final Locale locale : locales) {
- Action langAction = new Action () {
+ Action langAction = new Action() {
@Override
public void run() {
@@ -291,7 +305,7 @@ public void run() {
viewState.setVisibleLocales(visibleL);
redrawTreeViewer();
}
-
+
};
if (locale != null && locale.getDisplayName().trim().length() > 0) {
langAction.setText(locale.getDisplayName(Locale.US));
@@ -302,23 +316,26 @@ public void run() {
visibleLocaleActions.add(langAction);
}
}
-
+
private void makeActions() {
makeVisibleLocalesActions();
-
- selectResourceBundle = new Action () {
+
+ selectResourceBundle = new Action() {
@Override
public void run() {
super.run();
- ResourceBundleSelectionDialog sd = new ResourceBundleSelectionDialog (getViewSite().getShell(), null);
+ 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.setSelectedProjectName(resourceBundle
+ .substring(0, iSep));
+ viewState.setSelectedBundleId(resourceBundle
+ .substring(iSep + 1));
viewState.setVisibleLocales(null);
redrawTreeViewer();
setTitleToolTip(resourceBundle);
@@ -326,28 +343,35 @@ public void run() {
}
}
};
-
+
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 () {
+ 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());
+ treeViewer.enableFuzzyMatching(!treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
refreshSearchbarState();
}
};
enableFuzzyMatching.setText("Fuzzy-Matching");
- enableFuzzyMatching.setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
+ enableFuzzyMatching
+ .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled());
- enableFuzzyMatching.setToolTipText(enableFuzzyMatching.getDescription());
-
- editable = new Action () {
- public void run () {
+ enableFuzzyMatching
+ .setToolTipText(enableFuzzyMatching.getDescription());
+
+ editable = new Action() {
+ public void run() {
super.run();
treeViewer.setEditable(!treeViewer.isEditable());
viewState.setEditable(treeViewer.isEditable());
@@ -358,25 +382,26 @@ public void run () {
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;
-
+
+ if (visibleLocaleActions == null)
+ return;
+
for (Action loc : visibleLocaleActions) {
manager.add(loc);
}
@@ -384,7 +409,7 @@ private void fillLocalPullDown(IMenuManager manager) {
/*** CONTEXT MENU ***/
private void hookContextMenu() {
- new UIJob("set PopupMenu"){
+ new UIJob("set PopupMenu") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
MenuManager menuMgr = new MenuManager("#PopupMenu");
@@ -394,54 +419,59 @@ public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
- Menu menu = menuMgr.createContextMenu(treeViewer.getViewer().getControl());
+ Menu menu = menuMgr.createContextMenu(treeViewer.getViewer()
+ .getControl());
treeViewer.getViewer().getControl().setMenu(menu);
- getViewSite().registerContextMenu(menuMgr, treeViewer.getViewer());
-
+ 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 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));
+ // manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
-
+
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(selectResourceBundle);
}
-
+
@Override
- public void saveState (IMemento memento) {
+ public void saveState(IMemento memento) {
super.saveState(memento);
try {
- viewState.setEditable (treeViewer.isEditable());
+ viewState.setEditable(treeViewer.isEditable());
viewState.setSortings(treeViewer.getSortInfo());
viewState.setSearchString(treeViewer.getSearchString());
- viewState.setFuzzyMatchingEnabled(treeViewer.isFuzzyMatchingEnabled());
- viewState.setMatchingPrecision (treeViewer.getMatchingPrecision());
+ viewState.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setMatchingPrecision(treeViewer.getMatchingPrecision());
viewState.saveState(memento);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
this.memento = memento;
-
+
// init Viewstate
viewState = new MessagesViewState(null, null, false, null);
viewState.init(memento);
@@ -452,73 +482,80 @@ 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) {}
+ /*
+ * 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) {
}
-
- 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 ) {
+ }
+ viewState = new MessagesViewState(null, null, false, null);
+
+ new Thread(new Runnable() {
+
+ public void run() {
try {
- ResourceBundleManager.getManager(viewState.getSelectedProjectName())
- .unregisterResourceBundleChangeListener(viewState.getSelectedBundleId(), this);
-
- } catch (Exception e) {}
+ Thread.sleep(500);
+ } catch (Exception e) {
+ }
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ try {
+ redrawTreeViewer();
+ } catch (Exception e) {
+ Logger.logError(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();
+ }).start();
}
} catch (Exception e) {
Logger.logError(e);
}
}
-
+
@Override
- public void dispose(){
+ public void dispose() {
try {
super.dispose();
treeViewer.dispose();
- ResourceBundleManager.getManager(viewState.getSelectedProjectName()).unregisterResourceBundleChangeListener(viewState.getSelectedBundleId(), this);
- } catch (Exception e) {}
+ 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/ResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
index 7ac8c942..95c37640 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
@@ -23,9 +23,8 @@
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
-
public class ResourceBundleEntry extends ContributionItem implements
- ISelectionChangedListener {
+ ISelectionChangedListener {
private PropertyKeySelectionTree parentView;
private ISelection selection;
@@ -39,9 +38,10 @@ public class ResourceBundleEntry extends ContributionItem implements
public ResourceBundleEntry() {
}
- public ResourceBundleEntry(PropertyKeySelectionTree view, ISelection selection) {
+ public ResourceBundleEntry(PropertyKeySelectionTree view,
+ ISelection selection) {
this.selection = selection;
- this.legalSelection = ! selection.isEmpty();
+ this.legalSelection = !selection.isEmpty();
this.parentView = view;
parentView.addSelectionChangedListener(this);
}
@@ -53,17 +53,17 @@ public void fill(Menu menu, int index) {
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() {
-
+ .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) {
-
+
}
});
@@ -72,15 +72,15 @@ public void widgetDefaultSelected(SelectionEvent e) {
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) {
-
+
}
});
@@ -88,18 +88,18 @@ public void widgetDefaultSelected(SelectionEvent e) {
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() {
-
+ .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();
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 ff911693..e3b6b704 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
@@ -32,127 +32,147 @@
public class KeyTreeItemDropTarget extends DropTargetAdapter {
private final TreeViewer target;
-
- public KeyTreeItemDropTarget (TreeViewer viewer) {
+
+ 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;
+
+ 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());
+
+ 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);
- }
-
+
+ if (messages.length == 0) {
+ bundleGroup.addMessages(newKey);
+ }
+
for (IKeyTreeNode childs : children.getChildren()) {
- addBundleEntries(keyPrefix+"."+key, childs, bundleGroup);
+ addBundleEntries(keyPrefix + "." + key, childs, bundleGroup);
}
-
- } catch (Exception e) { Logger.logError(e); }
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
-
- private void remBundleEntries(IKeyTreeNode children, IMessagesBundleGroup group) {
+
+ private void remBundleEntries(IKeyTreeNode children,
+ IMessagesBundleGroup group) {
String key = children.getMessageKey();
-
+
for (IKeyTreeNode childs : children.getChildren()) {
remBundleEntries(childs, group);
}
-
+
group.removeMessagesAddParentKey(key);
}
-
- public void drop (final DropTargetEvent event) {
+
+ 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();
+ 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 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();
-
+
+ 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
+ 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()) {
+ 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();
-
+
+ IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey);
+
+ IMessagesBundleGroup bundleGroup = contentProvider
+ .getBundle();
+
DirtyHack.setFireEnabled(false);
- DirtyHack.setEditorModificationEnabled(false); // editor won't get dirty
-
+ 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
+ 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);
+ 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);
- }
- }
- });
+
+ } 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 6d7a9903..29c20008 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
@@ -37,7 +37,7 @@ public static KeyTreeItemTransfer getInstance() {
}
public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
+ if (!checkType(object) || !isSupportedType(transferData)) {
DND.error(DND.ERROR_INVALID_DATA);
}
IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
@@ -49,7 +49,7 @@ public void javaToNative(Object object, TransferData transferData) {
}
byte[] buffer = out.toByteArray();
oOut.close();
-
+
super.javaToNative(buffer, transferData);
} catch (IOException e) {
Logger.logError(e);
@@ -73,10 +73,10 @@ public Object nativeToJava(TransferData transferData) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(buffer);
ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
+ // while (readIn.available() > 0) {
IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
- terms.add(newTerm);
- //}
+ terms.add(newTerm);
+ // }
readIn.close();
} catch (Exception ex) {
Logger.logError(ex);
@@ -98,7 +98,7 @@ protected int[] getTypeIds() {
boolean checkType(Object object) {
if (object == null || !(object instanceof IKeyTreeNode[])
- || ((IKeyTreeNode[]) object).length == 0) {
+ || ((IKeyTreeNode[]) object).length == 0) {
return false;
}
IKeyTreeNode[] myTypes = (IKeyTreeNode[]) 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 2ad16188..8ed89aea 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
@@ -20,27 +20,29 @@ public class MessagesDragSource implements DragSourceListener {
private final TreeViewer source;
private String bundleId;
-
- public MessagesDragSource (TreeViewer sourceView, String bundleId) {
+
+ public MessagesDragSource(TreeViewer sourceView, String bundleId) {
source = sourceView;
this.bundleId = bundleId;
}
-
+
@Override
public void dragFinished(DragSourceEvent event) {
-
+
}
@Override
public void dragSetData(DragSourceEvent event) {
- IKeyTreeNode selectionObject = (IKeyTreeNode)
- ((IStructuredSelection)source.getSelection()).toList().get(0);
-
+ IKeyTreeNode selectionObject = (IKeyTreeNode) ((IStructuredSelection) source
+ .getSelection()).toList().get(0);
+
String key = selectionObject.getMessageKey();
-
- // TODO Solve the problem that its not possible to retrieve the editor position of the drop event
-
-// event.data = "(new ResourceBundle(\"" + bundleId + "\")).getString(\"" + key + "\")";
+
+ // 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 + "\"";
}
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 3fa158ad..74be80b5 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
@@ -25,43 +25,47 @@
public class MessagesDropTarget extends DropTargetAdapter {
private final String projectName;
private String bundleName;
-
- public MessagesDropTarget (TreeViewer viewer, String projectName, String 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) {
+
+ public void drop(DropTargetEvent event) {
if (event.detail != DND.DROP_COPY)
return;
-
- if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
- //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+
+ 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());
-
+ Display.getDefault().getActiveShell());
+
DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "");
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
+ + "." + "[Platzhalter]"
+ : "");
config.setPreselectedMessage(message);
config.setPreselectedBundle(bundleName);
config.setPreselectedLocale("");
config.setProjectName(projectName);
-
+
dialog.setDialogConfiguration(config);
-
+
if (dialog.open() != InputDialog.OK)
return;
} else
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 236b0406..68d47807 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
@@ -10,10 +10,9 @@
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.widgets;
-
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 1f05cfd8..ff37605d 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
@@ -83,145 +83,149 @@
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
-public class PropertyKeySelectionTree extends Composite implements IResourceBundleChangedListener {
+public class PropertyKeySelectionTree extends Composite implements
+ IResourceBundleChangedListener {
- private final int KEY_COLUMN_WEIGHT = 1;
- private final int LOCALE_COLUMN_WEIGHT = 1;
+ 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 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 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 SortInfo sortInfo;
- private ResKeyTreeContentProvider contentProvider;
- private ResKeyTreeLabelProvider labelProvider;
- private TreeType treeType = TreeType.Tree;
-
- private IMessagesEditorListener editorListener;
+ private ResKeyTreeContentProvider contentProvider;
+ private ResKeyTreeLabelProvider labelProvider;
+ private TreeType treeType = TreeType.Tree;
- /*** MATCHER ***/
- ExactMatcher matcher;
+ private IMessagesEditorListener editorListener;
- /*** SORTER ***/
- ValuedKeyTreeItemSorter sorter;
+ /*** MATCHER ***/
+ ExactMatcher matcher;
- /*** ACTIONS ***/
- private Action doubleClickAction;
+ /*** SORTER ***/
+ ValuedKeyTreeItemSorter sorter;
- /*** LISTENERS ***/
- private ISelectionChangedListener selectionChangedListener;
+ /*** 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() {
-
+ 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());
+ + ((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;
@@ -230,516 +234,571 @@ public boolean equals(Object a, Object b) {
return false;
}
});
-
- setTreeStructure();
- this.setRedraw(true);
- }
-
- public void setTreeStructure() {
- IAbstractKeyTreeModel model = KeyTreeFactory.createModel(ResourceBundleManager.getManager(projectName).getResourceBundle(resourceBundle));
- if (treeViewer.getInput() == null) {
- treeViewer.setUseHashlookup(true);
- }
- org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer.getExpandedTreePaths();
- treeViewer.setInput(model);
- treeViewer.refresh();
- treeViewer.setExpandedTreePaths(expandedTreePaths);
- }
-
- protected void refreshContent(ResourceBundleChangedEvent event) {
- if (visibleLocales == null) {
- initVisibleLocales();
- }
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- // update content provider
- contentProvider.setLocales(visibleLocales);
- contentProvider.setProjectName(manager.getProject().getName());
- contentProvider.setBundleId(resourceBundle);
-
- // init label provider
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
- labelProvider.setLocales(visibleLocales);
- if (treeViewer.getLabelProvider() != labelProvider)
- treeViewer.setLabelProvider(labelProvider);
-
- // define input of treeviewer
- setTreeStructure();
- }
-
- protected void initVisibleLocales() {
- SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- sortInfo = new SortInfo();
- visibleLocales.clear();
- if (resourceBundle != null) {
- for (Locale l : manager.getProvidedLocales(resourceBundle)) {
- if (l == null) {
- locSorted.put("Default", null);
- } else {
- locSorted.put(l.getDisplayName(uiLocale), l);
- }
- }
- }
-
- for (String lString : locSorted.keySet()) {
- visibleLocales.add(locSorted.get(lString));
- }
- sortInfo.setVisibleLocales(visibleLocales);
- }
-
- protected void constructWidget() {
- basicLayout = new TreeColumnLayout();
- this.setLayout(basicLayout);
-
- treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
- Tree tree = treeViewer.getTree();
-
- if (resourceBundle != null) {
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // create tree-columns
- constructTreeColumns(tree);
- } else {
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
- }
-
- makeActions();
- hookDoubleClickAction();
-
- // register messages table as selection provider
- site.setSelectionProvider(treeViewer);
- }
-
- protected void constructTreeColumns(Tree tree) {
- tree.removeAll();
- //tree.getColumns().length;
-
- // construct key-column
- keyColumn = new TreeColumn(tree, SWT.NONE);
- keyColumn.setText("Key");
- keyColumn.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(keyColumn, new ColumnWeightData(KEY_COLUMN_WEIGHT));
-
- if (visibleLocales != null) {
- final ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- for (final Locale l : visibleLocales) {
- TreeColumn col = new TreeColumn(tree, SWT.NONE);
-
- // Add editing support to this table column
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
-
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- boolean writeToFile = true;
-
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- String activeKey = vkti.getMessageKey();
-
- if (activeKey != null) {
- IMessagesBundleGroup bundleGroup = manager.getResourceBundle(resourceBundle);
- IMessage entry = bundleGroup.getMessage(activeKey, l);
-
- if (entry == null || !value.equals(entry.getValue())) {
- String comment = null;
- if (entry != null) {
- comment = entry.getComment();
- }
-
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(l);
-
- DirtyHack.setFireEnabled(false);
-
- IMessage message = messagesBundle.getMessage(activeKey);
- if (message == null) {
- IMessage newMessage = MessageFactory.createMessage(activeKey, l);
- newMessage.setText(String.valueOf(value));
- newMessage.setComment(comment);
- messagesBundle.addMessage(newMessage);
- } else {
- message.setText(String.valueOf(value));
- message.setComment(comment);
- }
-
- RBManager.getInstance(manager.getProject()).writeToFile(messagesBundle);
-
- // update TreeViewer
- vkti.setValue(l, String.valueOf(value));
- treeViewer.refresh();
-
- DirtyHack.setFireEnabled(true);
- }
- }
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, visibleLocales.indexOf(l) + 1);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer.getControl();
- editor = new TextCellEditor(tree);
- editor.getControl().addTraverseListener(new TraverseListener() {
-
- @Override
- public void keyTraversed(TraverseEvent e) {
- Logger.logInfo("CELL_EDITOR: " + e.toString());
- if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail ==
- SWT.TRAVERSE_TAB_PREVIOUS) {
-
- e.doit = false;
- int colIndex = visibleLocales.indexOf(l)+1;
- Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
- int noOfCols = treeViewer.getTree().getColumnCount();
-
- // go to next cell
- if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
- int nextColIndex = colIndex+1;
- if (nextColIndex < noOfCols)
- treeViewer.editElement(sel, nextColIndex);
- // go to previous cell
- } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
- int prevColIndex = colIndex-1;
- if (prevColIndex > 0)
- treeViewer.editElement(sel, colIndex-1);
- }
- }
- }
- });
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
-
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(uiLocale);
-
- col.setText(displayName);
- col.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
- });
- basicLayout.setColumnData(col, new ColumnWeightData(LOCALE_COLUMN_WEIGHT));
- }
- }
- }
-
- protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sortInfo.setVisibleLocales(visibleLocales);
- sorter.setSortInfo(sortInfo);
- treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
- setTreeStructure();
- treeViewer.refresh();
- }
-
- @Override
- public boolean setFocus() {
- return treeViewer.getControl().setFocus();
- }
-
- /*** DRAG AND DROP ***/
- protected void hookDragAndDrop() {
- //KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource (treeViewer);
- KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
- MessagesDragSource source = new MessagesDragSource(treeViewer, this.resourceBundle);
- MessagesDropTarget target = new MessagesDropTarget(treeViewer, projectName, resourceBundle);
-
- // Initialize drag source for copy event
- DragSource dragSource = new DragSource(treeViewer.getControl(), DND.DROP_COPY | DND.DROP_MOVE);
- dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
- //dragSource.addDragListener(ktiSource);
- dragSource.addDragListener(source);
-
- // Initialize drop target for copy event
- DropTarget dropTarget = new DropTarget(treeViewer.getControl(), DND.DROP_MOVE | DND.DROP_COPY);
- dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), JavaUI.getJavaElementClipboardTransfer() });
- dropTarget.addDropListener(ktiTarget);
- dropTarget.addDropListener(target);
- }
-
- /*** ACTIONS ***/
-
- private void makeActions() {
- doubleClickAction = new Action() {
-
- @Override
- public void run() {
- editSelectedItem();
- }
-
- };
- }
-
- private void hookDoubleClickAction() {
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
- }
-
- /*** SELECTION LISTENER ***/
-
- protected void registerListeners() {
-
- this.editorListener = new MessagesEditorListener();
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- if (manager != null) {
- RBManager.getInstance(manager.getProject()).addMessagesEditorListener(editorListener);
- }
-
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
-
- public void keyPressed(KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
- }
-
- protected void unregisterListeners() {
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- if (manager != null) {
- RBManager.getInstance(manager.getProject()).removeMessagesEditorListener(editorListener);
- }
- treeViewer.removeSelectionChangedListener(selectionChangedListener);
- }
-
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- selectionChangedListener = listener;
- }
-
- @Override
- public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
- if (event.getType() != ResourceBundleChangedEvent.MODIFIED
- || !event.getBundle().equals(this.getResourceBundle()))
- return;
-
- if (Display.getCurrent() != null) {
- refreshViewer(event, true);
- return;
- }
-
- Display.getDefault().asyncExec(new Runnable() {
-
- public void run() {
- refreshViewer(event, true);
- }
- });
- }
-
- private void refreshViewer(ResourceBundleChangedEvent event, boolean computeVisibleLocales) {
- //manager.loadResourceBundle(resourceBundle);
- if (computeVisibleLocales) {
- refreshContent(event);
- }
-
- // Display.getDefault().asyncExec(new Runnable() {
- // public void run() {
- treeViewer.refresh();
- // }
- // });
- }
-
- public StructuredViewer getViewer() {
- return this.treeViewer;
- }
-
- public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat : TreeType.Tree;
- labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
- // WTF?
- treeType = treeType.equals(TreeType.Tree) && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
- treeViewer.refresh();
- this.refreshContent(null);
- }
-
- public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- sortInfo.setVisibleLocales(visibleLocales);
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
- treeViewer.refresh();
- }
- }
-
- public String getSearchString() {
- return matcher.getPattern();
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public String getResourceBundle() {
- return resourceBundle;
- }
-
- public void editSelectedItem() {
- String key = "";
- ISelection selection = treeViewer.getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structSel = (IStructuredSelection) selection;
- if (structSel.getFirstElement() instanceof IKeyTreeNode) {
- IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel.getFirstElement();
- key = keyTreeNode.getMessageKey();
- }
- }
-
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- EditorUtils.openEditor(site.getPage(), manager.getRandomFile(resourceBundle),
- EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
- }
-
- public void deleteSelectedItems() {
- List<String> keys = new ArrayList<String>();
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- addKeysToRemove((IKeyTreeNode)elem, keys);
- }
- }
- }
-
- try {
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- manager.removeResourceBundleEntry(getResourceBundle(), keys);
- } catch (Exception ex) {
- Logger.logError(ex);
- }
- }
-
- private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
- keys.add(node.getMessageKey());
- for (IKeyTreeNode ktn : node.getChildren()) {
- addKeysToRemove(ktn, keys);
- }
- }
-
- public void addNewItem(ISelection selection) {
- //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
-
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
- break;
- }
- }
- }
+
+ setTreeStructure();
+ this.setRedraw(true);
+ }
+
+ public void setTreeStructure() {
+ IAbstractKeyTreeModel model = KeyTreeFactory
+ .createModel(ResourceBundleManager.getManager(projectName)
+ .getResourceBundle(resourceBundle));
+ if (treeViewer.getInput() == null) {
+ treeViewer.setUseHashlookup(true);
+ }
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer
+ .getExpandedTreePaths();
+ treeViewer.setInput(model);
+ treeViewer.refresh();
+ treeViewer.setExpandedTreePaths(expandedTreePaths);
+ }
+
+ protected void refreshContent(ResourceBundleChangedEvent event) {
+ if (visibleLocales == null) {
+ initVisibleLocales();
+ }
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+
+ // update content provider
+ contentProvider.setLocales(visibleLocales);
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
+
+ // init label provider
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ labelProvider.setLocales(visibleLocales);
+ if (treeViewer.getLabelProvider() != labelProvider)
+ treeViewer.setLabelProvider(labelProvider);
+
+ // define input of treeviewer
+ setTreeStructure();
+ }
+
+ protected void initVisibleLocales() {
+ SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ sortInfo = new SortInfo();
+ visibleLocales.clear();
+ if (resourceBundle != null) {
+ for (Locale l : manager.getProvidedLocales(resourceBundle)) {
+ if (l == null) {
+ locSorted.put("Default", null);
+ } else {
+ locSorted.put(l.getDisplayName(uiLocale), l);
+ }
+ }
+ }
+
+ for (String lString : locSorted.keySet()) {
+ visibleLocales.add(locSorted.get(lString));
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ }
+
+ protected void constructWidget() {
+ basicLayout = new TreeColumnLayout();
+ this.setLayout(basicLayout);
+
+ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
+ | SWT.BORDER);
+ Tree tree = treeViewer.getTree();
+
+ if (resourceBundle != null) {
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // create tree-columns
+ constructTreeColumns(tree);
+ } else {
+ tree.setHeaderVisible(false);
+ tree.setLinesVisible(false);
+ }
+
+ makeActions();
+ hookDoubleClickAction();
+
+ // register messages table as selection provider
+ site.setSelectionProvider(treeViewer);
+ }
+
+ protected void constructTreeColumns(Tree tree) {
+ tree.removeAll();
+ // tree.getColumns().length;
+
+ // construct key-column
+ keyColumn = new TreeColumn(tree, SWT.NONE);
+ keyColumn.setText("Key");
+ keyColumn.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(keyColumn, new ColumnWeightData(
+ KEY_COLUMN_WEIGHT));
+
+ if (visibleLocales != null) {
+ final ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ for (final Locale l : visibleLocales) {
+ TreeColumn col = new TreeColumn(tree, SWT.NONE);
+
+ // Add editing support to this table column
+ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
+ tCol.setEditingSupport(new EditingSupport(treeViewer) {
+
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ boolean writeToFile = true;
+
+ if (element instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ String activeKey = vkti.getMessageKey();
+
+ if (activeKey != null) {
+ IMessagesBundleGroup bundleGroup = manager
+ .getResourceBundle(resourceBundle);
+ IMessage entry = bundleGroup.getMessage(
+ activeKey, l);
+
+ if (entry == null
+ || !value.equals(entry.getValue())) {
+ String comment = null;
+ if (entry != null) {
+ comment = entry.getComment();
+ }
+
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(l);
+
+ DirtyHack.setFireEnabled(false);
+
+ IMessage message = messagesBundle
+ .getMessage(activeKey);
+ if (message == null) {
+ IMessage newMessage = MessageFactory
+ .createMessage(activeKey, l);
+ newMessage.setText(String
+ .valueOf(value));
+ newMessage.setComment(comment);
+ messagesBundle.addMessage(newMessage);
+ } else {
+ message.setText(String.valueOf(value));
+ message.setComment(comment);
+ }
+
+ RBManager.getInstance(manager.getProject())
+ .writeToFile(messagesBundle);
+
+ // update TreeViewer
+ vkti.setValue(l, String.valueOf(value));
+ treeViewer.refresh();
+
+ DirtyHack.setFireEnabled(true);
+ }
+ }
+ }
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element,
+ visibleLocales.indexOf(l) + 1);
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer
+ .getControl();
+ editor = new TextCellEditor(tree);
+ editor.getControl().addTraverseListener(
+ new TraverseListener() {
+
+ @Override
+ public void keyTraversed(TraverseEvent e) {
+ Logger.logInfo("CELL_EDITOR: "
+ + e.toString());
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT
+ || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+
+ e.doit = false;
+ int colIndex = visibleLocales
+ .indexOf(l) + 1;
+ Object sel = ((IStructuredSelection) treeViewer
+ .getSelection())
+ .getFirstElement();
+ int noOfCols = treeViewer
+ .getTree()
+ .getColumnCount();
+
+ // go to next cell
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
+ int nextColIndex = colIndex + 1;
+ if (nextColIndex < noOfCols)
+ treeViewer.editElement(
+ sel,
+ nextColIndex);
+ // go to previous cell
+ } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+ int prevColIndex = colIndex - 1;
+ if (prevColIndex > 0)
+ treeViewer.editElement(
+ sel,
+ colIndex - 1);
+ }
+ }
+ }
+ });
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName(uiLocale);
+
+ col.setText(displayName);
+ col.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+ });
+ basicLayout.setColumnData(col, new ColumnWeightData(
+ LOCALE_COLUMN_WEIGHT));
+ }
+ }
+ }
+
+ protected void updateSorter(int idx) {
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ sorter.setSortInfo(sortInfo);
+ treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
+ setTreeStructure();
+ treeViewer.refresh();
+ }
+
+ @Override
+ public boolean setFocus() {
+ return treeViewer.getControl().setFocus();
+ }
+
+ /*** DRAG AND DROP ***/
+ protected void hookDragAndDrop() {
+ // KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource
+ // (treeViewer);
+ KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
+ MessagesDragSource source = new MessagesDragSource(treeViewer,
+ this.resourceBundle);
+ MessagesDropTarget target = new MessagesDropTarget(treeViewer,
+ projectName, resourceBundle);
+
+ // Initialize drag source for copy event
+ DragSource dragSource = new DragSource(treeViewer.getControl(),
+ DND.DROP_COPY | DND.DROP_MOVE);
+ dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
+ // dragSource.addDragListener(ktiSource);
+ dragSource.addDragListener(source);
+
+ // Initialize drop target for copy event
+ DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
+ DND.DROP_MOVE | DND.DROP_COPY);
+ dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(),
+ JavaUI.getJavaElementClipboardTransfer() });
+ dropTarget.addDropListener(ktiTarget);
+ dropTarget.addDropListener(target);
+ }
+
+ /*** ACTIONS ***/
+
+ private void makeActions() {
+ doubleClickAction = new Action() {
+
+ @Override
+ public void run() {
+ editSelectedItem();
+ }
+
+ };
+ }
+
+ private void hookDoubleClickAction() {
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
+ }
+
+ /*** SELECTION LISTENER ***/
+
+ protected void registerListeners() {
+
+ this.editorListener = new MessagesEditorListener();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject())
+ .addMessagesEditorListener(editorListener);
+ }
+
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
+
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
+ }
+
+ protected void unregisterListeners() {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject())
+ .removeMessagesEditorListener(editorListener);
+ }
+ treeViewer.removeSelectionChangedListener(selectionChangedListener);
+ }
+
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
+ treeViewer.addSelectionChangedListener(listener);
+ selectionChangedListener = listener;
+ }
+
+ @Override
+ public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
+ if (event.getType() != ResourceBundleChangedEvent.MODIFIED
+ || !event.getBundle().equals(this.getResourceBundle()))
+ return;
+
+ if (Display.getCurrent() != null) {
+ refreshViewer(event, true);
+ return;
+ }
+
+ Display.getDefault().asyncExec(new Runnable() {
+
+ public void run() {
+ refreshViewer(event, true);
+ }
+ });
+ }
+
+ private void refreshViewer(ResourceBundleChangedEvent event,
+ boolean computeVisibleLocales) {
+ // manager.loadResourceBundle(resourceBundle);
+ if (computeVisibleLocales) {
+ refreshContent(event);
+ }
+
+ // Display.getDefault().asyncExec(new Runnable() {
+ // public void run() {
+ treeViewer.refresh();
+ // }
+ // });
+ }
+
+ public StructuredViewer getViewer() {
+ return this.treeViewer;
+ }
+
+ public void setSearchString(String pattern) {
+ matcher.setPattern(pattern);
+ treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat
+ : TreeType.Tree;
+ labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
+ // WTF?
+ treeType = treeType.equals(TreeType.Tree)
+ && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree
+ : TreeType.Flat;
+ treeViewer.refresh();
+ this.refreshContent(null);
+ }
+
+ public SortInfo getSortInfo() {
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ sortInfo.setVisibleLocales(visibleLocales);
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree
+ : TreeType.Flat;
+ treeViewer.refresh();
+ }
+ }
+
+ public String getSearchString() {
+ return matcher.getPattern();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void editSelectedItem() {
+ String key = "";
+ ISelection selection = treeViewer.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structSel = (IStructuredSelection) selection;
+ if (structSel.getFirstElement() instanceof IKeyTreeNode) {
+ IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel
+ .getFirstElement();
+ key = keyTreeNode.getMessageKey();
+ }
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ EditorUtils.openEditor(site.getPage(),
+ manager.getRandomFile(resourceBundle),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
+ }
+
+ public void deleteSelectedItems() {
+ List<String> keys = new ArrayList<String>();
+
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ addKeysToRemove((IKeyTreeNode) elem, keys);
+ }
+ }
+ }
+
+ try {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ manager.removeResourceBundleEntry(getResourceBundle(), keys);
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ }
+ }
+
+ private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
+ keys.add(node.getMessageKey());
+ for (IKeyTreeNode ktn : node.getChildren()) {
+ addKeysToRemove(ktn, keys);
+ }
+ }
+
+ public void addNewItem(ISelection selection) {
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
+
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
+ break;
+ }
+ }
+ }
CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
+ Display.getDefault().getActiveShell());
+
DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "");
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
+ + "." + "[Platzhalter]"
+ : "");
config.setPreselectedMessage("");
config.setPreselectedBundle(getResourceBundle());
config.setPreselectedLocale("");
config.setProjectName(projectName);
-
+
dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
- }
-
- public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- private class MessagesEditorListener implements IMessagesEditorListener {
- @Override
- public void onSave() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
-
- @Override
- public void onModify() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
-
- @Override
- public void onResourceChanged(IMessagesBundle bundle) {
- // TODO Auto-generated method stub
-
- }
- }
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+ }
+
+ public void setMatchingPrecision(float value) {
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ private class MessagesEditorListener implements IMessagesEditorListener {
+ @Override
+ public void onSave() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onModify() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onResourceChanged(IMessagesBundle bundle) {
+ // TODO Auto-generated method stub
+
+ }
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
index 71ea0448..6ffc0b1c 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
@@ -40,146 +40,165 @@
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
-
-public class ResourceSelector extends Composite {
+public class ResourceSelector extends Composite {
public static final int DISPLAY_KEYS = 0;
public static final int DISPLAY_TEXT = 1;
-
+
private Locale displayLocale = null; // default
private int displayMode;
private String resourceBundle;
private String projectName;
private boolean showTree = true;
-
+
private TreeViewer viewer;
private TreeColumnLayout basicLayout;
private TreeColumn entries;
private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>();
-
+
// Viewer model
private TreeType treeType = TreeType.Tree;
private StyledCellLabelProvider labelProvider;
-
- public ResourceSelector(Composite parent,
- int style) {
- super(parent, style);
- initLayout (this);
- initViewer (this);
+ public ResourceSelector(Composite parent, int style) {
+ super(parent, style);
+
+ initLayout(this);
+ initViewer(this);
}
- protected void updateContentProvider (IMessagesBundleGroup group) {
+ protected void updateContentProvider(IMessagesBundleGroup group) {
// define input of treeviewer
if (!showTree || displayMode == DISPLAY_TEXT) {
treeType = TreeType.Flat;
- }
-
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle));
- ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider)viewer.getContentProvider();
+ }
+
+ 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();
+ if (viewer.getInput() == null) {
+ viewer.setUseHashlookup(true);
+ }
+
+ // viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer
+ .getExpandedTreePaths();
viewer.setInput(model);
viewer.refresh();
viewer.setExpandedTreePaths(expandedTreePaths);
}
-
- protected void updateViewer (boolean updateContent) {
- IMessagesBundleGroup group = ResourceBundleManager.getManager(projectName).getResourceBundle(resourceBundle);
-
+
+ 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));
+ labelProvider = new ValueKeyTreeLabelProvider(
+ group.getMessagesBundle(displayLocale));
treeType = TreeType.Flat;
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ ((ResKeyTreeContentProvider) viewer.getContentProvider())
+ .setTreeType(treeType);
} else {
labelProvider = new ResKeyTreeLabelProvider(null);
treeType = TreeType.Tree;
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ ((ResKeyTreeContentProvider) viewer.getContentProvider())
+ .setTreeType(treeType);
}
-
+
viewer.setLabelProvider(labelProvider);
if (updateContent)
updateContentProvider(group);
}
-
- protected void initLayout (Composite parent) {
+
+ 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);
+
+ 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);
+ 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);
-
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+
if (selection instanceof IStructuredSelection) {
- Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection).iterator();
+ Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection)
+ .iterator();
if (itSel.hasNext()) {
- IKeyTreeNode selItem = itSel.next();
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ IKeyTreeNode selItem = itSel.next();
+ IMessagesBundleGroup group = manager
+ .getResourceBundle(resourceBundle);
selectedKey = selItem.getMessageKey();
-
+
if (group == null)
return;
- Iterator<Locale> itLocales = manager.getProvidedLocales(resourceBundle).iterator();
+ 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) {}
+ 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);
+ ResourceSelectionEvent e = new ResourceSelectionEvent(
+ selectedKey, selectionSummary);
fireSelectionChanged(e);
}
});
-
+
// we need this to keep the tree expanded
- viewer.setComparer(new IElementComparer() {
-
+ 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());
+ + ((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;
@@ -189,7 +208,7 @@ public boolean equals(Object a, Object b) {
}
});
}
-
+
public Locale getDisplayLocale() {
return displayLocale;
}
@@ -216,16 +235,16 @@ public void setResourceBundle(String resourceBundle) {
public String getResourceBundle() {
return resourceBundle;
}
-
- public void addSelectionChangedListener (IResourceSelectionListener l) {
+
+ public void addSelectionChangedListener(IResourceSelectionListener l) {
listeners.add(l);
}
-
- public void removeSelectionChangedListener (IResourceSelectionListener l) {
+
+ public void removeSelectionChangedListener(IResourceSelectionListener l) {
listeners.remove(l);
}
-
- private void fireSelectionChanged (ResourceSelectionEvent event) {
+
+ private void fireSelectionChanged(ResourceSelectionEvent event) {
Iterator<IResourceSelectionListener> itResList = listeners.iterator();
while (itResList.hasNext()) {
itResList.next().selectionChanged(event);
@@ -247,5 +266,5 @@ public void setShowTree(boolean showTree) {
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 40d713a8..3b58fc8a 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
@@ -14,16 +14,16 @@ public class ResourceSelectionEvent {
private String selectionSummary;
private String selectedKey;
-
- public ResourceSelectionEvent (String selectedKey, String selectionSummary) {
+
+ public ResourceSelectionEvent(String selectedKey, String selectionSummary) {
this.setSelectionSummary(selectionSummary);
this.setSelectedKey(selectedKey);
}
- public void setSelectedKey (String key) {
+ public void setSelectedKey(String key) {
selectedKey = key;
}
-
+
public void setSelectionSummary(String selectionSummary) {
this.selectionSummary = selectionSummary;
}
@@ -35,7 +35,5 @@ public String getSelectionSummary() {
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 8e5786df..9fe818fd 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
@@ -22,20 +22,20 @@ public class ExactMatcher extends ViewerFilter {
protected final StructuredViewer viewer;
protected String pattern = "";
protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
+
+ public ExactMatcher(StructuredViewer viewer) {
this.viewer = viewer;
}
-
- public String getPattern () {
+
+ public String getPattern() {
return pattern;
}
-
- public void setPattern (String p) {
+
+ public void setPattern(String p) {
boolean filtering = matcher != null;
if (p != null && p.trim().length() > 0) {
pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
+ matcher = new StringMatcher("*" + pattern + "*", true, false);
if (!filtering)
viewer.addFilter(this);
else
@@ -48,23 +48,24 @@ public void setPattern (String p) {
}
}
}
-
+
@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) {
+ 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);
@@ -72,16 +73,17 @@ public boolean select(Viewer viewer, Object parentElement, Object element) {
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());
+ while ((start = value.toLowerCase().indexOf(
+ pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo
+ .addFoundInLocaleRange(l, start, pattern.length());
}
selected = true;
}
}
-
+
vEle.setInfo(filterInfo);
return selected;
}
-
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
index fff5f7af..ee6725be 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
@@ -21,32 +21,32 @@
public class FilterInfo {
private boolean foundInKey;
- private List<Locale> foundInLocales = new ArrayList<Locale> ();
- private List<Region> keyOccurrences = new ArrayList<Region> ();
+ 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) {
+
+ public void setKeySimilarity(Double similarity) {
keySimilarity = similarity;
}
-
- public Double getKeySimilarity () {
+
+ public Double getKeySimilarity() {
return keySimilarity;
}
-
- public void addSimilarity (Locale l, Double similarity) {
- localeSimilarity.put (l, similarity);
+
+ public void addSimilarity(Locale l, Double similarity) {
+ localeSimilarity.put(l, similarity);
}
- public Double getSimilarityLevel (Locale l) {
+ public Double getSimilarityLevel(Locale l) {
return localeSimilarity.get(l);
}
-
+
public void setFoundInKey(boolean foundInKey) {
this.foundInKey = foundInKey;
}
@@ -54,41 +54,41 @@ public void setFoundInKey(boolean foundInKey) {
public boolean isFoundInKey() {
return foundInKey;
}
-
- public void addFoundInLocale (Locale loc) {
+
+ public void addFoundInLocale(Locale loc) {
foundInLocales.add(loc);
}
-
- public void removeFoundInLocale (Locale loc) {
+
+ public void removeFoundInLocale(Locale loc) {
foundInLocales.remove(loc);
}
-
- public void clearFoundInLocale () {
+
+ public void clearFoundInLocale() {
foundInLocales.clear();
}
- public boolean hasFoundInLocale (Locale l) {
+ public boolean hasFoundInLocale(Locale l) {
return foundInLocales.contains(l);
}
-
- public List<Region> getFoundInLocaleRanges (Locale locale) {
+
+ 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) {
+
+ 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 () {
+
+ public List<Region> getKeyOccurrences() {
return keyOccurrences;
}
-
- public void addKeyOccurrence (int start, int length) {
- keyOccurrences.add(new Region (start, length));
+
+ 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 79ba60e0..ff3d0d5a 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
@@ -22,28 +22,29 @@ public class FuzzyMatcher extends ExactMatcher {
protected ILevenshteinDistanceAnalyzer lvda;
protected float minimumSimilarity = 0.75f;
-
+
public FuzzyMatcher(StructuredViewer viewer) {
super(viewer);
- lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();;
+ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
+ ;
}
- public double getMinimumSimilarity () {
+ public double getMinimumSimilarity() {
return minimumSimilarity;
}
-
- public void setMinimumSimilarity (float 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;
-
+
IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
-
+
for (Locale l : vkti.getLocales()) {
String value = vkti.getValue(l);
if (filterInfo.hasFoundInLocale(l))
@@ -56,7 +57,7 @@ public boolean select(Viewer viewer, Object parentElement, Object element) {
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 c4cb2194..52238ec9 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
@@ -16,436 +16,481 @@
* A string pattern matcher, suppporting "*" and "?" wildcards.
*/
public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
+ protected String fPattern;
+
+ protected int fLength; // pattern length
+
+ protected boolean fIgnoreWildCards;
+
+ protected boolean fIgnoreCase;
+
+ protected boolean fHasLeadingStar;
+
+ protected boolean fHasTrailingStar;
+
+ protected String fSegments[]; // the given pattern is split into * separated
+ // segments
+
+ /* boundary value beyond which we don't need to search in the text */
+ protected int fBound = 0;
+
+ protected static final char fSingleWildCard = '\u0000';
+
+ public static class Position {
+ int start; // inclusive
+
+ int end; // exclusive
+
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getEnd() {
+ return end;
+ }
+ }
+
+ /**
+ * StringMatcher constructor takes in a String object that is a simple
+ * pattern which may contain '*' for 0 and many characters and '?' for
+ * exactly one character.
+ *
+ * Literal '*' and '?' characters must be escaped in the pattern e.g.,
+ * "\*" means literal "*", etc.
+ *
+ * Escaping any other character (including the escape character itself),
+ * just results in that character in the pattern. e.g., "\a" means "a" and
+ * "\\" means "\"
+ *
+ * If invoking the StringMatcher with string literals in Java, don't forget
+ * escape characters are represented by "\\".
+ *
+ * @param pattern
+ * the pattern to match text against
+ * @param ignoreCase
+ * if true, case is ignored
+ * @param ignoreWildCards
+ * if true, wild cards and their escape sequences are ignored
+ * (everything is taken literally).
+ */
+ public StringMatcher(String pattern, boolean ignoreCase,
+ boolean ignoreWildCards) {
+ if (pattern == null) {
throw new IllegalArgumentException();
}
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
+ 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) {
+ int tlen = text.length();
+ if (start < 0) {
start = 0;
}
- if (end > tlen) {
+ if (end > tlen) {
end = tlen;
}
- if (end < 0 || start >= end) {
+ if (end < 0 || start >= end) {
return null;
}
- if (fLength == 0) {
+ if (fLength == 0) {
return new Position(start, start);
}
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
return null;
}
- return new Position(x, x + fLength);
- }
+ return new Position(x, x + fLength);
+ }
- int segCount = fSegments.length;
- if (segCount == 0) {
+ 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) {
+ 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) {
+ if (i == 0) {
matchStart = nextMatch;
}
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
+ 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 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) {
+ 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) {
+ if (start > end) {
return false;
}
- if (fIgnoreWildCards) {
+ if (fIgnoreWildCards) {
return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
}
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
return true;
}
- if (start == end) {
+ if (start == end) {
return fLength == 0;
}
- if (fLength == 0) {
+ if (fLength == 0) {
return start == end;
}
- int tlen = text.length();
- if (start < 0) {
+ int tlen = text.length();
+ if (start < 0) {
start = 0;
}
- if (end > tlen) {
+ if (end > tlen) {
end = tlen;
}
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
+ 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) {
+ 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) {
+ } 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$
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
+
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
+ }
+
+ /**
+ * This method parses the given pattern into segments seperated by wildcard
+ * '*' characters. Since wildcards are not being used in this case, the
+ * pattern consists of a single segment.
+ */
+ private void parseNoWildCards() {
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
+ }
+
+ /**
+ * Parses the given pattern into segments seperated by wildcard '*'
+ * characters.
+ *
+ * @param p
+ * , a String object that is a simple regular expression with '*'
+ * and/or '?'
+ */
+ private void parseWildCards() {
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
fHasLeadingStar = true;
}
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
+
+ Vector temp = new Vector();
+
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
+
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
+
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
+ }
+
+ /**
+ * @param text
+ * a string which contains no wildcard
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int posIn(String text, int start, int end) {// no wild card in
+ // pattern
+ int max = end - fLength;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
return -1;
}
- return i;
- }
+ return i;
+ }
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ 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 -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) {
+ }
+ 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)) {
+ 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)) {
+ // 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 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;
- }
+ return i;
+ }
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
return i;
}
- }
+ }
- return -1;
- }
+ 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 9d44a242..3c44d65e 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
@@ -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 ce437b45..dfa592e0 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
@@ -8,7 +8,7 @@
* Contributors:
* Martin Reiterer - initial API and implementation
******************************************************************************/
- /*
+/*
+ * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
*
* This file is part of Essiembre ResourceBundle Editor.
@@ -44,133 +44,138 @@
/**
* Label provider for key tree viewer.
+ *
* @author Pascal Essiembre ([email protected])
* @version $Author: nl_carnage $ $Revision: 1.11 $ $Date: 2007/09/11 16:11:09 $
*/
-public class KeyTreeLabelProvider
- extends StyledCellLabelProvider /*implements IFontProvider, IColorProvider*/ {
-
- private static final int KEY_DEFAULT = 1 << 1;
- private static final int KEY_COMMENTED = 1 << 2;
- private static final int KEY_NOT = 1 << 3;
- private static final int WARNING = 1 << 4;
- private static final int WARNING_GREY = 1 << 5;
-
- /** Registry instead of UIUtils one for image not keyed by file name. */
- private static ImageRegistry imageRegistry = new ImageRegistry();
-
- private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY);
-
- /** Group font. */
- private Font groupFontKey = FontUtils.createFont(SWT.BOLD);
- private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
-
-
- /**
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- IKeyTreeNode treeItem = ((IKeyTreeNode) element);
-
- int iconFlags = 0;
-
- // Figure out background icon
- if (treeItem.getMessagesBundleGroup() != null &&
- treeItem.getMessagesBundleGroup().isKey(treeItem.getMessageKey())) {
- iconFlags += KEY_DEFAULT;
- } else {
- iconFlags += KEY_NOT;
- }
-
- return generateImage(iconFlags);
- }
-
- /**
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- return ((IKeyTreeNode) element).getName();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
- */
- public void dispose() {
- groupFontKey.dispose();
- groupFontNoKey.dispose();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- IKeyTreeNode item = (IKeyTreeNode) element;
- if (item.getChildren().length > 0 && item.getMessagesBundleGroup() != null) {
- if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) {
- return groupFontKey;
- }
- return groupFontNoKey;
- }
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- IKeyTreeNode treeItem = (IKeyTreeNode) element;
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- // TODO Auto-generated method stub
- return null;
- }
-
- /**
- * Generates an image based on icon flags.
- * @param iconFlags
- * @return generated image
- */
- private Image generateImage(int iconFlags) {
- Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
- if (image == null) {
- // Figure background image
- if ((iconFlags & KEY_COMMENTED) != 0) {
- image = getRegistryImage("keyCommented.gif"); //$NON-NLS-1$
- } else if ((iconFlags & KEY_NOT) != 0) {
- image = getRegistryImage("key.gif"); //$NON-NLS-1$
- } else {
- image = getRegistryImage("key.gif"); //$NON-NLS-1$
- }
-
- }
- return image;
- }
-
-
- private Image getRegistryImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
+public class KeyTreeLabelProvider extends StyledCellLabelProvider /*
+ * implements
+ * IFontProvider
+ * ,
+ * IColorProvider
+ */{
+
+ private static final int KEY_DEFAULT = 1 << 1;
+ private static final int KEY_COMMENTED = 1 << 2;
+ private static final int KEY_NOT = 1 << 3;
+ private static final int WARNING = 1 << 4;
+ private static final int WARNING_GREY = 1 << 5;
+
+ /** Registry instead of UIUtils one for image not keyed by file name. */
+ private static ImageRegistry imageRegistry = new ImageRegistry();
+
+ private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+
+ /** Group font. */
+ private Font groupFontKey = FontUtils.createFont(SWT.BOLD);
+ private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
+
+ /**
+ * @see ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ IKeyTreeNode treeItem = ((IKeyTreeNode) element);
+
+ int iconFlags = 0;
+
+ // Figure out background icon
+ if (treeItem.getMessagesBundleGroup() != null
+ && treeItem.getMessagesBundleGroup().isKey(
+ treeItem.getMessageKey())) {
+ iconFlags += KEY_DEFAULT;
+ } else {
+ iconFlags += KEY_NOT;
+ }
+
+ return generateImage(iconFlags);
+ }
+
+ /**
+ * @see ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ return ((IKeyTreeNode) element).getName();
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ groupFontKey.dispose();
+ groupFontNoKey.dispose();
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
+ */
+ public Font getFont(Object element) {
+ IKeyTreeNode item = (IKeyTreeNode) element;
+ if (item.getChildren().length > 0
+ && item.getMessagesBundleGroup() != null) {
+ if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) {
+ return groupFontKey;
+ }
+ return groupFontNoKey;
+ }
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
+ */
+ public Color getForeground(Object element) {
+ IKeyTreeNode treeItem = (IKeyTreeNode) element;
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
+ */
+ public Color getBackground(Object element) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /**
+ * Generates an image based on icon flags.
+ *
+ * @param iconFlags
+ * @return generated image
+ */
+ private Image generateImage(int iconFlags) {
+ Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
+ if (image == null) {
+ // Figure background image
+ if ((iconFlags & KEY_COMMENTED) != 0) {
+ image = getRegistryImage("keyCommented.gif"); //$NON-NLS-1$
+ } else if ((iconFlags & KEY_NOT) != 0) {
+ image = getRegistryImage("key.gif"); //$NON-NLS-1$
+ } else {
+ image = getRegistryImage("key.gif"); //$NON-NLS-1$
+ }
+
+ }
+ return image;
+ }
+
+ private Image getRegistryImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
@Override
public void update(ViewerCell cell) {
cell.setBackground(getBackground(cell.getElement()));
cell.setFont(getFont(cell.getElement()));
cell.setForeground(getForeground(cell.getElement()));
-
+
cell.setText(getText(cell.getElement()));
cell.setImage(getImage(cell.getElement()));
super.update(cell);
}
-
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
index 5ccb3f22..08b5525f 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
@@ -13,7 +13,8 @@
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
-public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements ITableLabelProvider {
+public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements
+ ITableLabelProvider {
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
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 724547dc..b17d9272 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
@@ -29,193 +29,201 @@
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
+public class ResKeyTreeContentProvider implements ITreeContentProvider {
+ private IAbstractKeyTreeModel keyTreeModel;
+ private Viewer viewer;
-public class ResKeyTreeContentProvider implements ITreeContentProvider {
+ private TreeType treeType = TreeType.Tree;
+
+ /** Viewer this provided act upon. */
+ protected TreeViewer treeViewer;
- 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) {
+
+ 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) {
+
+ public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
-
- public void setProjectName (String projectName) {
+
+ public void setProjectName(String projectName) {
this.projectName = projectName;
}
-
+
public ResKeyTreeContentProvider() {
locales = new ArrayList<Locale>();
}
- public void setLocales (List<Locale> locales) {
+ 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) {
+ 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);
-
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ this.projectName).getMessagesBundleGroup(this.bundleId);
+
for (Object o : children) {
if (o instanceof IValuedKeyTreeNode)
- items.add((IValuedKeyTreeNode)o);
+ items.add((IValuedKeyTreeNode) o);
else {
- IKeyTreeNode kti = (IKeyTreeNode) o;
- IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(kti.getParent(), kti.getName(), kti.getMessageKey(), messagesBundleGroup);
+ IKeyTreeNode kti = (IKeyTreeNode) o;
+ IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(
+ kti.getParent(), kti.getName(), kti.getMessageKey(),
+ messagesBundleGroup);
- for (IKeyTreeNode k : kti.getChildren()) {
+ 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) {}
+ IMessage message = messagesBundleGroup
+ .getMessagesBundle(l).getMessage(
+ kti.getMessageKey());
+ if (message != null) {
+ vkti.addValue(l, message.getValue());
+ }
+ } catch (Exception e) {
+ }
}
items.add(vkti);
}
}
-
+
return items.toArray();
}
@Override
public Object[] getElements(Object inputElement) {
- switch (treeType) {
- case Tree:
- return convertKTItoVKTI(keyTreeModel.getRootNodes());
- case Flat:
- final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
- IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
- public void visitKeyTreeNode(IKeyTreeNode node) {
- if (node.isUsedAsKey()) {
- actualKeys.add(node);
- }
- }
- };
- keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
-
- return actualKeys.toArray();
- default:
- // Should not happen
- return new IKeyTreeNode[0];
- }
+ 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;
- }
- }
-
+ 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;
- }
-
+ * 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);
+ 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();
- }
- }
- }
+ @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 3bbfcb9f..90709f7e 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
@@ -28,43 +28,45 @@
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
-
public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider {
private List<Locale> locales;
private boolean searchEnabled = false;
-
+
/*** COLORS ***/
private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
- private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
+ private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
+
+ /*** FONTS ***/
+ private Font bold = FontUtils.createFont(SWT.BOLD);
+ private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
- /*** FONTS ***/
- private Font bold = FontUtils.createFont(SWT.BOLD);
- private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
-
- public ResKeyTreeLabelProvider (List<Locale> locales) {
+ public ResKeyTreeLabelProvider(List<Locale> locales) {
this.locales = locales;
}
-
- //@Override
+
+ // @Override
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex == 0) {
- IKeyTreeNode kti = (IKeyTreeNode) element;
- IMessage[] be = kti.getMessagesBundleGroup().getMessages(kti.getMessageKey());
+ IKeyTreeNode kti = (IKeyTreeNode) element;
+ IMessage[] be = kti.getMessagesBundleGroup().getMessages(
+ kti.getMessageKey());
boolean incomplete = false;
-
- if (be.length != kti.getMessagesBundleGroup().getMessagesBundleCount())
+
+ if (be.length != kti.getMessagesBundleGroup()
+ .getMessagesBundleCount())
incomplete = true;
else {
for (IMessage b : be) {
- if (b.getValue() == null || b.getValue().trim().length() == 0) {
+ if (b.getValue() == null
+ || b.getValue().trim().length() == 0) {
incomplete = true;
break;
}
}
}
-
+
if (incomplete)
return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
else
@@ -73,26 +75,26 @@ public Image getColumnImage(Object element, int columnIndex) {
return null;
}
- //@Override
+ // @Override
public String getColumnText(Object element, int columnIndex) {
if (columnIndex == 0)
return super.getText(element);
-
+
if (columnIndex <= locales.size()) {
- IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
- String entry = item.getValue(locales.get(columnIndex-1));
+ IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
+ String entry = item.getValue(locales.get(columnIndex - 1));
if (entry != null) {
return entry;
}
}
return "";
}
-
- public void setSearchEnabled (boolean enabled) {
+
+ public void setSearchEnabled(boolean enabled) {
this.searchEnabled = enabled;
}
-
- public boolean isSearchEnabled () {
+
+ public boolean isSearchEnabled() {
return this.searchEnabled;
}
@@ -100,64 +102,71 @@ public void setLocales(List<Locale> visibleLocales) {
locales = visibleLocales;
}
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
+ protected boolean isMatchingToPattern(Object element, int columnIndex) {
boolean matching = false;
-
+
if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
-
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+
if (vkti.getInfo() == null)
return false;
-
+
FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
-
+
if (columnIndex == 0) {
matching = filterInfo.isFoundInKey();
} else {
- matching = filterInfo.hasFoundInLocale(locales.get(columnIndex-1));
+ matching = filterInfo.hasFoundInLocale(locales
+ .get(columnIndex - 1));
}
}
-
+
return matching;
}
- protected boolean isSearchEnabled (Object element) {
- return (element instanceof IValuedKeyTreeNode && searchEnabled );
+ protected boolean isSearchEnabled(Object element) {
+ return (element instanceof IValuedKeyTreeNode && searchEnabled);
}
-
+
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
int columnIndex = cell.getColumnIndex();
-
+
if (isSearchEnabled(element)) {
- if (isMatchingToPattern(element, columnIndex) ) {
+ if (isMatchingToPattern(element, columnIndex)) {
List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode)element).getInfo();
-
+ 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));
+ 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
+ // 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);
+ StyleRange sr = new StyleRange(reg.getOffset(),
+ reg.getLength(), black, info_color,
+ SWT.BOLD);
styleRanges.add(sr);
}
}
}
- cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
+ cell.setStyleRanges(styleRanges
+ .toArray(new StyleRange[styleRanges.size()]));
} else {
cell.setForeground(gray);
}
} else if (columnIndex == 0)
super.update(cell);
-
+
cell.setImage(this.getColumnImage(element, columnIndex));
cell.setText(this.getColumnText(element, columnIndex));
}
-
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
index 3de94961..61f5205c 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
@@ -20,9 +20,8 @@
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
-
public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
- ITableColorProvider, ITableFontProvider {
+ ITableColorProvider, ITableFontProvider {
private IMessagesBundle locale;
@@ -30,19 +29,19 @@ public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) {
this.locale = iBundle;
}
- //@Override
+ // @Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
- //@Override
+ // @Override
public String getColumnText(Object element, int columnIndex) {
try {
- IKeyTreeNode item = (IKeyTreeNode) element;
+ IKeyTreeNode item = (IKeyTreeNode) element;
IMessage entry = locale.getMessage(item.getMessageKey());
if (entry != null) {
String value = entry.getValue();
- if (value.length() > 40)
+ if (value.length() > 40)
value = value.substring(0, 39) + "...";
}
} catch (Exception e) {
@@ -52,7 +51,7 @@ public String getColumnText(Object element, int columnIndex) {
@Override
public Color getBackground(Object element, int columnIndex) {
- return null;//return new Color(Display.getDefault(), 255, 0, 0);
+ return null;// return new Color(Display.getDefault(), 255, 0, 0);
}
@Override
@@ -63,7 +62,7 @@ public Color getForeground(Object element, int columnIndex) {
@Override
public Font getFont(Object element, int columnIndex) {
- return null; //UIUtils.createFont(SWT.BOLD);
+ return null; // UIUtils.createFont(SWT.BOLD);
}
@Override
@@ -72,8 +71,8 @@ public void update(ViewerCell cell) {
int columnIndex = cell.getColumnIndex();
cell.setImage(this.getColumnImage(element, columnIndex));
cell.setText(this.getColumnText(element, columnIndex));
-
+
super.update(cell);
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
index 8541037d..e60e0081 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
@@ -20,11 +20,10 @@
public class ValuedKeyTreeItemSorter extends ViewerSorter {
- private StructuredViewer viewer;
- private SortInfo sortInfo;
-
- public ValuedKeyTreeItemSorter (StructuredViewer viewer,
- SortInfo sortInfo) {
+ private StructuredViewer viewer;
+ private SortInfo sortInfo;
+
+ public ValuedKeyTreeItemSorter(StructuredViewer viewer, SortInfo sortInfo) {
this.viewer = viewer;
this.sortInfo = sortInfo;
}
@@ -52,24 +51,27 @@ public int compare(Viewer viewer, Object e1, Object e2) {
return super.compare(viewer, e1, e2);
IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
-
+
int result = 0;
-
+
if (sortInfo == null)
return 0;
-
+
if (sortInfo.getColIdx() == 0)
result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
else {
- Locale loc = sortInfo.getVisibleLocales().get(sortInfo.getColIdx()-1);
- result = (comp1.getValue(loc) == null ? "" : comp1.getValue(loc))
- .compareTo((comp2.getValue(loc) == null ? "" : comp2.getValue(loc)));
+ Locale loc = sortInfo.getVisibleLocales().get(
+ sortInfo.getColIdx() - 1);
+ result = (comp1.getValue(loc) == null ? "" : comp1
+ .getValue(loc))
+ .compareTo((comp2.getValue(loc) == null ? "" : comp2
+ .getValue(loc)));
}
-
+
return result * (sortInfo.isDESC() ? -1 : 1);
} catch (Exception e) {
return 0;
}
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
index 1e162d90..af681415 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
@@ -15,26 +15,29 @@
public class Logger {
- public static void logInfo (String message) {
+ public static void logInfo(String message) {
log(IStatus.INFO, IStatus.OK, message, null);
}
-
- public static void logError (Throwable 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 log(int severity, int code, String message, Throwable 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);
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
index f2cd2b56..b8a920c8 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
@@ -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.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.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);
+ 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) {
+ }
}
- }
- } 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);
+ 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;
}
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
- }.schedule();
- }
+ }.schedule();
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java
index d2979e6f..cf1e43f1 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java
@@ -27,115 +27,115 @@
public class InternationalizationNature implements IProjectNature {
- private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
- private IProject project;
+ private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
+ private IProject project;
+
+ @Override
+ public void configure() throws CoreException {
+ I18nBuilder.addBuilderToProject(project);
+ new Job("Audit source files") {
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ project.build(I18nBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, monitor);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ return Status.OK_STATUS;
+ }
+
+ }.schedule();
+ }
+
+ @Override
+ public void deconfigure() throws CoreException {
+ I18nBuilder.removeBuilderFromProject(project);
+ }
+
+ @Override
+ public IProject getProject() {
+ return project;
+ }
+
+ @Override
+ public void setProject(IProject project) {
+ this.project = project;
+ }
+
+ public static void addNature(IProject project) {
+ if (!project.isOpen())
+ return;
+
+ IProjectDescription description = null;
+
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index != -1)
+ return;
- @Override
- public void configure() throws CoreException {
- I18nBuilder.addBuilderToProject(project);
- new Job("Audit source files") {
+ // Add the nature
+ newIds.add(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
- @Override
- protected IStatus run(IProgressMonitor monitor) {
try {
- project.build(I18nBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, monitor);
+ project.setDescription(description, null);
} 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;
}
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String>();
- newIds.addAll(Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf(NATURE_ID);
- if (index != -1)
- return;
-
- // Add the nature
- newIds.add(NATURE_ID);
- description.setNatureIds(newIds.toArray(new String[newIds.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
+ public static boolean supportsNature(IProject project) {
+ return project.isOpen();
}
- }
-
- public static boolean 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 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;
- }
+ 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()]));
- // 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);
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
- }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java
index 7a7fd4a8..1b95b872 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java
@@ -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 boolean hasResolutions(IMarker marker) {
+ return true;
+ }
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
- EditorUtils.updateMarker(marker);
+ EditorUtils.updateMarker(marker);
- String contextId = marker.getAttribute("context", "");
+ String contextId = marker.getAttribute("context", "");
- // find resolution generator for the given context
- try {
- I18nAuditor auditor = I18nBuilder
- .getI18nAuditorByContext(contextId);
- List<IMarkerResolution> resolutions = auditor
- .getMarkerResolutions(marker);
- return resolutions
- .toArray(new IMarkerResolution[resolutions.size()]);
- } catch (NoSuchResourceAuditorException e) {
- }
+ // 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];
- }
+ return new IMarkerResolution[0];
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java
index 5cafd49d..3c9d0e84 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java
@@ -21,19 +21,19 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.ui.IMarkerResolution;
-
public class RBAuditor extends I18nResourceAuditor {
@Override
public void audit(IResource resource) {
if (RBFileUtils.isResourceBundleFile(resource)) {
- ResourceBundleManager.getManager(resource.getProject()).addBundleResource (resource);
+ ResourceBundleManager.getManager(resource.getProject())
+ .addBundleResource(resource);
}
}
@Override
public String[] getFileEndings() {
- return new String [] { "properties" };
+ return new String[] { "properties" };
}
@Override
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
index 90715d66..5e5d8d7a 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
@@ -20,12 +20,11 @@
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
-
public class ResourceBundleDetectionVisitor implements IResourceVisitor,
- IResourceDeltaVisitor {
+ IResourceDeltaVisitor {
private IProject project = null;
-
+
public ResourceBundleDetectionVisitor(IProject project) {
this.project = project;
}
@@ -34,10 +33,12 @@ public ResourceBundleDetectionVisitor(IProject project) {
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);
- }
+ Logger.logInfo("Loading Resource-Bundle file '"
+ + resource.getName() + "'");
+ if (!ResourceBundleManager.isResourceExcluded(resource)) {
+ ResourceBundleManager.getManager(project)
+ .addBundleResource(resource);
+ }
return false;
} else {
return true;
@@ -52,11 +53,11 @@ public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
if (RBFileUtils.isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
return false;
}
-
+
return true;
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java
index 6a6fee78..c83d93c2 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java
@@ -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/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java
index 29648582..177d4428 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java
@@ -23,23 +23,24 @@
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;
-
public class IncludeResource implements IMarkerResolution2 {
private String bundleName;
private Set<IResource> bundleResources;
-
- public IncludeResource (String bundleName, Set<IResource> bundleResources) {
+
+ 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";
+ 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
@@ -60,8 +61,10 @@ public void run(final IMarker marker) {
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());
+ 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);
@@ -69,7 +72,8 @@ public void run(IProgressMonitor pm) {
pm.done();
}
});
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java
index a24f6012..f485987e 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java
@@ -18,58 +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);
-
- /**
- * 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();
+ /**
+ * 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 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 supported file endings.
+ *
+ * @return The supported file endings
+ */
+ public abstract String[] getFileEndings();
- /**
- * 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;
- }
+ /**
+ * Returns a list of quick fixes of a reported Internationalization problem.
+ *
+ * @param marker
+ * The warning marker of the Internationalization problem
+ * @param cause
+ * The problem type
+ * @return The list of marker resolution proposals
+ */
+ public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker);
+
+ /**
+ * Checks if the provided resource auditor is responsible for a particular
+ * resource.
+ *
+ * @param resource
+ * The resource reference
+ * @return True if the resource auditor is responsible for the referenced
+ * resource
+ */
+ public boolean isResourceOfType(IResource resource) {
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java
index d5fbb37d..3139dc32 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java
@@ -17,37 +17,39 @@
*
*
*/
-public abstract class I18nRBAuditor extends I18nAuditor{
-
+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.
+ * 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.
+ * 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();
+
+ // public abstract List<ILocation> getUnusedKeyReferences();
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java
index 38427431..3893742a 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java
@@ -22,86 +22,85 @@
* stored within the object's internal data structure and can be queried with
* the help of problem categorized getter methods.
*/
-public abstract class I18nResourceAuditor extends I18nAuditor{
- /**
- * Audits a project resource for I18N problems. This method is triggered
- * during the project's build process.
- *
- * @param resource
- * The project resource
- */
- public abstract void audit(IResource resource);
+public abstract class I18nResourceAuditor extends I18nAuditor {
+ /**
+ * Audits a project resource for I18N problems. This method is triggered
+ * during the project's build process.
+ *
+ * @param resource
+ * The project resource
+ */
+ public abstract void audit(IResource resource);
- /**
- * Returns a list of supported file endings.
- *
- * @return The supported file endings
- */
- public abstract String[] getFileEndings();
+ /**
+ * Returns 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/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 5b44a6d6..d8a77ebb 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
@@ -21,40 +21,40 @@
*/
public interface ILocation {
- /**
- * Returns the source resource's physical location.
- *
- * @return The file within the text fragment is located
- */
- public IFile getFile();
-
- /**
- * Returns the position of the text fragments starting character.
- *
- * @return The position of the first character
- */
- public int getStartPos();
-
- /**
- * Returns the position of the text fragments last character.
- *
- * @return The position of the last character
- */
- public int getEndPos();
-
- /**
- * Returns the text fragment.
- *
- * @return The text fragment
- */
- public String getLiteral();
-
- /**
- * Returns additional metadata. The type and content of this property is not
- * specified and can be used to marshal additional data for the computation
- * of resolution proposals.
- *
- * @return The metadata associated with the text fragment
- */
- public Serializable getData();
+ /**
+ * Returns the source resource's physical location.
+ *
+ * @return The file within the text fragment is located
+ */
+ public IFile getFile();
+
+ /**
+ * Returns the position of the text fragments starting character.
+ *
+ * @return The position of the first character
+ */
+ public int getStartPos();
+
+ /**
+ * Returns the position of the text fragments last character.
+ *
+ * @return The position of the last character
+ */
+ public int getEndPos();
+
+ /**
+ * Returns the text fragment.
+ *
+ * @return The text fragment
+ */
+ public String getLiteral();
+
+ /**
+ * Returns additional metadata. The type and content of this property is not
+ * specified and can be used to marshal additional data for the computation
+ * of resolution proposals.
+ *
+ * @return The metadata associated with the text fragment
+ */
+ public Serializable getData();
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
index 65b77225..b5a62072 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
@@ -14,7 +14,7 @@ public interface IMarkerConstants {
public static final int CAUSE_BROKEN_REFERENCE = 0;
public static final int CAUSE_CONSTANT_LITERAL = 1;
public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
-
+
public static final int CAUSE_UNSPEZIFIED_KEY = 3;
public static final int CAUSE_SAME_VALUE = 4;
public static final int CAUSE_MISSING_LANGUAGE = 5;
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
index 31d98ac4..a13886a6 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
@@ -14,6 +14,6 @@
public interface IResourceBundleChangedListener {
- public void resourceBundleChanged (ResourceBundleChangedEvent event);
-
+ public void resourceBundleChanged(ResourceBundleChangedEvent event);
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
index 3579810b..7a9b5b00 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
@@ -12,20 +12,20 @@
public interface IResourceDescriptor {
- public void setProjectName (String projName);
-
- public void setRelativePath (String relPath);
-
- public void setAbsolutePath (String absPath);
-
- public void setBundleId (String bundleId);
-
- public String getProjectName ();
-
- public String getRelativePath ();
-
- public String getAbsolutePath ();
-
- public String getBundleId ();
-
+ public void setProjectName(String projName);
+
+ public void setRelativePath(String relPath);
+
+ public void setAbsolutePath(String absPath);
+
+ public void setBundleId(String bundleId);
+
+ public String getProjectName();
+
+ public String getRelativePath();
+
+ public String getAbsolutePath();
+
+ public String getBundleId();
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
index bee918de..9492ce65 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
@@ -18,13 +18,13 @@ public class ResourceDescriptor implements IResourceDescriptor {
private String relativePath;
private String absolutePath;
private String bundleId;
-
- public ResourceDescriptor (IResource resource) {
+
+ public ResourceDescriptor(IResource resource) {
projectName = resource.getProject().getName();
relativePath = resource.getProjectRelativePath().toString();
absolutePath = resource.getRawLocation().toString();
}
-
+
public ResourceDescriptor() {
}
@@ -52,7 +52,7 @@ public int hashCode() {
public boolean equals(Object other) {
if (!(other instanceof ResourceDescriptor))
return false;
-
+
return absolutePath.equals(absolutePath);
}
@@ -81,5 +81,4 @@ public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
-
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
index 84e3c57c..1afbb963 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
@@ -15,16 +15,15 @@
import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
import org.eclipse.core.resources.IFile;
-
public class SLLocation implements Serializable, ILocation {
-
+
private static final long serialVersionUID = 1L;
private IFile file = null;
private int startPos = -1;
private int endPos = -1;
private String literal;
private Serializable data;
-
+
public SLLocation(IFile file, int startPos, int endPos, String literal) {
super();
this.file = file;
@@ -32,32 +31,41 @@ public SLLocation(IFile file, int startPos, int endPos, String literal) {
this.endPos = endPos;
this.literal = literal;
}
+
public IFile getFile() {
return file;
}
+
public void setFile(IFile file) {
this.file = file;
}
+
public int getStartPos() {
return startPos;
}
+
public void setStartPos(int startPos) {
this.startPos = startPos;
}
+
public int getEndPos() {
return endPos;
}
+
public void setEndPos(int endPos) {
this.endPos = endPos;
}
+
public String getLiteral() {
return literal;
}
- public Serializable getData () {
+
+ public Serializable getData() {
return data;
}
- public void setData (Serializable data) {
+
+ public void setData(Serializable data) {
this.data = data;
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
index 51eda8e6..40331555 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
@@ -14,12 +14,12 @@ public class ResourceBundleException extends Exception {
private static final long serialVersionUID = -2039182473628481126L;
- public ResourceBundleException (String msg) {
- super (msg);
+ public ResourceBundleException(String msg) {
+ super(msg);
}
-
- public ResourceBundleException () {
+
+ public ResourceBundleException() {
super();
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java
index 4dca02df..144ea304 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java
@@ -25,10 +25,10 @@ public void resourceChanged(IResourceChangeEvent event) {
try {
event.getDelta().accept(new IResourceDeltaVisitor() {
@Override
- public boolean visit(IResourceDelta delta) throws CoreException {
+ public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
if (RBFileUtils.isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
return false;
}
return true;
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
index 4e4079b7..d1344cf2 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
@@ -19,29 +19,29 @@ public class ResourceBundleChangedEvent {
public final static int MODIFIED = 2;
public final static int EXCLUDED = 3;
public final static int INCLUDED = 4;
-
+
private IProject project;
private String bundle = "";
private int type = -1;
-
- public ResourceBundleChangedEvent (int type, String bundle, IProject project) {
+
+ public ResourceBundleChangedEvent(int type, String bundle, IProject project) {
this.type = type;
this.bundle = bundle;
this.project = project;
}
-
+
public IProject getProject() {
return project;
}
-
+
public void setProject(IProject project) {
this.project = project;
}
-
+
public String getBundle() {
return bundle;
}
-
+
public void setBundle(String bundle) {
this.bundle = bundle;
}
@@ -49,7 +49,7 @@ public void setBundle(String bundle) {
public int getType() {
return type;
}
-
+
public void setType(int type) {
this.type = type;
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
index 578d190c..8e60b52b 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
@@ -541,7 +541,11 @@ public boolean visit(IResource resource) throws CoreException {
Logger.logError(e);
}
- (new I18nBuilder()).buildResource(res, null);
+ try {
+ res.touch(null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
// Check if the included resource represents a resource-bundle
if (RBFileUtils.isResourceBundleFile(res)) {
@@ -553,7 +557,13 @@ public boolean visit(IResource resource) throws CoreException {
// this.loadResourceBundle(bundleName);
if (newRB) {
- (new I18nBuilder()).buildProject(null, res.getProject());
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
fireResourceBundleChangedEvent(getResourceBundleId(res),
new ResourceBundleChangedEvent(
@@ -817,10 +827,9 @@ public boolean isResourceExisting(String bundleId, String key) {
return keyExists;
}
- public static void refreshResource(IResource resource) {
+ public static void rebuildProject(IResource resource) {
try {
- resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, null);
+ resource.touch(null);
} catch (CoreException e) {
Logger.logError(e);
}
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 d29de40c..35611b04 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
@@ -28,5 +28,5 @@ public void setChangedResources(Collection<Object> changedResources) {
public Collection<Object> getChangedResources() {
return changedResources;
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java
index 29e19226..28a3a03a 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java
@@ -14,15 +14,15 @@
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
-public class CheckItem{
+public class CheckItem {
boolean checked;
String name;
-
+
public CheckItem(String item, boolean checked) {
this.name = item;
this.checked = checked;
}
-
+
public String getName() {
return name;
}
@@ -30,15 +30,15 @@ public String getName() {
public boolean getChecked() {
return checked;
}
-
- public TableItem toTableItem(Table table){
+
+ public TableItem toTableItem(Table table) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(name);
item.setChecked(checked);
return item;
}
-
- public boolean equals(CheckItem item){
+
+ public boolean equals(CheckItem item) {
return name.equals(item.getName());
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
index 5ca700d8..c5355648 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
@@ -27,13 +27,14 @@ public TapiJIPreferenceInitializer() {
public void initializeDefaultPreferences() {
IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
- //ResourceBundle-Settings
+ // 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));
-
+ prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN,
+ TapiJIPreferences.convertListToString(patterns));
+
// Builder
prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
@@ -41,5 +42,5 @@ public void initializeDefaultPreferences() {
prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java
index 127924e0..31eb0b5c 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java
@@ -26,34 +26,31 @@ public class TapiJIPreferences implements IConfiguration {
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 IPreferenceStore PREF = Activator.getDefault()
+ .getPreferenceStore();
+
private static final String DELIMITER = ";";
private static final String ATTRIBUTE_DELIMITER = ":";
-
+
public boolean getAuditSameValue() {
return PREF.getBoolean(AUDIT_SAME_VALUE);
}
-
public boolean getAuditMissingValue() {
return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY);
}
-
public boolean getAuditMissingLanguage() {
return PREF.getBoolean(AUDIT_MISSING_LANGUAGE);
}
-
public boolean getAuditRb() {
return PREF.getBoolean(AUDIT_RB);
}
-
public boolean getAuditResource() {
return PREF.getBoolean(AUDIT_RESOURCE);
}
@@ -61,7 +58,7 @@ public boolean getAuditResource() {
public String getNonRbPattern() {
return PREF.getString(NON_RB_PATTERN);
}
-
+
public static List<CheckItem> getNonRbPatternAsList() {
return convertStringToList(PREF.getString(NON_RB_PATTERN));
}
@@ -72,41 +69,47 @@ public static List<CheckItem> convertStringToList(String string) {
List<CheckItem> elements = new LinkedList<CheckItem>();
for (int i = 0; i < tokenCount; i++) {
- StringTokenizer attribute = new StringTokenizer(tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
+ StringTokenizer attribute = new StringTokenizer(
+ tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
String name = attribute.nextToken();
boolean checked;
- if (attribute.nextToken().equals("true")) checked = true;
- else checked = false;
-
+ 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){
+
+ 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())
+ 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 addPropertyChangeListener(
+ IPropertyChangeListener listener) {
+ Activator.getDefault().getPreferenceStore()
+ .addPropertyChangeListener(listener);
+ }
- public static void removePropertyChangeListener(IPropertyChangeListener listener) {
- Activator.getDefault().getPreferenceStore().removePropertyChangeListener(listener);
+ public static void removePropertyChangeListener(
+ IPropertyChangeListener listener) {
+ Activator.getDefault().getPreferenceStore()
+ .removePropertyChangeListener(listener);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java
index 22f98efa..66230401 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java
@@ -18,34 +18,34 @@
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) {
+ 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) {
@@ -55,119 +55,121 @@ public void saveState (IMemento memento) {
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);
+
+ IMemento memMatchingPrec = memento
+ .createChild(TAG_MATCHING_PRECISION);
memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
-
- selectedProjectName = selectedProjectName != null ? selectedProjectName : "";
+
+ selectedProjectName = selectedProjectName != null ? selectedProjectName
+ : "";
selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
-
+
IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
memSP.putString(TAG_VALUE, selectedProjectName);
-
+
IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
memSB.putString(TAG_VALUE, selectedBundleId);
-
+
IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
memSStr.putString(TAG_VALUE, searchString);
-
+
IMemento memEditable = memento.createChild(TAG_EDITABLE);
memEditable.putBoolean(TAG_ENABLED, editable);
} catch (Exception e) {
-
+
}
}
-
- public void init (IMemento memento) {
+
+ 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);
+ 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 (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) {
+
+ 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;
}
@@ -183,7 +185,7 @@ public void setSelectedProjectName(String selectedProjectName) {
public void setSearchString(String searchString) {
this.searchString = searchString;
}
-
+
public String getSelectedBundleId() {
return selectedBundleId;
}
@@ -207,9 +209,9 @@ public void setEditable(boolean editable) {
public float getMatchingPrecision() {
return matchingPrecision;
}
-
- public void setMatchingPrecision (float value) {
+
+ public void setMatchingPrecision(float value) {
this.matchingPrecision = value;
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java
index c907c676..896e402a 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java
@@ -15,13 +15,12 @@
import org.eclipse.ui.IMemento;
-
public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
+
+ 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;
@@ -50,13 +49,13 @@ public List<Locale> getVisibleLocales() {
return visibleLocales;
}
- public void saveState (IMemento memento) {
+ 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) {
+
+ public void init(IMemento memento) {
IMemento mCI = memento.getChild(TAG_SORT_INFO);
if (mCI == null)
return;
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 38cd8def..5733d1c9 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
@@ -34,36 +34,37 @@
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
-
public class EditorUtils {
-
+
/** Marker constants **/
public static final String MARKER_ID = Activator.PLUGIN_ID
- + ".StringLiteralAuditMarker";
- public static final String RB_MARKER_ID = Activator.PLUGIN_ID + ".ResourceBundleAuditMarker";
-
+ + ".StringLiteralAuditMarker";
+ public static final String RB_MARKER_ID = Activator.PLUGIN_ID
+ + ".ResourceBundleAuditMarker";
+
/** Error messages **/
public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
-
- public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
- public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
+
+ public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
+ public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
-
+
/** Editor ids **/
public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
-
- public static String getFormattedMessage (String pattern, Object[] arguments) {
+
+ public static String getFormattedMessage(String pattern, Object[] arguments) {
String formattedMessage = "";
-
+
MessageFormat formatter = new MessageFormat(pattern);
formattedMessage = formatter.format(arguments);
-
+
return formattedMessage;
}
-
- public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String editor) {
+
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
+ String editor) {
// open the rb-editor for this file type
try {
return IDE.openEditor(page, file, editor);
@@ -72,18 +73,20 @@ public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String ed
}
return null;
}
-
- public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String editor, String key) {
- // open the rb-editor for this file type and selects given msg key
+
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
+ String editor, String key) {
+ // open the rb-editor for this file type and selects given msg key
IEditorPart part = openEditor(page, file, editor);
if (part instanceof IMessagesEditor) {
IMessagesEditor msgEditor = (IMessagesEditor) part;
msgEditor.setSelectedKey(key);
- }
+ }
return part;
}
-
- public static void reportToMarker(String string, ILocation problem, int cause, String key, ILocation data, String context) {
+
+ public static void reportToMarker(String string, ILocation problem,
+ int cause, String key, ILocation data, String context) {
try {
IMarker marker = problem.getFile().createMarker(MARKER_ID);
marker.setAttribute(IMarker.MESSAGE, string);
@@ -98,23 +101,28 @@ public static void reportToMarker(String string, ILocation problem, int cause, S
marker.setAttribute("bundleStart", data.getStartPos());
marker.setAttribute("bundleEnd", data.getEndPos());
}
-
+
// TODO: init attributes
marker.setAttribute("stringLiteral", string);
} catch (CoreException e) {
Logger.logError(e);
return;
}
-
+
Logger.logInfo(string);
}
- public static void reportToRBMarker(String string, ILocation problem, int cause, String key, String problemPartnerFile, ILocation data, String context) {
+ public static void reportToRBMarker(String string, ILocation problem,
+ int cause, String key, String problemPartnerFile, ILocation data,
+ String context) {
try {
- if (!problem.getFile().exists()) return;
+ if (!problem.getFile().exists())
+ return;
IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); //TODO better-dirty implementation
+ marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); // TODO
+ // better-dirty
+ // implementation
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
marker.setAttribute("cause", cause);
marker.setAttribute("key", key);
@@ -129,14 +137,15 @@ public static void reportToRBMarker(String string, ILocation problem, int cause,
Logger.logError(e);
return;
}
-
+
Logger.logInfo(string);
}
-
+
public static boolean deleteAuditMarkersForResource(IResource resource) {
try {
- if (resource != null && resource.exists()) {
- resource.deleteMarkers(MARKER_ID, false, IResource.DEPTH_INFINITE);
+ if (resource != null && resource.exists()) {
+ resource.deleteMarkers(MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
deleteAllAuditRBMarkersFromRB(resource);
}
} catch (CoreException e) {
@@ -145,66 +154,71 @@ public static boolean deleteAuditMarkersForResource(IResource resource) {
}
return true;
}
-
+
/*
* Delete all RB_MARKER from the hole resourcebundle
*/
- private static boolean deleteAllAuditRBMarkersFromRB(IResource resource) throws CoreException{
-// if (resource.findMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE).length > 0)
- if (RBFileUtils.isResourceBundleFile(resource)){
- String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile)resource);
- if (rbId==null) return true; //file in no resourcebundle
-
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(resource.getProject());
- for(IResource r : rbmanager.getResourceBundles(rbId))
- r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
- }
+ private static boolean deleteAllAuditRBMarkersFromRB(IResource resource)
+ throws CoreException {
+ // if (resource.findMarkers(RB_MARKER_ID, false,
+ // IResource.DEPTH_INFINITE).length > 0)
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ String rbId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) resource);
+ if (rbId == null)
+ return true; // file in no resourcebundle
+
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(resource.getProject());
+ for (IResource r : rbmanager.getResourceBundles(rbId))
+ r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
+ }
return true;
}
-
- public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add){
+
+ public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add) {
IMarker[] old_ms = ms;
ms = new IMarker[old_ms.length + ms_to_add.length];
System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
-
+
return ms;
}
-
+
public static void updateMarker(IMarker marker) {
FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
-
- AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel)
- getAnnotationModel(marker);
- IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
-
+ (IFile) marker.getResource());
+
+ AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) getAnnotationModel(marker);
+ IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
+
try {
model.updateMarker(doc, marker, getCurPosition(marker, model));
} catch (CoreException e) {
Logger.logError(e);
}
}
-
+
public static IAnnotationModel getAnnotationModel(IMarker marker) {
FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
-
+ (IFile) marker.getResource());
+
return JavaUI.getDocumentProvider().getAnnotationModel(input);
}
-
- private static Position getCurPosition(IMarker marker, IAnnotationModel model) {
+
+ private static Position getCurPosition(IMarker marker,
+ IAnnotationModel model) {
Iterator iter = model.getAnnotationIterator();
Logger.logInfo("Updates Position!");
while (iter.hasNext()) {
- Object curr = iter.next();
- if (curr instanceof SimpleMarkerAnnotation) {
+ Object curr = iter.next();
+ if (curr instanceof SimpleMarkerAnnotation) {
SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
if (marker.equals(annot.getMarker())) {
- return model.getPosition(annot);
+ return model.getPosition(annot);
}
- }
+ }
}
return null;
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
index db5552bc..6fd3b3de 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
@@ -22,44 +22,48 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.OperationCanceledException;
-
public class FileUtils {
- public static String readFile (IResource resource) {
+ public static String readFile(IResource resource) {
return readFileAsString(resource.getRawLocation().toFile());
}
-
- protected static String readFileAsString(File filePath) {
- String content = "";
-
- try {
- content = org.apache.commons.io.FileUtils.readFileToString(filePath);
- } catch (IOException e) {
- Logger.logError(e);
- }
-
- return content;
- }
+
+ protected static String readFileAsString(File filePath) {
+ String content = "";
+
+ try {
+ content = org.apache.commons.io.FileUtils
+ .readFileToString(filePath);
+ } catch (IOException e) {
+ Logger.logError(e);
+ }
+
+ return content;
+ }
public static File getRBManagerStateFile() {
- return Activator.getDefault().getStateLocation().append("internationalization.xml").toFile();
+ return Activator.getDefault().getStateLocation()
+ .append("internationalization.xml").toFile();
}
/**
- * Don't use that -> causes {@link ResourceException} -> because File out of sync
+ * Don't use that -> causes {@link ResourceException} -> because File out of
+ * sync
+ *
* @param file
* @param editorContent
* @throws CoreException
* @throws OperationCanceledException
*/
- public synchronized void saveTextFile(IFile file, String editorContent)
- throws CoreException, OperationCanceledException {
+ public synchronized void saveTextFile(IFile file, String editorContent)
+ throws CoreException, OperationCanceledException {
try {
- file.setContents(new ByteArrayInputStream(editorContent.getBytes()),
- false, true, null);
+ file.setContents(
+ new ByteArrayInputStream(editorContent.getBytes()), false,
+ true, null);
} catch (Exception e) {
e.printStackTrace();
}
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java
index c655986d..e69b815b 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java
@@ -17,74 +17,86 @@
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
-
public class FontUtils {
/**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
+ * Gets a system color.
+ *
+ * @param colorId
+ * SWT constant
+ * @return system color
+ */
+ public static Color getSystemColor(int colorId) {
+ return Activator.getDefault().getWorkbench().getDisplay()
+ .getSystemColor(colorId);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style (size is unaffected).
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style) {
+ // TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
+ }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style and relative size.
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style, int relSize) {
+ // TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
+ }
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(int style) {
+ return createFont(style, 0);
+ }
+
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(int style, int relSize) {
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
index 0f6f5c33..5e5038fa 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
@@ -15,31 +15,30 @@
import org.eclipse.babel.core.util.PDEUtils;
import org.eclipse.core.resources.IProject;
-public class FragmentProjectUtils{
-
- public static String getPluginId(IProject project){
+public class FragmentProjectUtils {
+
+ public static String getPluginId(IProject project) {
return PDEUtils.getPluginId(project);
}
-
- public static IProject[] lookupFragment(IProject pluginProject){
+ public static IProject[] lookupFragment(IProject pluginProject) {
return PDEUtils.lookupFragment(pluginProject);
}
-
- public static boolean isFragment(IProject pluginProject){
+
+ public static boolean isFragment(IProject pluginProject) {
return PDEUtils.isFragment(pluginProject);
}
-
- public static List<IProject> getFragments(IProject hostProject){
+
+ public static List<IProject> getFragments(IProject hostProject) {
return PDEUtils.getFragments(hostProject);
}
-
- public static String getFragmentId(IProject project, String hostPluginId){
+
+ public static String getFragmentId(IProject project, String hostPluginId) {
return PDEUtils.getFragmentId(project, hostPluginId);
}
-
- public static IProject getFragmentHost(IProject fragment){
+
+ public static IProject getFragmentHost(IProject fragment) {
return PDEUtils.getFragmentHost(fragment);
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java
index 952f93f9..4ee076e2 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java
@@ -14,65 +14,55 @@
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
-
-
/**
* Utility methods related to application UI.
+ *
* @author Pascal Essiembre ([email protected])
* @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $
*/
public final class ImageUtils {
- /** Name of resource bundle image. */
- public static final String IMAGE_RESOURCE_BUNDLE =
- "icons/resourcebundle.gif"; //$NON-NLS-1$
- /** Name of properties file image. */
- public static final String IMAGE_PROPERTIES_FILE =
- "icons/propertiesfile.gif"; //$NON-NLS-1$
- /** Name of properties file entry image */
- public static final String IMAGE_PROPERTIES_FILE_ENTRY =
- "icons/key.gif";
- /** Name of new properties file image. */
- public static final String IMAGE_NEW_PROPERTIES_FILE =
- "icons/newpropertiesfile.gif"; //$NON-NLS-1$
- /** Name of hierarchical layout image. */
- public static final String IMAGE_LAYOUT_HIERARCHICAL =
- "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
- /** Name of flat layout image. */
- public static final String IMAGE_LAYOUT_FLAT =
- "icons/flatLayout.gif"; //$NON-NLS-1$
- public static final String IMAGE_INCOMPLETE_ENTRIES =
- "icons/incomplete.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_ON =
- "icons/int.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_OFF =
- "icons/exclude.png"; //$NON-NLS-1$
- public static final String ICON_RESOURCE =
- "icons/Resource16_small.png";
- public static final String ICON_RESOURCE_INCOMPLETE =
- "icons/Resource16_warning_small.png";
-
- /** Image registry. */
- private static final ImageRegistry imageRegistry = new ImageRegistry();
-
- /**
- * Constructor.
- */
- private ImageUtils() {
- super();
- }
+ /** Name of resource bundle image. */
+ public static final String IMAGE_RESOURCE_BUNDLE = "icons/resourcebundle.gif"; //$NON-NLS-1$
+ /** Name of properties file image. */
+ public static final String IMAGE_PROPERTIES_FILE = "icons/propertiesfile.gif"; //$NON-NLS-1$
+ /** Name of properties file entry image */
+ public static final String IMAGE_PROPERTIES_FILE_ENTRY = "icons/key.gif";
+ /** Name of new properties file image. */
+ public static final String IMAGE_NEW_PROPERTIES_FILE = "icons/newpropertiesfile.gif"; //$NON-NLS-1$
+ /** Name of hierarchical layout image. */
+ public static final String IMAGE_LAYOUT_HIERARCHICAL = "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
+ /** Name of flat layout image. */
+ public static final String IMAGE_LAYOUT_FLAT = "icons/flatLayout.gif"; //$NON-NLS-1$
+ public static final String IMAGE_INCOMPLETE_ENTRIES = "icons/incomplete.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_ON = "icons/int.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_OFF = "icons/exclude.png"; //$NON-NLS-1$
+ public static final String ICON_RESOURCE = "icons/Resource16_small.png";
+ public static final String ICON_RESOURCE_INCOMPLETE = "icons/Resource16_warning_small.png";
+
+ /** Image registry. */
+ private static final ImageRegistry imageRegistry = new ImageRegistry();
+
+ /**
+ * Constructor.
+ */
+ private ImageUtils() {
+ super();
+ }
- /**
- * Gets an image.
- * @param imageName image name
- * @return image
- */
- public static Image getImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
+ /**
+ * Gets an image.
+ *
+ * @param imageName
+ * image name
+ * @return image
+ */
+ public static Image getImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java
index 247aab8a..d7f3ceae 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java
@@ -30,135 +30,162 @@
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
-
public class LanguageUtils {
private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY;
-
-
- private static IFile createFile(IContainer container, String fileName, IProgressMonitor monitor) throws CoreException, IOException {
- if (!container.exists()){
- if (container instanceof IFolder){
+
+ 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()){
+ if (!file.exists()) {
InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
file.create(s, true, monitor);
s.close();
}
-
+
return file;
- }
-
+ }
+
/**
* Checks if ResourceBundle provides a given locale. If the locale is not
* provided, creates a new properties-file with the ResourceBundle-basename
* and the index of the given locale.
+ *
* @param project
* @param rbId
* @param locale
*/
- public static void addLanguageToResourceBundle(IProject project, final String rbId, final Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- if (rbManager.getProvidedLocales(rbId).contains(locale)) return;
-
+ public static void addLanguageToResourceBundle(IProject project,
+ final String rbId, final Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
+
+ if (rbManager.getProvidedLocales(rbId).contains(locale))
+ return;
+
final IResource file = rbManager.getRandomFile(rbId);
- final IContainer c = ResourceUtils.getCorrespondingFolders(file.getParent(), project);
-
- new Job("create new propertfile") {
+ 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)
+ 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 += "_" + locale.getLanguage();
+ if (locale.getCountry() != null
+ && !locale.getCountry().equals(""))
+ newFilename += "_" + locale.getCountry();
+ if (locale.getVariant() != null
+ && !locale.getCountry().equals(""))
+ newFilename += "_" + locale.getVariant();
newFilename += ".properties";
-
+
createFile(c, newFilename, monitor);
} catch (CoreException e) {
- Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
+ 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);
+ Logger.logError(
+ "File for locale "
+ + locale
+ + " could not be created in ResourceBundle "
+ + rbId, e);
}
- monitor.done();
+ 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.
+ * 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()){
+ public static void addLanguageToProject(IProject project, Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
+
+ // Audit if all resourecbundles provide this locale. if not - add new
+ // file
+ for (String rbId : rbManager.getResourceBundleIdentifiers()) {
addLanguageToResourceBundle(project, rbId, locale);
}
}
-
-
- private static void deleteFile(IFile file, boolean force, IProgressMonitor monitor) throws CoreException{
+
+ private static void deleteFile(IFile file, boolean force,
+ IProgressMonitor monitor) throws CoreException {
EditorUtils.deleteAuditMarkersForResource(file);
file.delete(force, monitor);
}
-
+
/**
* Removes the properties-file of a given locale from a ResourceBundle, if
- * the ResourceBundle provides the locale.
+ * 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;
-
+ public static void removeFileFromResourceBundle(IProject project,
+ String rbId, Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
+
+ if (!rbManager.getProvidedLocales(rbId).contains(locale))
+ return;
+
final IFile file = rbManager.getResourceBundleFile(rbId, locale);
final String filename = file.getName();
-
+
new Job("remove properties-file") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
deleteFile(file, true, monitor);
} catch (CoreException e) {
-// MessageDialog.openError(Display.getCurrent().getActiveShell(), "Confirm", "File could not be deleted");
- Logger.logError("File could not be deleted",e);
+ // MessageDialog.openError(Display.getCurrent().getActiveShell(),
+ // "Confirm", "File could not be deleted");
+ Logger.logError("File could not be deleted", e);
}
return Status.OK_STATUS;
}
- }.schedule();
+ }.schedule();
}
-
+
/**
- * Removes all properties-files of a given locale from all ResourceBundles of a project.
+ * 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()){
+ public static void removeLanguageFromProject(IProject project, Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
+
+ for (String rbId : rbManager.getResourceBundleIdentifiers()) {
removeFileFromResourceBundle(project, rbId, locale);
}
}
-
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java
index 76a90ea0..64750be5 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java
@@ -17,26 +17,34 @@
public class LocaleUtils {
- public static Locale getLocaleByDisplayName (Set<Locale> locales, String displayName) {
+ 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))) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (name.equals(displayName)
+ || (name.trim().length() == 0 && displayName
+ .equals(ResourceBundleManager.defaultLocaleTag))) {
return l;
}
}
-
+
return null;
}
-
- public static boolean containsLocaleByDisplayName(Set<Locale> locales, String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
- return true;
- }
- }
-
- return false;
+
+ public static boolean containsLocaleByDisplayName(Set<Locale> locales,
+ String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (name.equals(displayName)
+ || (name.trim().length() == 0 && displayName
+ .equals(ResourceBundleManager.defaultLocaleTag))) {
+ return true;
+ }
+ }
+
+ return false;
}
-
+
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
index bcd1cc8f..e824855e 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
@@ -32,7 +32,8 @@ public OverlayIcon(Image baseImage, Image overlayImage, int location) {
this.img = baseImage;
this.overlay = overlayImage;
this.location = location;
- this.imgSize = new Point(baseImage.getImageData().width, baseImage.getImageData().height);
+ this.imgSize = new Point(baseImage.getImageData().width,
+ baseImage.getImageData().height);
}
@Override
@@ -52,7 +53,7 @@ protected void drawCompositeImage(int width, int height) {
break;
case BOTTOM_RIGHT:
drawImage(imageData, imgSize.x - imageData.width, imgSize.y
- - imageData.height);
+ - imageData.height);
break;
}
}
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 c496ed82..66ed394d 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
@@ -27,76 +27,84 @@
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
-
/**
*
* @author mgasser
- *
+ *
*/
-public class RBFileUtils extends Action{
+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")){
+
+ 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
+
+ // 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())){
+
+ 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 properties-file is not RB-file and has
+ // ResouceBundleMarker, deletes all ResouceBundleMarker
+ // of the file
if (hasResourceBundleMarker(file))
try {
- file.deleteMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE);
+ file.deleteMarkers(EditorUtils.RB_MARKER_ID,
+ true, IResource.DEPTH_INFINITE);
} catch (CoreException e) {
}
}
}
}
}
-
+
return isValied;
}
-
+
/**
* Checks whether a RB-file has a problem-marker
*/
- public static boolean hasResourceBundleMarker(IResource r){
+ 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;
+ if (r.findMarkers(EditorUtils.RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE).length > 0)
+ return true;
+ else
+ return false;
} catch (CoreException e) {
return false;
}
}
-
/**
* @return the locale of a given properties-file
*/
- public static Locale getLocale(IFile file){
+ public static Locale getLocale(IFile file) {
String localeID = file.getName();
- localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
- String baseBundleName = ResourceBundleManager.getResourceBundleName(file);
-
+ 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
+ locale = null; // Default locale
} else {
localeID = localeID.substring(baseBundleName.length() + 1);
String[] localeTokens = localeID.split("_");
@@ -108,7 +116,8 @@ public static Locale getLocale(IFile file){
locale = new Locale(localeTokens[0], localeTokens[1]);
break;
case 3:
- locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
break;
default:
locale = new Locale("");
@@ -119,63 +128,68 @@ public static Locale getLocale(IFile file){
}
/**
- * @return number of ResourceBundles in the subtree
+ * @return number of ResourceBundles in the subtree
*/
- public static int countRecursiveResourceBundle(IContainer container) {
+ public static int countRecursiveResourceBundle(IContainer container) {
return getSubResourceBundle(container).size();
}
-
-
- private static List<String> getSubResourceBundle(IContainer container){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(container.getProject());
-
+
+ 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))){
+ for (IResource r : rbmanager.getResourceBundles(rbId)) {
+ if (r.getFullPath().toString().contains(conatinerId)
+ && (!subResourceBundles.contains(rbId))) {
subResourceBundles.add(rbId);
}
}
}
return subResourceBundles;
}
-
+
/**
* @param container
* @return Set with all ResourceBundles in this container
*/
- public static Set<String> getResourceBundleIds (IContainer container) {
+ public static Set<String> getResourceBundleIds(IContainer container) {
Set<String> resourcebundles = new HashSet<String>();
-
+
try {
- for(IResource r : container.members()){
+ for (IResource r : container.members()) {
if (r instanceof IFile) {
- String resourcebundle = getCorrespondingResourceBundleId((IFile)r);
- if (resourcebundle != null) resourcebundles.add(resourcebundle);
+ String resourcebundle = getCorrespondingResourceBundleId((IFile) r);
+ if (resourcebundle != null)
+ resourcebundles.add(resourcebundle);
}
}
- } catch (CoreException e) {/*resourcebundle.size()==0*/}
-
+ } catch (CoreException e) {/* resourcebundle.size()==0 */
+ }
+
return resourcebundles;
}
-
+
/**
*
* @param file
- * @return ResourceBundle-name or null if no ResourceBundle contains the 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());
+ // TODO integrate in ResourceBundleManager
+ public static String getCorrespondingResourceBundleId(IFile file) {
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file
+ .getProject());
String possibleRBId = null;
-
+
if (isResourceBundleFile((IFile) file)) {
possibleRBId = ResourceBundleManager.getResourceBundleId(file);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- if ( possibleRBId.equals(rbId) )
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ if (possibleRBId.equals(rbId))
return possibleRBId;
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java
index 39334de6..19a09471 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java
@@ -19,90 +19,99 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
-
public class ResourceUtils {
- private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*";
- private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
-
- public static boolean isValidResourceKey (String key) {
+ private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*";
+ private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
+
+ public static boolean isValidResourceKey(String key) {
boolean isValid = false;
-
+
if (key != null && key.trim().length() > 0) {
isValid = key.matches(REGEXP_RESOURCE_KEY);
}
-
+
return isValid;
}
-
- public static String deriveNonExistingRBName (String nameProposal, ResourceBundleManager manager) {
+
+ 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, "");
-
+ nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME,
+ "");
+
int i = 0;
do {
- if (manager.getResourceBundleIdentifiers().contains(nameProposal) || nameProposal.length() == 0) {
+ if (manager.getResourceBundleIdentifiers().contains(nameProposal)
+ || nameProposal.length() == 0) {
nameProposal = nameProposal + (++i);
} else
break;
} while (true);
-
+
return nameProposal;
}
-
- public static boolean isJavaCompUnit (IResource res) {
+
+ public static boolean isJavaCompUnit(IResource res) {
boolean result = false;
-
- if (res.getType() == IResource.FILE && !res.isDerived() &&
- res.getFileExtension().equalsIgnoreCase("java")) {
+
+ if (res.getType() == IResource.FILE && !res.isDerived()
+ && res.getFileExtension().equalsIgnoreCase("java")) {
result = true;
}
-
+
return result;
}
public static boolean isJSPResource(IResource res) {
boolean result = false;
-
- if (res.getType() == IResource.FILE && !res.isDerived() &&
- (res.getFileExtension().equalsIgnoreCase("jsp") ||
- res.getFileExtension().equalsIgnoreCase("xhtml"))) {
+
+ if (res.getType() == IResource.FILE
+ && !res.isDerived()
+ && (res.getFileExtension().equalsIgnoreCase("jsp") || res
+ .getFileExtension().equalsIgnoreCase("xhtml"))) {
result = true;
}
-
+
return result;
}
-
+
/**
*
* @param baseFolder
- * @param targetProjects Projects with a same structure
- * @return List of
+ * @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;
- }
+ public static List<IContainer> getCorrespondingFolders(
+ IContainer baseFolder, List<IProject> targetProjects) {
+ List<IContainer> correspondingFolder = new ArrayList<IContainer>();
+
+ for (IProject p : targetProjects) {
+ IContainer c = getCorrespondingFolders(baseFolder, p);
+ if (c.exists())
+ correspondingFolder.add(c);
+ }
+
+ return correspondingFolder;
+ }
/**
*
* @param baseFolder
* @param targetProject
- * @return a Container with the corresponding path as the baseFolder. The Container doesn't must exist.
+ * @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())
+ 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
+ else
return targetProject;
}
-
+
}
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 160b5c78..1919674d 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
@@ -7,6 +7,7 @@
******************************************************************************/
package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+import org.eclipse.babel.tapiji.tools.core.Logger;
import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
@@ -61,23 +62,24 @@ public void apply(IDocument document) {
dialog.setDialogConfiguration(config);
- if (dialog.open() != InputDialog.OK)
+ if (dialog.open() != InputDialog.OK) {
return;
+ }
String resourceBundleId = dialog.getSelectedResourceBundle();
String key = dialog.getSelectedKey();
try {
- if (!bundleContext)
+ if (!bundleContext) {
reference = ASTutils.insertNewBundleRef(document, resource,
startPos, endPos - startPos, resourceBundleId, key);
- else {
+ } else {
document.replace(startPos, endPos - startPos, key);
reference = key + "\"";
}
- ResourceBundleManager.refreshResource(resource);
+ ResourceBundleManager.rebuildProject(resource);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
@@ -86,8 +88,9 @@ 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
+ } else {
return "";
+ }
}
@Override
@@ -98,13 +101,15 @@ public IContextInformation getContextInformation() {
@Override
public String getDisplayString() {
String displayStr = "";
- if (bundleContext)
+ if (bundleContext) {
displayStr = "Create a new resource-bundle-entry";
- else
+ } else {
displayStr = "Create a new localized string literal";
+ }
- if (value != null && value.length() > 0)
+ if (value != null && value.length() > 0) {
displayStr += " for '" + value + "'";
+ }
return displayStr;
}
@@ -123,10 +128,11 @@ public Point getSelection(IDocument document) {
@Override
public int getRelevance() {
- if (this.value.trim().length() == 0)
+ if (this.value.trim().length() == 0) {
return 96;
- else
+ } else {
return 1096;
+ }
}
}
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 8c50b5dc..58f1b718 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
@@ -21,90 +21,100 @@
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";
-
+ 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
+ * @throws URISyntaxException
*/
- public static Image getBaseImage(String imageName){
+ 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);
+ if (image == null) {
+ ImageDescriptor descriptor = RBManagerActivator
+ .getImageDescriptor(imageName);
+
+ if (descriptor.getImageData() != null) {
+ image = descriptor.createImage(false);
imageRegistry.put(imageName, image);
- }
- }
-
- return image;
+ }
+ }
+
+ return image;
}
-
+
/**
* @param baseImage
* @return baseImage with a overlay warning-image
*/
- public static Image getImageWithWarning(Image baseImage){
- String imageWithWarningId = baseImage.toString()+".w";
- Image imageWithWarning = imageRegistry.get(imageWithWarningId);
-
- if (imageWithWarning==null){
+ 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();
+ imageWithWarning = new OverlayIcon(baseImage, warningImage,
+ OverlayIcon.BOTTOM_LEFT).createImage();
imageRegistry.put(imageWithWarningId, imageWithWarning);
}
-
+
return imageWithWarning;
}
-
+
/**
*
* @param baseImage
* @return baseImage with a overlay fragment-image
*/
- public static Image getImageWithFragment(Image baseImage){
- String imageWithFragmentId = baseImage.toString()+".f";
- Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
-
- if (imageWithFragment==null){
- Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
- imageWithFragment = new OverlayIcon(baseImage, fragement, OverlayIcon.BOTTOM_RIGHT).createImage();
+ public static Image getImageWithFragment(Image baseImage) {
+ String imageWithFragmentId = baseImage.toString() + ".f";
+ Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
+
+ if (imageWithFragment == null) {
+ Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
+ imageWithFragment = new OverlayIcon(baseImage, fragement,
+ OverlayIcon.BOTTOM_RIGHT).createImage();
imageRegistry.put(imageWithFragmentId, imageWithFragment);
}
-
+
return imageWithFragment;
}
-
+
/**
* @return a Image with a flag of the given country
*/
public static Image getLocalIcon(Locale locale) {
String imageName;
Image image = null;
-
- if (locale != null && !locale.getCountry().equals("")){
- imageName = File.separatorChar+"countries"+File.separatorChar+ locale.getCountry().toLowerCase() +".gif";
+
+ 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";
+ } 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
+ } else {
+ imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale
+ // icon
image = getBaseImage(imageName);
}
}
-
- if (image == null) image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
+
+ 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 a53c8d3c..0b5d62a6 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
@@ -22,8 +22,7 @@ public class RBManagerActivator extends AbstractUIPlugin {
public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.rbmanager"; //$NON-NLS-1$
// The shared instance
private static RBManagerActivator plugin;
-
-
+
/**
* The constructor
*/
@@ -32,7 +31,10 @@ public RBManagerActivator() {
/*
* (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
@@ -41,7 +43,10 @@ public void start(BundleContext context) throws Exception {
/*
* (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
@@ -50,17 +55,17 @@ public void stop(BundleContext context) throws Exception {
/**
* Returns the shared instance
- *
+ *
* @return the shared instance
*/
public static RBManagerActivator getDefault() {
return plugin;
}
-
- public static ImageDescriptor getImageDescriptor(String name){
+
+ public static ImageDescriptor getImageDescriptor(String name) {
String path = "icons/" + name;
-
+
return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
index e36be156..f80ac230 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
@@ -21,20 +21,20 @@ public class RBLocation implements ILocation {
private String language;
private Serializable data;
private ILocation sameValuePartner;
-
-
+
public RBLocation(IFile file, int startPos, int endPos, String language) {
this.file = file;
this.startPos = startPos;
this.endPos = endPos;
this.language = language;
}
-
- public RBLocation(IFile file, int startPos, int endPos, String language, ILocation sameValuePartner) {
+
+ public RBLocation(IFile file, int startPos, int endPos, String language,
+ ILocation sameValuePartner) {
this(file, startPos, endPos, language);
- this.sameValuePartner=sameValuePartner;
+ this.sameValuePartner = sameValuePartner;
}
-
+
@Override
public IFile getFile() {
return file;
@@ -56,15 +56,15 @@ public String getLiteral() {
}
@Override
- public Serializable getData () {
+ public Serializable getData() {
return data;
}
-
- public void setData (Serializable data) {
+
+ public void setData(Serializable data) {
this.data = data;
}
- public ILocation getSameValuePartner(){
+ 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 20ac2c9f..95e92aa9 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
@@ -50,7 +50,6 @@ public class ResourceBundleAuditor extends I18nRBAuditor {
private List<ILocation> missingLanguages = new LinkedList<ILocation>();
private List<String> seenRBs = new LinkedList<String>();
-
@Override
public String[] getFileEndings() {
return new String[] { "properties" };
@@ -102,7 +101,7 @@ public void audit(IResource resource) {
if (!seenRBs.contains(rbId)) {
ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(file.getProject());
+ .getManager(file.getProject());
audit(rbId, rbmanager);
seenRBs.add(rbId);
} else
@@ -113,23 +112,25 @@ public void audit(IResource resource) {
* audits all files of a resourcebundle
*/
public void audit(String rbId, ResourceBundleManager rbmanager) {
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
String[] keys = bundlegroup.getMessageKeys();
-
for (IResource r : bundlefile) {
IFile f1 = (IFile) r;
-
+
for (String key : keys) {
// check if all keys have a value
-
- if (auditUnspecifiedKey(f1, key, bundlegroup)){
- /* do nothing - all just done*/
- }else {
- // check if a key has the same value like a key of an other properties-file
- if (configuration.getAuditSameValue() && bundlefile.size() > 1)
+
+ 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);
@@ -137,22 +138,22 @@ public void audit(String rbId, ResourceBundleManager rbmanager) {
}
}
}
-
- if (configuration.getAuditMissingLanguage()){
+
+ if (configuration.getAuditMissingLanguage()) {
// checks if the resourcebundle supports all project-languages
Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
-
+
auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
}
}
/*
- * Audits the file if the key is not specified. If the value is null reports a
- * problem.
+ * 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) {
+ IMessagesBundleGroup bundlegroup) {
if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
int pos = calculateKeyLine(key, f1);
unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
@@ -162,24 +163,25 @@ private boolean auditUnspecifiedKey(IFile f1, String key,
}
/*
- * 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
+ * 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) {
+ IMessagesBundleGroup bundlegroup) {
Locale l1 = RBFileUtils.getLocale(f1);
Locale l2 = RBFileUtils.getLocale(f2);
- if (!l2.equals(l1) && !(l1.toString().equals("")||l2.toString().equals(""))) {
+ 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())) {
+ .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));
+ new RBLocation(f2, pos2, pos2 + 1, key));
}
}
}
@@ -189,19 +191,20 @@ private void auditSameValues(IFile f1, IFile f2, String key,
* missing languages.
*/
private void auditMissingLanguage(Set<Locale> rbLocales,
- Set<Locale> projectLocales, ResourceBundleManager rbmanager,
- String rbId) {
+ Set<Locale> projectLocales, ResourceBundleManager rbmanager,
+ String rbId) {
for (Locale pLocale : projectLocales) {
if (!rbLocales.contains(pLocale)) {
- String language = pLocale != null ? pLocale.toString() : ResourceBundleManager.defaultLocaleTag;
+ String language = pLocale != null ? pLocale.toString()
+ : ResourceBundleManager.defaultLocaleTag;
// Add Warning to default-file or a random chosen file
IResource representative = rbmanager.getResourceBundleFile(
- rbId, null);
+ rbId, null);
if (representative == null)
representative = rbmanager.getRandomFile(rbId);
missingLanguages.add(new RBLocation((IFile) representative, 1,
- 2, language));
+ 2, language));
}
}
}
@@ -212,20 +215,20 @@ private void auditMissingLanguage(Set<Locale> rbLocales,
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");
-// }
+ // 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) {
@@ -241,8 +244,8 @@ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
switch (marker.getAttribute("cause", -1)) {
case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
- // change
- // Name
+ // change
+ // Name
resolutions.add(new MissingLanguageResolution(l));
break;
}
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 ad80bff9..18013c76 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
@@ -22,21 +22,22 @@
public class MissingLanguageResolution implements IMarkerResolution2 {
private Locale language;
-
- public MissingLanguageResolution(Locale language){
+
+ public MissingLanguageResolution(Locale language) {
this.language = language;
}
-
+
@Override
public String getLabel() {
- return "Add missing language '"+ language +"'";
+ 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);
+ LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId,
+ language);
}
@Override
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 bffdc241..23c516e8 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
@@ -22,23 +22,24 @@ public class VirtualContainer {
protected ResourceBundleManager rbmanager;
protected IContainer container;
protected int rbCount;
-
- public VirtualContainer(IContainer container1, boolean countResourceBundles){
+
+ public VirtualContainer(IContainer container1, boolean countResourceBundles) {
this.container = container1;
rbmanager = ResourceBundleManager.getManager(container.getProject());
- if (countResourceBundles){
- rbCount=1;
- new Job("count ResourceBundles"){
+ if (countResourceBundles) {
+ rbCount = 1;
+ new Job("count ResourceBundles") {
@Override
protected IStatus run(IProgressMonitor monitor) {
recount();
return Status.OK_STATUS;
}
- }.schedule();
- }else rbCount = 0;
+ }.schedule();
+ } else
+ rbCount = 0;
}
-
- protected VirtualContainer(IContainer container){
+
+ protected VirtualContainer(IContainer container) {
this.container = container;
}
@@ -47,25 +48,26 @@ public VirtualContainer(IContainer container, int rbCount) {
this.rbCount = rbCount;
}
- public ResourceBundleManager getResourceBundleManager(){
- if (rbmanager == null)
- rbmanager = ResourceBundleManager.getManager(container.getProject());
+ public ResourceBundleManager getResourceBundleManager() {
+ if (rbmanager == null)
+ rbmanager = ResourceBundleManager
+ .getManager(container.getProject());
return rbmanager;
}
-
+
public IContainer getContainer() {
return container;
}
-
- public void setRbCounter(int rbCount){
+
+ public void setRbCounter(int rbCount) {
this.rbCount = rbCount;
}
public int getRbCount() {
return rbCount;
}
-
- public void recount(){
- rbCount = RBFileUtils.countRecursiveResourceBundle(container);
+
+ public void recount() {
+ rbCount = RBFileUtils.countRecursiveResourceBundle(container);
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
index 1a7b576c..fa90a287 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
@@ -15,19 +15,18 @@
import org.eclipse.core.resources.IContainer;
-
public class VirtualContentManager {
private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>();
private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>();
-
+
static private VirtualContentManager singelton = null;
-
+
private VirtualContentManager() {
}
- public static VirtualContentManager getVirtualContentManager(){
- if (singelton == null){
- singelton = new VirtualContentManager();
+ public static VirtualContentManager getVirtualContentManager() {
+ if (singelton == null) {
+ singelton = new VirtualContentManager();
}
return singelton;
}
@@ -36,29 +35,27 @@ public VirtualContainer getContainer(IContainer container) {
return containers.get(container);
}
-
public void addVContainer(IContainer container, VirtualContainer vContainer) {
containers.put(container, vContainer);
}
- public void removeVContainer(IContainer container){
+ public void removeVContainer(IContainer container) {
vResourceBundles.remove(container);
}
-
+
public VirtualResourceBundle getVResourceBundles(String vRbId) {
return vResourceBundles.get(vRbId);
}
-
- public void addVResourceBundle(String vRbId, VirtualResourceBundle vResourceBundle) {
+ public void addVResourceBundle(String vRbId,
+ VirtualResourceBundle vResourceBundle) {
vResourceBundles.put(vRbId, vResourceBundle);
}
-
- public void removeVResourceBundle(String vRbId){
+
+ public void removeVResourceBundle(String vRbId) {
vResourceBundles.remove(vRbId);
}
-
public boolean containsVResourceBundles(String vRbId) {
return vResourceBundles.containsKey(vRbId);
}
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 ce8b12e4..1748928f 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
@@ -20,14 +20,14 @@
/**
* Representation of a project
- *
+ *
*/
-public class VirtualProject extends VirtualContainer{
+public class VirtualProject extends VirtualContainer {
private boolean isFragment;
private IProject hostProject;
private List<IProject> fragmentProjects = new LinkedList<IProject>();
-
- //Slow
+
+ // Slow
public VirtualProject(IProject project, boolean countResourceBundles) {
super(project, countResourceBundles);
isFragment = FragmentProjectUtils.isFragment(project);
@@ -36,38 +36,39 @@ public VirtualProject(IProject project, boolean countResourceBundles) {
} else
fragmentProjects = FragmentProjectUtils.getFragments(project);
}
-
+
/*
* No fragment search
*/
- public VirtualProject(final IProject project, boolean isFragment, boolean countResourceBundles){
+ 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);
-// }
-// });
+ // Display.getDefault().asyncExec(new Runnable() {
+ // @Override
+ // public void run() {
+ // hostProject = FragmentProjectUtils.getFragmentHost(project);
+ // }
+ // });
}
-
- public Set<Locale> getProvidedLocales(){
+
+ public Set<Locale> getProvidedLocales() {
return rbmanager.getProjectProvidedLocales();
}
-
- public boolean isFragment(){
+
+ public boolean isFragment() {
return isFragment;
}
-
- public IProject getHostProject(){
+
+ public IProject getHostProject() {
return hostProject;
}
public boolean hasFragments() {
return !fragmentProjects.isEmpty();
}
-
- public List<IProject> getFragmets(){
+
+ 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 857dc023..95373235 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
@@ -17,37 +17,35 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
-public class VirtualResourceBundle{
- private String resourcebundlename;
- private String resourcebundleId;
+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 VirtualResourceBundle(String rbname, String rbId,
+ ResourceBundleManager rbmanager) {
+ this.rbmanager = rbmanager;
+ resourcebundlename = rbname;
+ resourcebundleId = rbId;
}
public ResourceBundleManager getResourceBundleManager() {
return rbmanager;
}
- public String getResourceBundleId(){
+ public String getResourceBundleId() {
return resourcebundleId;
}
-
-
+
@Override
- public String toString(){
+ public String toString() {
return resourcebundleId;
}
public IPath getFullPath() {
- return rbmanager.getRandomFile(resourcebundleId).getFullPath();
+ return rbmanager.getRandomFile(resourcebundleId).getFullPath();
}
-
public String getName() {
return resourcebundlename;
}
@@ -56,7 +54,7 @@ public Collection<IResource> getFiles() {
return rbmanager.getResourceBundles(resourcebundleId);
}
- public IFile getRandomFile(){
+ 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 5fc99787..f59c796e 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
@@ -27,42 +27,43 @@
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
-
public class Hover {
private Shell hoverShell;
private Point hoverPosition;
private List<HoverInformant> informant;
-
- public Hover(Shell parent, List<HoverInformant> informant){
+
+ public Hover(Shell parent, List<HoverInformant> informant) {
this.informant = informant;
hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
Display display = hoverShell.getDisplay();
-
+
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.verticalSpacing = 2;
hoverShell.setLayout(gridLayout);
-
- hoverShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- hoverShell.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+
+ 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);
+ 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);
+ Math.min(position.y + 16, displayBounds.height
+ - (shellBounds.height + 1)), 0);
shell.setBounds(shellBounds);
}
-
public void activateHoverHelp(final Control control) {
control.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible()){
+ if (hoverShell != null && hoverShell.isVisible()) {
hoverShell.setVisible(false);
}
}
@@ -74,7 +75,7 @@ public void mouseExit(MouseEvent e) {
hoverShell.setVisible(false);
}
- public void mouseHover(MouseEvent event) {
+ public void mouseHover(MouseEvent event) {
Point pt = new Point(event.x, event.y);
Widget widget = event.widget;
if (widget instanceof ToolBar) {
@@ -94,23 +95,24 @@ public void mouseHover(MouseEvent event) {
return;
}
hoverPosition = control.toDisplay(pt);
-
+
boolean show = false;
- Object data = widget.getData();
-
- for (HoverInformant hi :informant){
+ Object data = widget.getData();
+
+ for (HoverInformant hi : informant) {
hi.getInfoComposite(data, hoverShell);
- if (hi.show()) show= true;
+ if (hi.show())
+ show = true;
}
-
- if (show){
+
+ if (show) {
hoverShell.pack();
hoverShell.layout();
setHoverLocation(hoverShell, hoverPosition);
hoverShell.setVisible(true);
- }
- else hoverShell.setVisible(false);
-
+ } 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 b9fb231b..71a3cd1e 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
@@ -13,8 +13,8 @@
import org.eclipse.swt.widgets.Composite;
public interface HoverInformant {
-
+
public Composite getInfoComposite(Object data, Composite parent);
-
+
public boolean show();
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
index 27966aba..f8780b9c 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
@@ -26,12 +26,12 @@
public class ExpandAllActionDelegate implements IViewActionDelegate {
private CommonViewer viewer;
-
+
@Override
public void run(IAction action) {
- Object data = viewer.getControl().getData();
+ Object data = viewer.getControl().getData();
- for(final IProject p : ((IWorkspaceRoot)data).getProjects()){
+ for (final IProject p : ((IWorkspaceRoot) data).getProjects()) {
UIJob job = new UIJob("expand Projects") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
@@ -39,7 +39,7 @@ public IStatus runInUIThread(IProgressMonitor monitor) {
return Status.OK_STATUS;
}
};
-
+
job.schedule();
}
}
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 f1b3ed72..f0ee4d9c 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
@@ -20,20 +20,18 @@
import org.eclipse.ui.navigator.INavigatorContentService;
import org.eclipse.ui.navigator.INavigatorFilterService;
-
-
-public class ToggleFilterActionDelegate implements IViewActionDelegate{
+public class ToggleFilterActionDelegate implements IViewActionDelegate {
private INavigatorFilterService filterService;
private boolean active;
- private static final String[] FILTER = {RBManagerActivator.PLUGIN_ID+".filter.ProblematicResourceBundleFiles"};
-
+ private static final String[] FILTER = { RBManagerActivator.PLUGIN_ID
+ + ".filter.ProblematicResourceBundleFiles" };
+
@Override
- public void run(IAction action) {
- if (active==true){
+ public void run(IAction action) {
+ if (active == true) {
filterService.activateFilterIdsAndUpdateViewer(new String[0]);
active = false;
- }
- else {
+ } else {
filterService.activateFilterIdsAndUpdateViewer(FILTER);
active = true;
}
@@ -46,22 +44,23 @@ public void selectionChanged(IAction action, ISelection selection) {
@Override
public void init(IViewPart view) {
- INavigatorContentService contentService = ((CommonNavigator) view).getCommonViewer().getNavigatorContentService();
-
+ INavigatorContentService contentService = ((CommonNavigator) view)
+ .getCommonViewer().getNavigatorContentService();
+
filterService = contentService.getFilterService();
filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active=false;
+ active = false;
}
-
@SuppressWarnings("unused")
private String[] getActiveFilterIds() {
- ICommonFilterDescriptor[] fds = filterService.getVisibleFilterDescriptors();
- String activeFilterIds[]=new String[fds.length];
-
- for(int i=0;i<fds.length;i++)
- activeFilterIds[i]=fds[i].getId();
-
+ ICommonFilterDescriptor[] fds = filterService
+ .getVisibleFilterDescriptors();
+ String activeFilterIds[] = new String[fds.length];
+
+ for (int i = 0; i < fds.length; i++)
+ activeFilterIds[i] = fds[i].getId();
+
return activeFilterIds;
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
index 4f5a021e..722c548d 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
@@ -26,22 +26,24 @@
public class LinkHelper implements ILinkHelper {
public static IStructuredSelection viewer;
-
+
@Override
- public IStructuredSelection findSelection(IEditorInput anInput) {
+ public IStructuredSelection findSelection(IEditorInput anInput) {
IFile file = ResourceUtil.getFile(anInput);
- if (file != null) {
- return new StructuredSelection(file);
- }
+ if (file != null) {
+ return new StructuredSelection(file);
+ }
return StructuredSelection.EMPTY;
}
@Override
- public void activateEditor(IWorkbenchPage aPage,IStructuredSelection aSelection) {
+ public void activateEditor(IWorkbenchPage aPage,
+ IStructuredSelection aSelection) {
if (aSelection.getFirstElement() instanceof IFile)
try {
IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
- } catch (PartInitException e) {/**/}
+ } 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 77ca1823..a7c2a92d 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
@@ -52,13 +52,13 @@
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.progress.UIJob;
-
-
/**
*
*
*/
-public class ResourceBundleContentProvider implements ITreeContentProvider, IResourceChangeListener, IPropertyChangeListener, IResourceBundleChangedListener{
+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;
@@ -67,11 +67,13 @@ public class ResourceBundleContentProvider implements ITreeContentProvider, IRes
private IWorkspaceRoot root;
private List<IProject> listenedProjects;
+
/**
*
*/
public ResourceBundleContentProvider() {
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this,
+ IResourceChangeEvent.POST_CHANGE);
TapiJIPreferences.addPropertyChangeListener(this);
vcManager = VirtualContentManager.getVirtualContentManager();
listenedProjects = new LinkedList<IProject>();
@@ -85,121 +87,148 @@ public Object[] getElements(Object inputElement) {
@Override
public Object[] getChildren(final Object parentElement) {
Object[] children = null;
-
+
if (parentElement instanceof IWorkspaceRoot) {
- root = (IWorkspaceRoot) parentElement;
+ root = (IWorkspaceRoot) parentElement;
try {
- IResource[] members = ((IWorkspaceRoot)parentElement).members();
-
+ IResource[] members = ((IWorkspaceRoot) parentElement)
+ .members();
+
List<Object> displayedProjects = new ArrayList<Object>();
for (IResource r : members)
- if (r instanceof IProject){
+ 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);
+ 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){
+ if (SHOW_ONLY_PROJECTS_WITH_RBS) {
VirtualProject vP;
- if ((vP=(VirtualProject) vcManager.getContainer(p))==null){
+ 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 {
+
+ if (vP.getRbCount() > 0)
+ displayedProjects.add(p);
+ } else {
displayedProjects.add(p);
}
}
}
-
+
children = displayedProjects.toArray();
return children;
- } catch (CoreException e) { }
+ } 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 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())
+ if (!((VirtualProject) vcManager
+ .getContainer(((IResource) parentElement).getProject()))
+ .isFragment())
try {
children = addChildren(container);
- } catch (CoreException e) {/**/}
+ } catch (CoreException e) {/**/
+ }
}
-
+
if (parentElement instanceof VirtualResourceBundle) {
VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
- ResourceBundleManager rbmanager = virtualrb.getResourceBundleManager();
- children = rbmanager.getResourceBundles(virtualrb.getResourceBundleId()).toArray();
+ ResourceBundleManager rbmanager = virtualrb
+ .getResourceBundleManager();
+ children = rbmanager.getResourceBundles(
+ virtualrb.getResourceBundleId()).toArray();
}
-
+
return children != null ? children : new Object[0];
}
-
+
/*
- * Returns all ResourceBundles and sub-containers (with ResourceBundles in their subtree) of a Container
+ * 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());
+ private Object[] addChildren(IContainer container) throws CoreException {
+ Map<String, Object> children = new HashMap<String, Object>();
+
+ VirtualProject p = (VirtualProject) vcManager.getContainer(container
+ .getProject());
+ List<IResource> members = new ArrayList<IResource>(
+ Arrays.asList(container.members()));
+
+ // finds files in the corresponding fragment-projects folder
+ if (p.hasFragments()) {
+ List<IContainer> folders = ResourceUtils.getCorrespondingFolders(
+ container, p.getFragmets());
for (IContainer f : folders)
for (IResource r : f.members())
if (r instanceof IFile)
members.add(r);
}
-
- for(IResource r : members){
-
- if (r instanceof IFile) {
- String resourcebundleId = RBFileUtils.getCorrespondingResourceBundleId((IFile)r);
- if( resourcebundleId != null && (!children.containsKey(resourcebundleId))) {
- VirtualResourceBundle vrb;
-
- String vRBId;
-
- if (!p.isFragment()) vRBId = r.getProject()+"."+resourcebundleId;
- else vRBId = p.getHostProject() + "." + resourcebundleId;
-
- VirtualResourceBundle vResourceBundle = vcManager.getVResourceBundles(vRBId);
- if (vResourceBundle == null){
- String resourcebundleName = ResourceBundleManager.getResourceBundleName(r);
- vrb = new VirtualResourceBundle(resourcebundleName, resourcebundleId, ResourceBundleManager.getManager(r.getProject()));
- vcManager.addVResourceBundle(vRBId, vrb);
-
- } else vrb = vcManager.getVResourceBundles(vRBId);
-
- children.put(resourcebundleId, vrb);
+
+ for (IResource r : members) {
+
+ if (r instanceof IFile) {
+ String resourcebundleId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) r);
+ if (resourcebundleId != null
+ && (!children.containsKey(resourcebundleId))) {
+ VirtualResourceBundle vrb;
+
+ String vRBId;
+
+ if (!p.isFragment())
+ vRBId = r.getProject() + "." + resourcebundleId;
+ else
+ vRBId = p.getHostProject() + "." + resourcebundleId;
+
+ VirtualResourceBundle vResourceBundle = vcManager
+ .getVResourceBundles(vRBId);
+ if (vResourceBundle == null) {
+ String resourcebundleName = ResourceBundleManager
+ .getResourceBundleName(r);
+ vrb = new VirtualResourceBundle(
+ resourcebundleName,
+ resourcebundleId,
+ ResourceBundleManager.getManager(r.getProject()));
+ vcManager.addVResourceBundle(vRBId, vrb);
+
+ } else
+ vrb = vcManager.getVResourceBundles(vRBId);
+
+ children.put(resourcebundleId, vrb);
+ }
+ }
+ if (r instanceof IContainer)
+ if (!r.isDerived()) { // Don't show the 'bin' folder
+ VirtualContainer vContainer = vcManager
+ .getContainer((IContainer) r);
+
+ if (vContainer == null) {
+ int count = RBFileUtils
+ .countRecursiveResourceBundle((IContainer) r);
+ vContainer = new VirtualContainer(container, count);
+ vcManager.addVContainer((IContainer) r, vContainer);
}
- }
- if (r instanceof IContainer)
- if (!r.isDerived()){ //Don't show the 'bin' folder
- VirtualContainer vContainer = vcManager.getContainer((IContainer) r);
-
- if (vContainer == null){
- int count = RBFileUtils.countRecursiveResourceBundle((IContainer)r);
- vContainer = new VirtualContainer(container, count);
- vcManager.addVContainer((IContainer) r, vContainer);
- }
-
- if (vContainer.getRbCount() != 0) //Don't show folder without resourcebundles
- children.put(""+children.size(), r);
+
+ if (vContainer.getRbCount() != 0) // Don't show folder
+ // without resourcebundles
+ children.put("" + children.size(), r);
}
}
return children.values().toArray();
@@ -211,12 +240,15 @@ public Object getParent(Object element) {
return ((IContainer) element).getParent();
}
if (element instanceof IFile) {
- String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile) element);
+ 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();
+ Iterator<IResource> i = new HashSet<IResource>(
+ ((VirtualResourceBundle) element).getFiles()).iterator();
+ if (i.hasNext())
+ return i.next().getParent();
}
return null;
}
@@ -225,22 +257,29 @@ public Object getParent(Object element) {
public boolean hasChildren(Object element) {
if (element instanceof IWorkspaceRoot) {
try {
- if (((IWorkspaceRoot) element).members().length > 0) return true;
- } catch (CoreException e) {}
+ 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 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)
+ 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) {}
+ else if (((IContainer) element).members().length > 0)
+ return true;
+ } catch (CoreException e) {
+ }
}
- if (element instanceof VirtualResourceBundle){
+ if (element instanceof VirtualResourceBundle) {
return true;
}
return false;
@@ -260,136 +299,144 @@ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
- //TODO remove ResourceChangelistner and add ResourceBundleChangelistner
+ // TODO remove ResourceChangelistner and add ResourceBundleChangelistner
public void resourceChanged(final IResourceChangeEvent event) {
-
+
final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
final IResource res = delta.getResource();
-
+
if (!RBFileUtils.isResourceBundleFile(res))
return true;
-
+
switch (delta.getKind()) {
- case IResourceDelta.REMOVED:
- recountParenthierarchy(res.getParent());
- break;
- //TODO remove unused VirtualResourceBundles and VirtualContainer from vcManager
- case IResourceDelta.ADDED:
- checkListner(res);
- break;
- case IResourceDelta.CHANGED:
- if (delta.getFlags() != IResourceDelta.MARKERS)
- return true;
- break;
+ case IResourceDelta.REMOVED:
+ recountParenthierarchy(res.getParent());
+ break;
+ // TODO remove unused VirtualResourceBundles and
+ // VirtualContainer from vcManager
+ case IResourceDelta.ADDED:
+ checkListner(res);
+ break;
+ case IResourceDelta.CHANGED:
+ if (delta.getFlags() != IResourceDelta.MARKERS)
+ return true;
+ break;
}
-
+
refresh(res);
-
+
return true;
}
};
-
+
try {
event.getDelta().accept(visitor);
} catch (Exception e) {
e.printStackTrace();
}
}
-
+
@Override
public void resourceBundleChanged(ResourceBundleChangedEvent event) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(event.getProject());
-
- switch (event.getType()){
- case ResourceBundleChangedEvent.ADDED:
- case ResourceBundleChangedEvent.DELETED:
- IResource res = rbmanager.getRandomFile(event.getBundle());
- IContainer hostContainer;
-
- if (res == null)
- try{
- hostContainer = event.getProject().getFile(event.getBundle()).getParent();
- }catch (Exception e) {
- refresh(null);
- return;
- }
- else {
- VirtualProject vProject = (VirtualProject) vcManager.getContainer((IContainer) res.getProject());
- if (vProject != null && vProject.isFragment()){
- IProject hostProject = vProject.getHostProject();
- hostContainer = ResourceUtils.getCorrespondingFolders(res.getParent(), hostProject);
- } else
- hostContainer = res.getParent();
+ 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;
}
-
- recountParenthierarchy(hostContainer);
- refresh(null);
- break;
+ else {
+ VirtualProject vProject = (VirtualProject) vcManager
+ .getContainer((IContainer) res.getProject());
+ if (vProject != null && vProject.isFragment()) {
+ IProject hostProject = vProject.getHostProject();
+ hostContainer = ResourceUtils.getCorrespondingFolders(
+ res.getParent(), hostProject);
+ } else
+ hostContainer = res.getParent();
+ }
+
+ recountParenthierarchy(hostContainer);
+ refresh(null);
+ break;
}
-
+
}
-
+
@Override
public void propertyChange(PropertyChangeEvent event) {
- if(event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)){
+ if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) {
vcManager.reset();
-
+
refresh(root);
}
}
-
- //TODO problems with remove a hole ResourceBundle
+
+ // TODO problems with remove a hole ResourceBundle
private void recountParenthierarchy(IContainer parent) {
if (parent.isDerived())
- return; //Don't recount the 'bin' folder
-
- VirtualContainer vContainer = vcManager.getContainer((IContainer) parent);
- if (vContainer != null){
+ return; // Don't recount the 'bin' folder
+
+ VirtualContainer vContainer = vcManager
+ .getContainer((IContainer) parent);
+ if (vContainer != null) {
vContainer.recount();
}
-
+
if ((parent instanceof IFolder))
recountParenthierarchy(parent.getParent());
}
-
+
private void refresh(final IResource res) {
if (refresh == null || refresh.getResult() != null)
refresh = new UIJob("refresh viewer") {
@Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (viewer != null
- && !viewer.getControl().isDisposed())
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (viewer != null && !viewer.getControl().isDisposed())
if (res != null)
- viewer.refresh(res.getProject(),true); // refresh(res);
- else viewer.refresh();
+ viewer.refresh(res.getProject(), true); // refresh(res);
+ else
+ viewer.refresh();
return Status.OK_STATUS;
}
};
- refresh.schedule();
+ refresh.schedule();
}
-
+
private void registerResourceBundleListner(IProject p) {
listenedProjects.add(p);
-
- ResourceBundleManager rbmanager =ResourceBundleManager.getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
+
+ 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()){
+ 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());
+ 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 ccf3e999..6e833ca7 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
@@ -36,140 +36,156 @@
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.navigator.IDescriptionProvider;
-
-
-public class ResourceBundleLabelProvider extends LabelProvider implements ILabelProvider, IDescriptionProvider{
+public class ResourceBundleLabelProvider extends LabelProvider implements
+ ILabelProvider, IDescriptionProvider {
VirtualContentManager vcManager;
-
- public ResourceBundleLabelProvider(){
+
+ 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);
+ 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);
+ 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 IContainer) && (returnImage == null)) {
+ returnImage = PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_FOLDER);
}
if (element instanceof VirtualResourceBundle)
- returnImage = ImageUtils.getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
- if (element instanceof IFile){
- if (RBFileUtils.isResourceBundleFile((IFile)element)){
- Locale l = RBFileUtils.getLocale((IFile)element);
+ returnImage = ImageUtils
+ .getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
+ if (element instanceof IFile) {
+ if (RBFileUtils.isResourceBundleFile((IFile) element)) {
+ Locale l = RBFileUtils.getLocale((IFile) element);
returnImage = ImageUtils.getLocalIcon(l);
-
- VirtualProject p = ((VirtualProject)vcManager.getContainer(((IFile) element).getProject()));
- if (p!=null && p.isFragment())
+
+ 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
+ // Add a Warning Image
returnImage = ImageUtils.getImageWithWarning(returnImage);
}
return returnImage;
}
-
+
@Override
public String getText(Object element) {
-
+
StringBuilder text = new StringBuilder();
if (element instanceof IContainer) {
IContainer container = (IContainer) element;
text.append(container.getName());
-
- if (element instanceof IProject){
- VirtualContainer vproject = vcManager.getContainer((IProject) element);
-// if (vproject != null && vproject instanceof VirtualFragment) text.append("�");
+
+ 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()+"]");
-
+ text.append(" [" + vContainer.getRbCount() + "]");
+
}
- if (element instanceof VirtualResourceBundle){
- text.append(((VirtualResourceBundle)element).getName());
+ if (element instanceof VirtualResourceBundle) {
+ text.append(((VirtualResourceBundle) element).getName());
}
- if (element instanceof IFile){
- if (RBFileUtils.isResourceBundleFile((IFile)element)){
- Locale locale = RBFileUtils.getLocale((IFile)element);
+ if (element instanceof IFile) {
+ if (RBFileUtils.isResourceBundleFile((IFile) element)) {
+ Locale locale = RBFileUtils.getLocale((IFile) element);
text.append(" ");
if (locale != null) {
text.append(locale);
- }
- else {
+ } else {
text.append("default");
}
-
- VirtualProject vproject = (VirtualProject) vcManager.getContainer(((IFile) element).getProject());
- if (vproject!= null && vproject.isFragment()) text.append("�");
+
+ VirtualProject vproject = (VirtualProject) vcManager
+ .getContainer(((IFile) element).getProject());
+ if (vproject != null && vproject.isFragment())
+ text.append("�");
}
}
- if(element instanceof String){
+ if (element instanceof String) {
text.append(element);
}
return text.toString();
}
-
+
@Override
public String getDescription(Object anElement) {
if (anElement instanceof IResource)
- return ((IResource)anElement).getName();
+ return ((IResource) anElement).getName();
if (anElement instanceof VirtualResourceBundle)
- return ((VirtualResourceBundle)anElement).getName();
+ return ((VirtualResourceBundle) anElement).getName();
return null;
}
-
- private boolean checkMarkers(Object element){
- if (element instanceof IResource){
- IMarker[] ms = 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)
+ 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()));
-
+
+ if (element instanceof IContainer) {
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders(
+ (IContainer) element,
+ FragmentProjectUtils
+ .getFragments(((IContainer) element)
+ .getProject()));
+
IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
+ for (IContainer c : fragmentContainer) {
try {
if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = EditorUtils.concatMarkerArray(ms,
+ fragment_ms);
}
} catch (CoreException e) {
e.printStackTrace();
}
}
- if (ms.length>0)
+ if (ms.length > 0)
return true;
}
} catch (CoreException e) {
}
}
- if (element instanceof VirtualResourceBundle){
- ResourceBundleManager rbmanager = ((VirtualResourceBundle)element).getResourceBundleManager();
- String id = ((VirtualResourceBundle)element).getResourceBundleId();
- for (IResource r : rbmanager.getResourceBundles(id)){
- if (RBFileUtils.hasResourceBundleMarker(r)) return true;
+ if (element instanceof VirtualResourceBundle) {
+ ResourceBundleManager rbmanager = ((VirtualResourceBundle) element)
+ .getResourceBundleManager();
+ String id = ((VirtualResourceBundle) element).getResourceBundleId();
+ for (IResource r : rbmanager.getResourceBundles(id)) {
+ if (RBFileUtils.hasResourceBundleMarker(r))
+ return true;
}
}
-
+
return false;
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
index b082c2af..ca261701 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
@@ -20,31 +20,35 @@
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.navigator.CommonViewer;
-
-public class ExpandAction extends Action implements IAction{
+public class ExpandAction extends Action implements IAction {
private CommonViewer viewer;
-
+
public ExpandAction(CommonViewer viewer) {
- this.viewer= viewer;
+ this.viewer = viewer;
setText("Expand Node");
setToolTipText("expand node");
- setImageDescriptor(RBManagerActivator.getImageDescriptor(ImageUtils.EXPAND));
+ setImageDescriptor(RBManagerActivator
+ .getImageDescriptor(ImageUtils.EXPAND));
}
-
+
@Override
- public boolean isEnabled(){
- IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
- if (sSelection.size()>=1) return true;
- else return false;
+ 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();
+ public void run() {
+ IStructuredSelection sSelection = (IStructuredSelection) viewer
+ .getSelection();
Iterator<?> it = sSelection.iterator();
- while (it.hasNext()){
+ 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 5daa6386..32951bf8 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
@@ -24,31 +24,33 @@
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-
public class GeneralActionProvider extends CommonActionProvider {
private IAction expandAction;
-
+
public GeneralActionProvider() {
// TODO Auto-generated constructor stub
}
-
+
@Override
- public void init(ICommonActionExtensionSite aSite){
+ public void init(ICommonActionExtensionSite aSite) {
super.init(aSite);
- //init Expand-Action
- expandAction = new ExpandAction((CommonViewer) aSite.getStructuredViewer());
-
- //activate View-Hover
+ // 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());
+
+ Hover hover = new Hover(Display.getCurrent().getActiveShell(),
+ informants);
+ hover.activateHoverHelp(((CommonViewer) aSite.getStructuredViewer())
+ .getTree());
}
@Override
public void fillContextMenu(IMenuManager menu) {
- menu.appendToGroup("expand",expandAction);
+ 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 bef7aa1a..bae91e5f 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
@@ -18,30 +18,36 @@
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
-
-
public class OpenVRBAction extends Action {
private ISelectionProvider selectionProvider;
-
+
public OpenVRBAction(ISelectionProvider selectionProvider) {
this.selectionProvider = selectionProvider;
}
-
+
@Override
- public boolean isEnabled(){
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
- if (sSelection.size()==1) return true;
- else return false;
+ public boolean isEnabled() {
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
+ .getSelection();
+ if (sSelection.size() == 1)
+ return true;
+ else
+ return false;
}
-
+
@Override
- public void run(){
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
- if (sSelection.size()==1 && sSelection.getFirstElement() instanceof VirtualResourceBundle){
- VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection.getFirstElement();
- IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
-
- EditorUtils.openEditor(wp, vRB.getRandomFile(), EditorUtils.RESOURCE_BUNDLE_EDITOR);
+ public void run() {
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
+ .getSelection();
+ if (sSelection.size() == 1
+ && sSelection.getFirstElement() instanceof VirtualResourceBundle) {
+ VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection
+ .getFirstElement();
+ IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+
+ EditorUtils.openEditor(wp, vRB.getRandomFile(),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR);
}
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
index 306bfcde..94286918 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
@@ -21,19 +21,21 @@
*/
public class VirtualRBActionProvider extends CommonActionProvider {
private IAction openAction;
-
+
public VirtualRBActionProvider() {
// TODO Auto-generated constructor stub
}
@Override
- public void init(ICommonActionExtensionSite aSite){
+ public void init(ICommonActionExtensionSite aSite) {
super.init(aSite);
- openAction = new OpenVRBAction(aSite.getViewSite().getSelectionProvider());
+ openAction = new OpenVRBAction(aSite.getViewSite()
+ .getSelectionProvider());
}
-
+
@Override
- public void fillActionBars(IActionBars actionBars){
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, openAction);
+ 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 5db2465c..1a2279be 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
@@ -31,37 +31,37 @@ 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){
+
+ if (infoComposite == null) {
infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout =new GridLayout(1,false);
+ 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) {
+
+ if (data instanceof IProject) {
addLocale(infoComposite, data);
addFragments(infoComposite, data);
- }
-
+ }
+
if (show) {
infoData.heightHint = -1;
infoData.widthHint = -1;
@@ -69,11 +69,11 @@ public Composite getInfoComposite(Object data, Composite parent) {
infoData.heightHint = 0;
infoData.widthHint = 0;
}
-
+
infoComposite.layout();
infoComposite.pack();
sinkColor(infoComposite);
-
+
return infoComposite;
}
@@ -81,55 +81,54 @@ public Composite getInfoComposite(Object data, Composite parent) {
public boolean show() {
return show;
}
-
- private void setColor(Control control){
+
+ private void setColor(Control control) {
Display display = control.getParent().getDisplay();
-
- control.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+
+ control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
-
- private void sinkColor(Composite composite){
+
+ private void sinkColor(Composite composite) {
setColor(composite);
-
- for(Control c : composite.getChildren()){
- setColor(c);
- if (c instanceof Composite) sinkColor((Composite) c);
+
+ for (Control c : composite.getChildren()) {
+ setColor(c);
+ if (c instanceof Composite)
+ sinkColor((Composite) c);
}
}
- private void addLocale(Composite parent, Object data){
+ private void addLocale(Composite parent, Object data) {
if (localeGroup == null) {
- localeGroup = new Composite(parent, SWT.NONE);
+ localeGroup = new Composite(parent, SWT.NONE);
localeLabel = new Label(localeGroup, SWT.SINGLE);
-
+
showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
localeGroup.setLayoutData(showLocalesData);
}
-
+
locales = getProvidedLocales(data);
-
+
if (locales.length() != 0) {
localeLabel.setText(locales);
- localeLabel.pack();
+ localeLabel.pack();
show = true;
-// showLocalesData.heightHint = -1;
-// showLocalesData.widthHint=-1;
+ // showLocalesData.heightHint = -1;
+ // showLocalesData.widthHint=-1;
} else {
localeLabel.setText("No Language Provided");
localeLabel.pack();
show = true;
-// showLocalesData.heightHint = 0;
-// showLocalesData.widthHint = 0;
+ // showLocalesData.heightHint = 0;
+ // showLocalesData.widthHint = 0;
}
-
-// localeGroup.layout();
+
+ // localeGroup.layout();
localeGroup.pack();
}
-
- private void addFragments(Composite parent, Object data){
+
+ private void addFragments(Composite parent, Object data) {
if (fragmentsGroup == null) {
fragmentsGroup = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(1, false);
@@ -141,7 +140,7 @@ private void addFragments(Composite parent, Object data){
fragmentsGroup.setLayoutData(showFragmentsData);
Composite fragmentTitleGroup = new Composite(fragmentsGroup,
- SWT.NONE);
+ SWT.NONE);
layout = new GridLayout(2, false);
layout.verticalSpacing = 0;
layout.horizontalSpacing = 5;
@@ -149,7 +148,7 @@ private void addFragments(Composite parent, Object data){
Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
fragmentImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
+ .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
fragmentImageLabel.pack();
Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
@@ -157,27 +156,28 @@ private void addFragments(Composite parent, Object data){
fragementTitleLabel.pack();
fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
}
-
+
fragments = getFragmentProjects(data);
-
+
if (fragments.length() != 0) {
fragmentsLabel.setText(fragments);
show = true;
showFragmentsData.heightHint = -1;
- showFragmentsData.widthHint= -1;
+ showFragmentsData.widthHint = -1;
fragmentsLabel.pack();
} else {
showFragmentsData.heightHint = 0;
showFragmentsData.widthHint = 0;
}
-
+
fragmentsGroup.layout();
fragmentsGroup.pack();
}
-
+
private String getProvidedLocales(Object data) {
if (data instanceof IProject) {
- ResourceBundleManager rbmanger = ResourceBundleManager.getManager((IProject) data);
+ ResourceBundleManager rbmanger = ResourceBundleManager
+ .getManager((IProject) data);
Set<Locale> ls = rbmanger.getProjectProvidedLocales();
if (ls.size() > 0) {
@@ -203,25 +203,26 @@ private String getProvidedLocales(Object data) {
return sb.toString();
}
}
-
-
+
return "";
}
private String getFragmentProjects(Object data) {
- if (data instanceof IProject){
- List<IProject> fragments = FragmentProjectUtils.getFragments((IProject) 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){
+ for (IProject f : fragments) {
sb.append(f.getName());
- if (++i != fragments.size()) sb.append("\n");
+ if (++i != fragments.size())
+ sb.append("\n");
}
return sb.toString();
}
- }
+ }
return "";
}
}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
index ffe60967..bb5e04cf 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
@@ -33,110 +33,106 @@
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
-
public class RBMarkerInformant implements HoverInformant {
private int MAX_PROBLEMS = 20;
private boolean show = false;
-
+
private String title;
private String problems;
-
+
private Composite infoComposite;
private Composite titleGroup;
private Label titleLabel;
private Composite problemGroup;
private Label problemLabel;
-
+
private GridData infoData;
private GridData showTitleData;
private GridData showProblemsData;
-
-
+
@Override
public Composite getInfoComposite(Object data, Composite parent) {
show = false;
-
- if (infoComposite == null){
+
+ if (infoComposite == null) {
infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout =new GridLayout(1,false);
+ 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) {
+
+ if (data instanceof VirtualResourceBundle || data instanceof IResource) {
addTitle(infoComposite, data);
addProblems(infoComposite, data);
}
-
- if (show){
- infoData.heightHint=-1;
- infoData.widthHint=-1;
+
+ if (show) {
+ infoData.heightHint = -1;
+ infoData.widthHint = -1;
} else {
- infoData.heightHint=0;
- infoData.widthHint=0;
+ infoData.heightHint = 0;
+ infoData.widthHint = 0;
}
-
+
infoComposite.layout();
sinkColor(infoComposite);
infoComposite.pack();
-
+
return infoComposite;
}
@Override
- public boolean show(){
+ public boolean show() {
return show;
}
-
- private void setColor(Control control){
+
+ private void setColor(Control control) {
Display display = control.getParent().getDisplay();
-
- control.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+
+ control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
-
- private void sinkColor(Composite composite){
+
+ private void sinkColor(Composite composite) {
setColor(composite);
-
- for(Control c : composite.getChildren()){
- setColor(c);
- if (c instanceof Composite) sinkColor((Composite) c);
+
+ for (Control c : composite.getChildren()) {
+ setColor(c);
+ if (c instanceof Composite)
+ sinkColor((Composite) c);
}
}
-
- private void addTitle(Composite parent, Object data){
+
+ private void addTitle(Composite parent, Object data) {
if (titleGroup == null) {
titleGroup = new Composite(parent, SWT.NONE);
titleLabel = new Label(titleGroup, SWT.SINGLE);
-
+
showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
titleGroup.setLayoutData(showTitleData);
}
title = getTitel(data);
-
+
if (title.length() != 0) {
titleLabel.setText(title);
show = true;
- showTitleData.heightHint=-1;
- showTitleData.widthHint=-1;
+ showTitleData.heightHint = -1;
+ showTitleData.widthHint = -1;
titleLabel.pack();
} else {
- showTitleData.heightHint=0;
- showTitleData.widthHint=0;
+ showTitleData.heightHint = 0;
+ showTitleData.widthHint = 0;
}
-
+
titleGroup.layout();
titleGroup.pack();
}
-
-
- private void addProblems(Composite parent, Object data){
+
+ private void addProblems(Composite parent, Object data) {
if (problemGroup == null) {
problemGroup = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(1, false);
@@ -146,7 +142,7 @@ private void addProblems(Composite parent, Object data){
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;
@@ -155,7 +151,7 @@ private void addProblems(Composite parent, Object data){
Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
warningImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.WARNING_IMAGE));
+ .getBaseImage(ImageUtils.WARNING_IMAGE));
warningImageLabel.pack();
Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
@@ -164,60 +160,63 @@ private void addProblems(Composite parent, Object data){
problemLabel = new Label(problemGroup, SWT.SINGLE);
}
-
+
problems = getProblems(data);
-
+
if (problems.length() != 0) {
problemLabel.setText(problems);
show = true;
- showProblemsData.heightHint=-1;
- showProblemsData.widthHint=-1;
+ showProblemsData.heightHint = -1;
+ showProblemsData.widthHint = -1;
problemLabel.pack();
} else {
- showProblemsData.heightHint=0;
- showProblemsData.widthHint=0;
+ showProblemsData.heightHint = 0;
+ showProblemsData.widthHint = 0;
}
-
+
problemGroup.layout();
problemGroup.pack();
- }
-
-
+ }
+
private String getTitel(Object data) {
- if (data instanceof IFile){
- return ((IResource)data).getFullPath().toString();
+ if (data instanceof IFile) {
+ return ((IResource) data).getFullPath().toString();
}
- if (data instanceof VirtualResourceBundle){
- return ((VirtualResourceBundle)data).getResourceBundleId();
+ if (data instanceof VirtualResourceBundle) {
+ return ((VirtualResourceBundle) data).getResourceBundleId();
}
-
+
return "";
}
-
- private String getProblems(Object data){
+
+ private String getProblems(Object data) {
IMarker[] ms = null;
-
- if (data instanceof IResource){
+
+ 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];
+ 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()));
-
+ 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){
+ for (IContainer c : fragmentContainer) {
try {
if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
}
@@ -226,41 +225,42 @@ private String getProblems(Object data){
}
}
}
-
- if (data instanceof VirtualResourceBundle){
+
+ if (data instanceof VirtualResourceBundle) {
VirtualResourceBundle vRB = (VirtualResourceBundle) data;
-
+
ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
IMarker[] file_ms;
-
- Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB.getResourceBundleId());
+
+ Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB
+ .getResourceBundleId());
if (!rBundles.isEmpty())
- for (IResource r : rBundles){
+ for (IResource r : rBundles) {
try {
- file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
+ file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID,
+ false, IResource.DEPTH_INFINITE);
if (ms != null) {
ms = EditorUtils.concatMarkerArray(ms, file_ms);
- }else{
+ } else {
ms = file_ms;
}
} catch (Exception e) {
}
}
}
-
-
+
StringBuilder sb = new StringBuilder();
- int count=0;
-
- if (ms != null && ms.length!=0){
+ 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){
+ if (count == MAX_PROBLEMS && ms.length - count != 0) {
sb.append(" ... and ");
- sb.append(ms.length-count);
+ sb.append(ms.length - count);
sb.append(" other problems");
break;
}
@@ -270,7 +270,7 @@ private String getProblems(Object data){
}
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 b46e456d..fb67215c 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
@@ -25,50 +25,55 @@
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
-
-
public class ProblematicResourceBundleFilter extends ViewerFilter {
-
+
/**
* Shows only IContainer and VirtualResourcebundles with all his
* properties-files, which have RB_Marker.
*/
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof IFile){
+ if (element instanceof IFile) {
return true;
- }
+ }
if (element instanceof VirtualResourceBundle) {
- for (IResource f : ((VirtualResourceBundle)element).getFiles() ){
+ 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)
+ 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){
+ for (IContainer c : fragmentContainer) {
try {
if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
}
} catch (CoreException e) {
e.printStackTrace();
}
}
- if (ms.length>0)
+ if (ms.length > 0)
return true;
-
- } catch (CoreException e) { }
+
+ } catch (CoreException e) {
+ }
}
return false;
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
index 98b25018..f7599b69 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
@@ -10,20 +10,18 @@
******************************************************************************/
package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+public interface IAbstractKeyTreeModel {
+ IKeyTreeNode[] getChildren(IKeyTreeNode node);
-public interface IAbstractKeyTreeModel {
+ IKeyTreeNode getChild(String key);
+
+ IKeyTreeNode[] getRootNodes();
+
+ IKeyTreeNode getRootNode();
+
+ IKeyTreeNode getParent(IKeyTreeNode node);
+
+ void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
- IKeyTreeNode[] getChildren(IKeyTreeNode node);
-
- IKeyTreeNode getChild(String key);
-
- IKeyTreeNode[] getRootNodes();
-
- IKeyTreeNode getRootNode();
-
- IKeyTreeNode getParent(IKeyTreeNode node);
-
- void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
-
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
index 8d59daf5..595b80d3 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
@@ -12,12 +12,11 @@
import org.eclipse.jface.viewers.TreeViewer;
-
public interface IKeyTreeContributor {
- void contribute(final TreeViewer treeViewer);
-
- IKeyTreeNode getKeyTreeNode(String key);
-
- IKeyTreeNode[] getRootKeyItems();
+ void contribute(final TreeViewer treeViewer);
+
+ IKeyTreeNode getKeyTreeNode(String key);
+
+ IKeyTreeNode[] getRootKeyItems();
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
index 0f86d946..6d27815e 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
@@ -10,63 +10,68 @@
******************************************************************************/
package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+public interface IKeyTreeNode {
+ /**
+ * Returns the key of the corresponding Resource-Bundle entry.
+ *
+ * @return The key of the Resource-Bundle entry
+ */
+ String getMessageKey();
-public interface IKeyTreeNode {
+ /**
+ * Returns the set of Resource-Bundle entries of the next deeper hierarchy
+ * level that share the represented entry as their common parent.
+ *
+ * @return The direct child Resource-Bundle entries
+ */
+ IKeyTreeNode[] getChildren();
+
+ /**
+ * The represented Resource-Bundle entry's id without the prefix defined by
+ * the entry's parent.
+ *
+ * @return The Resource-Bundle entry's display name.
+ */
+ String getName();
- /**
- * Returns the key of the corresponding Resource-Bundle entry.
- * @return The key of the Resource-Bundle entry
- */
- String getMessageKey();
+ /**
+ * Returns the set of Resource-Bundle entries from all deeper hierarchy
+ * levels that share the represented entry as their common parent.
+ *
+ * @return All child Resource-Bundle entries
+ */
+ // Collection<? extends IKeyTreeItem> getNestedChildren();
- /**
- * Returns the set of Resource-Bundle entries of the next deeper
- * hierarchy level that share the represented entry as their common
- * parent.
- * @return The direct child Resource-Bundle entries
- */
- IKeyTreeNode[] getChildren();
+ /**
+ * Returns whether this Resource-Bundle entry is visible under the given
+ * filter expression.
+ *
+ * @param filter
+ * The filter expression
+ * @return True if the filter expression matches the represented
+ * Resource-Bundle entry
+ */
+ // boolean applyFilter(String filter);
- /**
- * The represented Resource-Bundle entry's id without the prefix defined
- * by the entry's parent.
- * @return The Resource-Bundle entry's display name.
- */
- String getName();
+ /**
+ * The Resource-Bundle entries parent.
+ *
+ * @return The parent Resource-Bundle entry
+ */
+ IKeyTreeNode getParent();
- /**
- * Returns the set of Resource-Bundle entries from all deeper hierarchy
- * levels that share the represented entry as their common parent.
- * @return All child Resource-Bundle entries
- */
-// Collection<? extends IKeyTreeItem> getNestedChildren();
+ /**
+ * The Resource-Bundles key representation.
+ *
+ * @return The Resource-Bundle reference, if known
+ */
+ IMessagesBundleGroup getMessagesBundleGroup();
- /**
- * Returns whether this Resource-Bundle entry is visible under the
- * given filter expression.
- * @param filter The filter expression
- * @return True if the filter expression matches the represented Resource-Bundle entry
- */
-// boolean applyFilter(String filter);
+ boolean isUsedAsKey();
- /**
- * The Resource-Bundle entries parent.
- * @return The parent Resource-Bundle entry
- */
- IKeyTreeNode getParent();
+ void setParent(IKeyTreeNode parentNode);
- /**
- * The Resource-Bundles key representation.
- * @return The Resource-Bundle reference, if known
- */
- IMessagesBundleGroup getMessagesBundleGroup();
+ void addChild(IKeyTreeNode childNode);
-
- boolean isUsedAsKey();
-
- void setParent(IKeyTreeNode parentNode);
-
- void addChild(IKeyTreeNode childNode);
-
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
index 7e136194..42b7fdf1 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
@@ -10,16 +10,18 @@
******************************************************************************/
package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
/**
* Objects implementing this interface can act as a visitor to a
* <code>IKeyTreeModel</code>.
+ *
* @author Pascal Essiembre ([email protected])
*/
public interface IKeyTreeVisitor {
- /**
- * Visits a key tree node.
- * @param item key tree node to visit
- */
+ /**
+ * Visits a key tree node.
+ *
+ * @param item
+ * key tree node to visit
+ */
void visitKeyTreeNode(IKeyTreeNode node);
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java
index 9c62be4b..a71e24f5 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java
@@ -12,30 +12,28 @@
import java.util.Locale;
+public interface IMessage {
+ String getKey();
-public interface IMessage {
+ String getValue();
+
+ Locale getLocale();
+
+ String getComment();
+
+ boolean isActive();
+
+ String toString();
+
+ void setActive(boolean active);
+
+ void setComment(String comment);
+
+ void setComment(String comment, boolean silent);
+
+ void setText(String test);
+
+ void setText(String test, boolean silent);
- String getKey();
-
- String getValue();
-
- Locale getLocale();
-
- String getComment();
-
- boolean isActive();
-
- String toString();
-
- void setActive(boolean active);
-
- void setComment(String comment);
-
- void setComment(String comment, boolean silent);
-
- void setText(String test);
-
- void setText(String test, boolean silent);
-
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
index 34853fb4..b2da952c 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
@@ -13,38 +13,35 @@
import java.util.Collection;
import java.util.Locale;
+public interface IMessagesBundle {
+ void dispose();
+ void renameMessageKey(String sourceKey, String targetKey);
-public interface IMessagesBundle {
+ void removeMessage(String messageKey);
+
+ void duplicateMessage(String sourceKey, String targetKey);
+
+ Locale getLocale();
+
+ String[] getKeys();
+
+ String getValue(String key);
+
+ Collection<IMessage> getMessages();
+
+ IMessage getMessage(String key);
+
+ void addMessage(IMessage message);
+
+ void removeMessages(String[] messageKeys);
+
+ void setComment(String comment);
+
+ String getComment();
- void dispose();
-
- void renameMessageKey(String sourceKey, String targetKey);
-
- void removeMessage(String messageKey);
-
- void duplicateMessage(String sourceKey, String targetKey);
-
- Locale getLocale();
-
- String[] getKeys();
-
- String getValue(String key);
-
- Collection<IMessage> getMessages();
-
- IMessage getMessage(String key);
-
- void addMessage(IMessage message);
-
- void removeMessages(String[] messageKeys);
-
- void setComment(String comment);
-
- String getComment();
-
- IMessagesResource getResource();
+ IMessagesResource getResource();
void removeMessageAddParentKey(String key);
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
index 0dbdc00a..8f27130f 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
@@ -13,44 +13,43 @@
import java.util.Collection;
import java.util.Locale;
-
public interface IMessagesBundleGroup {
- Collection<IMessagesBundle> getMessagesBundles();
-
- boolean containsKey(String key);
-
- IMessage[] getMessages(String key);
-
- IMessage getMessage(String key, Locale locale);
-
- IMessagesBundle getMessagesBundle(Locale locale);
-
- void removeMessages(String messageKey);
-
- boolean isKey(String key);
-
- void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
-
- String[] getMessageKeys();
-
- void addMessages(String key);
-
- int getMessagesBundleCount();
-
- String getName();
-
- String getResourceBundleId();
-
- boolean hasPropertiesFileGroupStrategy();
-
- public boolean isMessageKey(String key);
-
- public String getProjectName();
-
- public void removeMessagesBundle(IMessagesBundle messagesBundle);
-
- public void dispose();
+ Collection<IMessagesBundle> getMessagesBundles();
+
+ boolean containsKey(String key);
+
+ IMessage[] getMessages(String key);
+
+ IMessage getMessage(String key, Locale locale);
+
+ IMessagesBundle getMessagesBundle(Locale locale);
+
+ void removeMessages(String messageKey);
+
+ boolean isKey(String key);
+
+ void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
+
+ String[] getMessageKeys();
+
+ void addMessages(String key);
+
+ int getMessagesBundleCount();
+
+ String getName();
+
+ String getResourceBundleId();
+
+ boolean hasPropertiesFileGroupStrategy();
+
+ public boolean isMessageKey(String key);
+
+ public String getProjectName();
+
+ public void removeMessagesBundle(IMessagesBundle messagesBundle);
+
+ public void dispose();
void removeMessagesAddParentKey(String key);
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java
index 87729d1f..bd16ace1 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
@@ -12,5 +12,6 @@
public interface IMessagesEditor {
String getSelectedKey();
+
void setSelectedKey(String key);
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
index db071eb3..11050768 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
@@ -14,52 +14,69 @@
/**
* Class abstracting the underlying native storage mechanism for persisting
- * internationalised text messages.
+ * internationalised text messages.
+ *
* @author Pascal Essiembre
*/
public interface IMessagesResource {
/**
* Gets the resource locale.
+ *
* @return locale
*/
- Locale getLocale();
- /**
- * Gets the underlying object abstracted by this resource (e.g. a File).
- * @return source object
- */
- Object getSource();
- /**
- * Serializes a {@link MessagesBundle} instance to its native format.
- * @param messagesBundle the MessagesBundle to serialize
- */
- void serialize(IMessagesBundle messagesBundle);
- /**
- * Deserializes a {@link MessagesBundle} instance from its native format.
- * @param messagesBundle the MessagesBundle to deserialize
- */
- void deserialize(IMessagesBundle messagesBundle);
- /**
- * Adds a messages resource listener. Implementors are required to notify
- * listeners of changes within the native implementation.
- * @param listener the listener
- */
- void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * Removes a messages resource listener.
- * @param listener the listener
- */
- void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * @return The resource location label. or null if unknown.
- */
- String getResourceLocationLabel();
-
- /**
- * Called when the group it belongs to is disposed.
- */
- void dispose();
-
+ Locale getLocale();
+
+ /**
+ * Gets the underlying object abstracted by this resource (e.g. a File).
+ *
+ * @return source object
+ */
+ Object getSource();
+
+ /**
+ * Serializes a {@link MessagesBundle} instance to its native format.
+ *
+ * @param messagesBundle
+ * the MessagesBundle to serialize
+ */
+ void serialize(IMessagesBundle messagesBundle);
+
+ /**
+ * Deserializes a {@link MessagesBundle} instance from its native format.
+ *
+ * @param messagesBundle
+ * the MessagesBundle to deserialize
+ */
+ void deserialize(IMessagesBundle messagesBundle);
+
+ /**
+ * Adds a messages resource listener. Implementors are required to notify
+ * listeners of changes within the native implementation.
+ *
+ * @param listener
+ * the listener
+ */
+ void addMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
+
+ /**
+ * Removes a messages resource listener.
+ *
+ * @param listener
+ * the listener
+ */
+ void removeMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
+
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ String getResourceLocationLabel();
+
+ /**
+ * Called when the group it belongs to is disposed.
+ */
+ void dispose();
+
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
index 07600e20..cc1025bd 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
@@ -12,13 +12,16 @@
/**
* Listener being notified when a {@link IMessagesResource} content changes.
+ *
* @author Pascal Essiembre
*/
public interface IMessagesResourceChangeListener {
/**
* Method called when the messages resource has changed.
- * @param resource the resource that changed
+ *
+ * @param resource
+ * the resource that changed
*/
- void resourceChanged(IMessagesResource resource);
+ void resourceChanged(IMessagesResource resource);
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
index d5c84662..1bc03c23 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
@@ -14,23 +14,22 @@
import java.util.Locale;
import java.util.Map;
+public interface IValuedKeyTreeNode extends IKeyTreeNode {
-public interface IValuedKeyTreeNode extends IKeyTreeNode{
-
- public void initValues (Map<Locale, String> values);
+ public void initValues(Map<Locale, String> values);
- public void addValue (Locale locale, String value);
-
- public void setValue (Locale locale, String newValue);
-
- public String getValue (Locale locale);
-
- public Collection<String> getValues ();
+ public void addValue(Locale locale, String value);
- public void setInfo(Object info);
+ public void setValue(Locale locale, String newValue);
- public Object getInfo();
-
- public Collection<Locale> getLocales ();
+ public String getValue(Locale locale);
+
+ public Collection<String> getValues();
+
+ public void setInfo(Object info);
+
+ public Object getInfo();
+
+ public Collection<Locale> getLocales();
}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java
index 4c0bb023..718c5253 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java
@@ -13,12 +13,10 @@
*/
package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
/**
* @author ala
- *
+ *
*/
public enum TreeType {
- Tree,
- Flat
+ Tree, Flat
}
diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html b/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html
index ed4b1966..b776137d 100644
--- a/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html
+++ b/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html
@@ -1,6 +1,6 @@
<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">
+ 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">
@@ -8,7 +8,7 @@
<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">
+ 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>
@@ -24,304 +24,429 @@
<o:CharactersWithSpaces>11384</o:CharactersWithSpaces>
<o:Version>9.4402</o:Version>
</o:DocumentProperties>
-</xml><![endif]--><!--[if gte mso 9]><xml>
+</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;}
+<!-- /* 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 ("AGREEMENT"). 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'>"Contribution" 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'>"Contributor" means any person or
-entity that distributes the Program.</span> </p>
-
-<p><span style='font-size:10.0pt'>"Licensed Patents " 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'>"Program" means the Contributions
-distributed in accordance with this Agreement.</span> </p>
-
-<p><span style='font-size:10.0pt'>"Recipient" 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 ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") 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 "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING,
-WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
-MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. 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]> <![endif]><o:p></o:p></p>
-
-</div>
+<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
+ ("AGREEMENT"). 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'>"Contribution"
+ 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'>"Contributor" means
+ any person or entity that distributes the Program.</span>
+ </p>
+
+ <p>
+ <span style='font-size: 10.0pt'>"Licensed Patents "
+ 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'>"Program" means the
+ Contributions distributed in accordance with this Agreement.</span>
+ </p>
+
+ <p>
+ <span style='font-size: 10.0pt'>"Recipient" 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 ("Commercial Contributor") hereby agrees to
+ defend and indemnify every other Contributor ("Indemnified
+ Contributor") against any losses, damages and costs
+ (collectively "Losses") 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 "AS IS"
+ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
+ OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
+ CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
+ FOR A PARTICULAR PURPOSE. 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]>
+
+ <![endif]><o:p></o:p></p>
+
+ </div>
</body>
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
index 700a2c05..1e535abd 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
@@ -32,15 +32,15 @@
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);
+
+ public void audit(IResource resource) {
+ parse(resource);
}
-
- private void parse (IResource resource) {
+
+ private void parse(IResource resource) {
}
@@ -68,53 +68,67 @@ public String getContextId() {
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);
-
+ 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));
+ 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)));
+ resolutions.add(new CreateResourceBundle(bname, marker
+ .getResource(), dataStart, dataEnd));
+
+ resolutions.add(new ReplaceResourceBundleDefReference(bname,
+ dataStart, dataEnd));
+ }
+
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
+ String bname = marker.getAttribute("key", "");
+
+ Set<IResource> bundleResources = ResourceBundleManager.getManager(
+ marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions.add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(marker.getAttribute(
+ "key", ""), marker.getResource(), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ resolutions.add(new ReplaceResourceBundleDefReference(marker
+ .getAttribute("key", ""), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
}
-
+
return resolutions;
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
index e63caa94..26c3bbed 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
@@ -28,115 +28,124 @@
public class JSFResourceBundleDetector {
- public static List<IRegion> getNonELValueRegions (String elExpression) {
+ public static List<IRegion> getNonELValueRegions(String elExpression) {
List<IRegion> stringRegions = new ArrayList<IRegion>();
int pos = -1;
-
+
do {
int start = pos + 1;
int end = elExpression.indexOf("#{", start);
end = end >= 0 ? end : elExpression.length();
-
+
if (elExpression.substring(start, end).trim().length() > 0) {
- IRegion region = new Region (start, end-start);
+ IRegion region = new Region(start, end - start);
stringRegions.add(region);
}
-
+
if (elExpression.substring(end).startsWith("#{"))
pos = elExpression.indexOf("}", end);
- else
+ else
pos = end;
} while (pos >= 0 && pos < elExpression.length());
-
+
return stringRegions;
}
-
- public static String getBundleVariableName (String elExpression) {
+
+ public static String getBundleVariableName(String elExpression) {
String bundleVarName = null;
- String[] delimitors = new String [] { ".", "[" };
-
+ String[] delimitors = new String[] { ".", "[" };
+
int startPos = elExpression.indexOf(delimitors[0]);
-
+
for (String del : delimitors) {
- if ((startPos > elExpression.indexOf(del) && elExpression.indexOf(del) >= 0) ||
- (startPos == -1 && elExpression.indexOf(del) >= 0))
+ 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) {
+
+ public static String getResourceKey(String elExpression) {
String key = null;
-
- if (elExpression.indexOf("[") == -1 || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression.indexOf(".") >= 0)) {
+
+ 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 (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);
+ key = elExpression.substring(startPos + 1, endPos);
}
}
}
-
+
return key;
}
-
- public static String resolveResourceBundleRefIdentifier (IDocument document, int startPos) {
+
+ public static String resolveResourceBundleRefIdentifier(IDocument document,
+ int startPos) {
String result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, startPos);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
+ .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))
+ if (isBundleElement(owner, context))
result = attr.getValue();
}
- } else if (curNode instanceof Element) {
+ } else if (curNode instanceof Element) {
final Element elem = (Element) curNode;
- if (isBundleElement (elem, context))
+ if (isBundleElement(elem, context))
result = elem.getAttribute("basename");
}
}
-
+
return result;
}
-
+
public static String resolveResourceBundleId(IDocument document,
- String varName) {
+ String varName) {
String content = document.get();
String bundleId = "";
int offset = 0;
- while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
- || content.indexOf("'" + varName + "'", offset+1) >= 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 + "'");
+ .indexOf("\"" + varName + "\"") : content.indexOf("'"
+ + varName + "'");
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
+ .getContext(document, offset);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
+ .getDOMContextResolver(context);
if (domResolver != null) {
final Node curNode = domResolver.getNode();
-
+
// node must be an XML attribute
Attr attr = null;
if (curNode instanceof Attr) {
@@ -144,119 +153,136 @@ public static String resolveResourceBundleId(IDocument document,
if (!attr.getNodeName().toLowerCase().equals("var"))
continue;
}
-
+
// Retrieve parent node
Element parentElement = (Element) attr.getOwnerElement();
-
+
if (!isBundleElement(parentElement, context))
continue;
-
+
bundleId = parentElement.getAttribute("basename");
break;
}
}
-
+
return bundleId;
}
-
- public static boolean isBundleElement (Element element, IStructuredDocumentContext context) {
- String bName = element.getTagName().substring(element.getTagName().indexOf(":")+1);
-
+
+ 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")) {
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+ if (tlResolver.getTagURIForNodeName(element).trim()
+ .equalsIgnoreCase("http://java.sun.com/jsf/core")) {
return true;
}
}
-
+
return false;
}
-
- public static boolean isJSFElement (Element element, IStructuredDocumentContext context) {
+
+ 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")) {
+ 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) {}
+ } 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 IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, startPos);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
+ .getDOMContextResolver(context);
+
if (domResolver != null) {
final Node curNode = domResolver.getNode();
-
+
// node must be an XML attribute
- if (curNode instanceof Element) {
+ if (curNode instanceof Element) {
final Element elem = (Element) curNode;
- if (isBundleElement (elem, context)) {
+ 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());
+ int attrStart = document.get().indexOf("basename",
+ startPos);
+ result = new Region(document.get().indexOf(
+ na.getValue(), attrStart), na.getValue()
+ .length());
}
}
}
}
-
+
return result;
}
- public static IRegion getElementAttrValueRegion(IDocument document, String attribute, int startPos) {
+ public static IRegion getElementAttrValueRegion(IDocument document,
+ String attribute, int startPos) {
IRegion result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, startPos);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
+ .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;
+ 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());
+ 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 varName) {
String content = document.get();
IRegion region = null;
int offset = 0;
- while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
- || content.indexOf("'" + varName + "'", offset+1) >= 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 + "'");
+ .indexOf("\"" + varName + "\"") : content.indexOf("'"
+ + varName + "'");
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
+ .getContext(document, offset);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
+ .getDOMContextResolver(context);
if (domResolver != null) {
final Node curNode = domResolver.getNode();
-
+
// node must be an XML attribute
Attr attr = null;
if (curNode instanceof Attr) {
@@ -264,53 +290,56 @@ public static IRegion resolveResourceBundleRefPos(IDocument document,
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));
+ int value = content.indexOf(bundleId,
+ content.indexOf("=", basename));
if (value > basename) {
- region = new Region (value, bundleId.length());
+ region = new Region(value, bundleId.length());
}
}
-
+
}
break;
}
}
-
+
return region;
}
public static String resolveResourceBundleVariable(IDocument document,
- String selectedResourceBundle) {
+ 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) {
+ while (content
+ .indexOf("\"" + selectedResourceBundle + "\"", offset + 1) >= 0
+ || content.indexOf("'" + selectedResourceBundle + "'",
+ offset + 1) >= 0) {
offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content
- .indexOf("\"" + selectedResourceBundle + "\"") : content.indexOf("'"
- + selectedResourceBundle + "'");
+ .indexOf("\"" + selectedResourceBundle + "\"") : content
+ .indexOf("'" + selectedResourceBundle + "'");
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
+ .getContext(document, offset);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
+ .getDOMContextResolver(context);
if (domResolver != null) {
final Node curNode = domResolver.getNode();
-
+
// node must be an XML attribute
Attr attr = null;
if (curNode instanceof Attr) {
@@ -318,88 +347,92 @@ public static String resolveResourceBundleVariable(IDocument document,
if (!attr.getNodeName().toLowerCase().equals("basename"))
continue;
}
-
+
// Retrieve parent node
Element parentElement = (Element) attr.getOwnerElement();
-
+
if (!isBundleElement(parentElement, context))
continue;
-
+
variableName = parentElement.getAttribute("var");
break;
}
}
-
+
return variableName;
}
-
- public static String resolveNewVariableName (IDocument document, String selectedResourceBundle) {
+
+ public static String resolveNewVariableName(IDocument document,
+ String selectedResourceBundle) {
String variableName = "";
int i = 0;
variableName = selectedResourceBundle.replace(".", "");
- while (resolveResourceBundleId(document, variableName).trim().length() > 0 ) {
+ while (resolveResourceBundleId(document, variableName).trim().length() > 0) {
variableName = selectedResourceBundle + (i++);
}
return variableName;
}
public static void createResourceBundleRef(IDocument document,
- String selectedResourceBundle,
- String variableName) {
+ 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);
+
+ while (content.indexOf("head", offset + 1) >= 0) {
+ offset = content.indexOf("head", offset + 1);
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
+ .getContext(document, offset);
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
+ .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);
-
+ headInsertPos = content.indexOf("head", offset + 5);
+
final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
+ .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("<");
+ .getDOMContextResolver(contextHeadClose);
+ if (domResolverHeadClose.getNode() instanceof Element
+ && domResolverHeadClose.getNode().getNodeName()
+ .equalsIgnoreCase("head")) {
+ headInsertPos = content.substring(0, headInsertPos)
+ .lastIndexOf("<");
break;
}
} while (headInsertPos >= 0);
-
+
if (headInsertPos < 0) {
headInsertPos = content.indexOf(">", offset) + 1;
}
-
+
break;
}
}
}
-
+
// resolve the taglib
try {
int taglibPos = content.lastIndexOf("taglib");
if (taglibPos > 0) {
final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, taglibPos);
+ .getContext(document, taglibPos);
taglibPos = content.indexOf("%>", taglibPos);
if (taglibPos > 0) {
- String decl = createLoadBundleDeclaration (document, taglibContext, variableName, selectedResourceBundle);
+ String decl = createLoadBundleDeclaration(document,
+ taglibContext, variableName, selectedResourceBundle);
if (headInsertPos > taglibPos)
document.replace(headInsertPos, 0, decl);
else
@@ -409,20 +442,25 @@ public static void createResourceBundleRef(IDocument document,
} catch (Exception e) {
e.printStackTrace();
}
-
+
}
private static String createLoadBundleDeclaration(IDocument document,
- IStructuredDocumentContext context, String variableName, String selectedResourceBundle) {
+ IStructuredDocumentContext context, String variableName,
+ String selectedResourceBundle) {
String bundleDecl = "";
-
+
// Retrieve jsf core namespace prefix
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- String bundlePrefix = tlResolver.getTagPrefixForURI("http://java.sun.com/jsf/core");
-
- MessageFormat tlFormatter = new MessageFormat ("<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n");
- bundleDecl = tlFormatter.format(new String[] {bundlePrefix, variableName, selectedResourceBundle});
-
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+ String bundlePrefix = tlResolver
+ .getTagPrefixForURI("http://java.sun.com/jsf/core");
+
+ MessageFormat tlFormatter = new MessageFormat(
+ "<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n");
+ bundleDecl = tlFormatter.format(new String[] { bundlePrefix,
+ variableName, selectedResourceBundle });
+
return bundleDecl;
}
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
index 2e07a824..28debd95 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
@@ -15,16 +15,15 @@
import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
import org.eclipse.core.resources.IFile;
-
public class SLLocation implements Serializable, ILocation {
-
+
private static final long serialVersionUID = 1L;
private IFile file = null;
private int startPos = -1;
private int endPos = -1;
private String literal;
private Serializable data;
-
+
public SLLocation(IFile file, int startPos, int endPos, String literal) {
super();
this.file = file;
@@ -32,32 +31,41 @@ public SLLocation(IFile file, int startPos, int endPos, String literal) {
this.endPos = endPos;
this.literal = literal;
}
+
public IFile getFile() {
return file;
}
+
public void setFile(IFile file) {
this.file = file;
}
+
public int getStartPos() {
return startPos;
}
+
public void setStartPos(int startPos) {
this.startPos = startPos;
}
+
public int getEndPos() {
return endPos;
}
+
public void setEndPos(int endPos) {
this.endPos = endPos;
}
+
public String getLiteral() {
return literal;
}
- public Serializable getData () {
+
+ public Serializable getData() {
return data;
}
- public void setData (Serializable 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 6e8fe8d8..50b1fd90 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
@@ -29,101 +29,101 @@
public class ExportToResourceBundleResolution implements IMarkerResolution2 {
- public ExportToResourceBundleResolution() {
- }
-
- @Override
- public String getDescription() {
- return "Export constant string literal to a resource bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Export to Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey("");
- config.setPreselectedMessage("");
- config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document
- .get(startPos, endPos) : "");
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- /** Check for an existing resource bundle reference **/
- String bundleVar = JSFResourceBundleDetector
- .resolveResourceBundleVariable(document,
- dialog.getSelectedResourceBundle());
-
- boolean requiresNewReference = false;
- if (bundleVar == null) {
- requiresNewReference = true;
- bundleVar = JSFResourceBundleDetector.resolveNewVariableName(
- document, dialog.getSelectedResourceBundle());
- }
-
- // insert resource reference
- String key = dialog.getSelectedKey();
-
- if (key.indexOf(".") >= 0) {
- int quoteDblIdx = document.get().substring(0, startPos)
- .lastIndexOf("\"");
- int quoteSingleIdx = document.get().substring(0, startPos)
- .lastIndexOf("'");
- String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
-
- document.replace(startPos, endPos, "#{" + bundleVar + "["
- + quoteSign + key + quoteSign + "]}");
- } else {
- document.replace(startPos, endPos, "#{" + bundleVar + "." + key
- + "}");
- }
-
- if (requiresNewReference) {
- JSFResourceBundleDetector.createResourceBundleRef(document,
- dialog.getSelectedResourceBundle(), bundleVar);
- }
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
+ public ExportToResourceBundleResolution() {
}
- }
+ @Override
+ public String getDescription() {
+ return "Export constant string literal to a resource bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Export to Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey("");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document
+ .get(startPos, endPos) : "");
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ /** Check for an existing resource bundle reference **/
+ String bundleVar = JSFResourceBundleDetector
+ .resolveResourceBundleVariable(document,
+ dialog.getSelectedResourceBundle());
+
+ boolean requiresNewReference = false;
+ if (bundleVar == null) {
+ requiresNewReference = true;
+ bundleVar = JSFResourceBundleDetector.resolveNewVariableName(
+ document, dialog.getSelectedResourceBundle());
+ }
+
+ // insert resource reference
+ String key = dialog.getSelectedKey();
+
+ if (key.indexOf(".") >= 0) {
+ int quoteDblIdx = document.get().substring(0, startPos)
+ .lastIndexOf("\"");
+ int quoteSingleIdx = document.get().substring(0, startPos)
+ .lastIndexOf("'");
+ String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
+
+ document.replace(startPos, endPos, "#{" + bundleVar + "["
+ + quoteSign + key + quoteSign + "]}");
+ } else {
+ document.replace(startPos, endPos, "#{" + bundleVar + "." + key
+ + "}");
+ }
+
+ if (requiresNewReference) {
+ JSFResourceBundleDetector.createResourceBundleRef(document,
+ dialog.getSelectedResourceBundle(), bundleVar);
+ }
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
index fd912c66..d98ba32f 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
@@ -15,7 +15,7 @@
import org.eclipse.ui.IMarkerResolutionGenerator;
public class JSFViolationResolutionGenerator implements
- IMarkerResolutionGenerator {
+ IMarkerResolutionGenerator {
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
index b1a86373..79fbf52b 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
@@ -24,13 +24,12 @@
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IMarkerResolution2;
-
public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
private String key;
private int start;
private int end;
-
+
public ReplaceResourceBundleDefReference(String key, int start, int end) {
this.key = key;
this.start = start;
@@ -39,9 +38,8 @@ public ReplaceResourceBundleDefReference(String key, int start, int end) {
@Override
public String getDescription() {
- return "Replaces the non-existing Resource-Bundle reference '"
- + key
- + "' with a reference to an already existing Resource-Bundle.";
+ return "Replaces the non-existing Resource-Bundle reference '" + key
+ + "' with a reference to an already existing Resource-Bundle.";
}
@Override
@@ -58,26 +56,29 @@ public String getLabel() {
@Override
public void run(IMarker marker) {
int startPos = start;
- int endPos = end-start;
+ int endPos = end - start;
IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
- resource.getProject());
-
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(
+ Display.getDefault().getActiveShell(),
+ resource.getProject());
+
if (dialog.open() != InputDialog.OK)
return;
-
+
key = dialog.getSelectedBundleId();
-
+
document.replace(startPos, endPos, key);
-
+
textFileBuffer.commit(null, false);
} catch (Exception e) {
e.printStackTrace();
@@ -86,7 +87,7 @@ public void run(IMarker marker) {
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 f890d1e5..edd8e11f 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
@@ -41,8 +41,8 @@ public ReplaceResourceBundleReference(String key, String bundleId) {
@Override
public String getDescription() {
return "Replaces the non-existing Resource-Bundle key '"
- + key
- + "' with a reference to an already existing localized string literal.";
+ + key
+ + "' with a reference to an already existing localized string literal.";
}
@Override
@@ -63,20 +63,20 @@ public void run(IMarker marker) {
IResource resource = marker.getResource();
ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
+ .getTextFileBufferManager();
IPath path = resource.getRawLocation();
try {
bufferManager.connect(path, null);
ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
+ .getTextFileBuffer(path);
IDocument document = textFileBuffer.getDocument();
ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell());
-
+ Display.getDefault().getActiveShell());
+
dialog.setProjectName(resource.getProject().getName());
dialog.setBundleName(bundleId);
-
+
if (dialog.open() != InputDialog.OK)
return;
@@ -84,18 +84,18 @@ public void run(IMarker marker) {
Locale locale = dialog.getSelectedLocale();
String jsfBundleVar = JSFResourceBundleDetector
- .getBundleVariableName(document.get().substring(startPos,
- startPos + endPos));
+ .getBundleVariableName(document.get().substring(startPos,
+ startPos + endPos));
if (key.indexOf(".") >= 0) {
int quoteDblIdx = document.get().substring(0, startPos)
- .lastIndexOf("\"");
+ .lastIndexOf("\"");
int quoteSingleIdx = document.get().substring(0, startPos)
- .lastIndexOf("'");
+ .lastIndexOf("'");
String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
document.replace(startPos, endPos, jsfBundleVar + "["
- + quoteSign + key + quoteSign + "]");
+ + quoteSign + key + quoteSign + "]");
} else {
document.replace(startPos, endPos, jsfBundleVar + "." + key);
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
index f539768d..87e47930 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
@@ -36,38 +36,43 @@ public class JSFELMessageHover implements ITextHover {
private IProject project = null;
public final String getHoverInfo(final ITextViewer textViewer,
- final IRegion hoverRegion) {
- String bundleName = JSFResourceBundleDetector.resolveResourceBundleId(textViewer.getDocument(),
- JSFResourceBundleDetector.getBundleVariableName(expressionValue));
- String resourceKey = JSFResourceBundleDetector.getResourceKey(expressionValue);
-
- return ELUtils.getResource (project, bundleName, resourceKey);
+ final IRegion hoverRegion) {
+ String bundleName = JSFResourceBundleDetector.resolveResourceBundleId(
+ textViewer.getDocument(), JSFResourceBundleDetector
+ .getBundleVariableName(expressionValue));
+ String resourceKey = JSFResourceBundleDetector
+ .getResourceKey(expressionValue);
+
+ return ELUtils.getResource(project, bundleName, resourceKey);
}
public final IRegion getHoverRegion(final ITextViewer textViewer,
- final int documentPosition) {
+ final int documentPosition) {
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(textViewer, documentPosition);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
+ .getContext(textViewer, documentPosition);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
project = workspaceResolver.getProject();
-
+
if (project != null) {
if (!InternationalizationNature.hasNature(project))
return null;
} else
return null;
- final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTextRegionResolver(context);
-
- if (!symbolResolver.getRegionType().equals(DOMJSPRegionContexts.JSP_VBL_CONTENT))
+ final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTextRegionResolver(context);
+
+ if (!symbolResolver.getRegionType().equals(
+ DOMJSPRegionContexts.JSP_VBL_CONTENT))
return null;
expressionValue = symbolResolver.getRegionText();
-
- return new Region (symbolResolver.getStartOffset(), symbolResolver.getLength());
-
+
+ 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 68bcbed5..6bc2299c 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
@@ -34,19 +34,18 @@
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
-
public class BundleNameProposal implements IContentAssistProcessor {
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
+ int offset) {
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(viewer, offset);
+ .getContext(viewer, offset);
IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
+ .getWorkspaceContextResolver(context);
IProject project = workspaceResolver.getProject();
IResource resource = workspaceResolver.getResource();
@@ -54,53 +53,56 @@ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
if (project != null) {
if (!InternationalizationNature.hasNature(project))
return proposals.toArray(new ICompletionProposal[proposals
- .size()]);
+ .size()]);
} else
return proposals.toArray(new ICompletionProposal[proposals.size()]);
- addBundleProposals(proposals, context, offset, viewer.getDocument(),
- resource);
-
+ 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) {
+ private void addBundleProposals(List<ICompletionProposal> proposals,
+ final IStructuredDocumentContext context, int startPos,
+ IDocument document, IResource resource) {
final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getTextRegionResolver(context);
+ .getTextRegionResolver(context);
if (resolver != null) {
final String regionType = resolver.getRegionType();
- startPos = resolver.getStartOffset()+1;
-
+ startPos = resolver.getStartOffset() + 1;
+
if (regionType != null
- && regionType
- .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
+ && regionType
+ .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getTaglibContextResolver(context);
+ .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)
+ 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));
+ 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));
}
}
}
@@ -112,7 +114,7 @@ private void addBundleProposals(List<ICompletionProposal> proposals,
private Attr getAttribute(IStructuredDocumentContext context) {
final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
+ .getDOMContextResolver(context);
if (domResolver != null) {
final Node curNode = domResolver.getNode();
@@ -124,10 +126,10 @@ private Attr getAttribute(IStructuredDocumentContext context) {
return null;
}
-
+
@Override
public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
+ int offset) {
// 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 3753f9e4..509c28c1 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
@@ -17,21 +17,21 @@
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
-
public class MessageCompletionProposal implements IJavaCompletionProposal {
private int offset = 0;
private int length = 0;
private String content = "";
private boolean messageAccessor = false;
-
- public MessageCompletionProposal (int offset, int length, String content, boolean messageAccessor) {
+
+ 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 {
@@ -44,7 +44,8 @@ public void apply(IDocument document) {
@Override
public String getAdditionalProposalInfo() {
// TODO Auto-generated method stub
- return "Inserts the property key '" + content + "' of the resource-bundle 'at.test.messages'";
+ return "Inserts the property key '" + content
+ + "' of the resource-bundle 'at.test.messages'";
}
@Override
@@ -69,7 +70,7 @@ public Image getImage() {
@Override
public Point getSelection(IDocument document) {
// TODO Auto-generated method stub
- return new Point (offset+content.length()+1, 0);
+ return new Point(offset + content.length() + 1, 0);
}
@Override
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 278f3669..33bb3193 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -24,7 +24,6 @@
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
-
public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
private int startPos;
@@ -36,8 +35,9 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
private String reference;
private boolean isKey;
- public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos,
- ResourceBundleManager manager, String bundleName, 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;
@@ -49,30 +49,30 @@ public NewResourceBundleEntryProposal(IResource resource, String str, int startP
@Override
public void apply(IDocument document) {
-
+
CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
+ Display.getDefault().getActiveShell());
+
DialogConfiguration config = dialog.new DialogConfiguration();
config.setPreselectedKey(isKey ? value : "");
config.setPreselectedMessage(!isKey ? value : "");
config.setPreselectedBundle(bundleName == null ? "" : bundleName);
config.setPreselectedLocale("");
config.setProjectName(resource.getProject().getName());
-
+
dialog.setDialogConfiguration(config);
-
+
if (dialog.open() != InputDialog.OK) {
return;
}
-
+
String resourceBundleId = dialog.getSelectedResourceBundle();
String key = dialog.getSelectedKey();
-
+
try {
document.replace(startPos, endPos, key);
reference = key + "\"";
- ResourceBundleManager.refreshResource(resource);
+ ResourceBundleManager.rebuildProject(resource);
} catch (Exception e) {
e.printStackTrace();
}
@@ -81,9 +81,9 @@ public void apply(IDocument document) {
@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!";
+ 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
@@ -95,9 +95,9 @@ public IContextInformation getContextInformation() {
@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 + "'";
@@ -110,14 +110,14 @@ public String getDisplayString() {
@Override
public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJ_ADD).createImage();
+ 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);
+ return new Point(startPos + reference.length() - 1, 0);
}
@Override
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 02ab4f34..3ea82d12 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
@@ -32,64 +32,68 @@
import ui.autocompletion.NewResourceBundleEntryProposal;
import auditor.JSFResourceBundleDetector;
-public class MessageCompletionProposal implements IContentAssistProcessor {
+public class MessageCompletionProposal implements IContentAssistProcessor {
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List <ICompletionProposal> proposals = new ArrayList<ICompletionProposal> ();
-
+ int offset) {
+ List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
+
final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(viewer, offset);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
+ .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()]);
+ 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 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)) {
+
+ 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));
+
+ proposals.add(new NewResourceBundleEntryProposal(resource, key,
+ startpos, length,
+ ResourceBundleManager.getManager(project), bundleId, true));
}
-
+
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
private String getProposalPrefix(IDocument document, int offset) {
String content = document.get().substring(0, offset);
int expIntro = content.lastIndexOf("#{");
-
- return content.substring(expIntro+2, offset);
+
+ return content.substring(expIntro + 2, offset);
}
- protected boolean isNonExistingKey (IProject project, String bundleId, String key) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
-
+ 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) {
+ int offset) {
// 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 695eb4bc..af134256 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
@@ -13,11 +13,12 @@
import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
import org.eclipse.core.resources.IProject;
-
public class ELUtils {
-
- public static String getResource (IProject project, String bundleName, String key) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
+
+ 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
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
index e6b5e9bb..1f7ad5cb 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
@@ -30,7 +30,8 @@
import auditor.JSFResourceBundleDetector;
import auditor.model.SLLocation;
-public class JSFInternationalizationValidator implements IValidator, ISourceValidator {
+public class JSFInternationalizationValidator implements IValidator,
+ ISourceValidator {
private IDocument document;
@@ -40,14 +41,14 @@ public void cleanup(IReporter reporter) {
@Override
public void validate(IValidationContext context, IReporter reporter)
- throws ValidationException {
+ throws ValidationException {
if (context.getURIs().length > 0) {
IFile file = ResourcesPlugin.getWorkspace().getRoot()
- .getFile(new Path(context.getURIs()[0]));
+ .getFile(new Path(context.getURIs()[0]));
// full document validation
EditorUtils.deleteAuditMarkersForResource(file.getProject()
- .findMember(file.getProjectRelativePath()));
+ .findMember(file.getProjectRelativePath()));
// validate all bundle definitions
int pos = document.get().indexOf("loadBundle", 0);
@@ -76,69 +77,62 @@ public void disconnect(IDocument arg0) {
}
public void validateRegion(IRegion dirtyRegion, IValidationContext context,
- IReporter reporter) {
+ 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]));
+ .getFile(new Path(context.getURIs()[0]));
ResourceBundleManager manager = ResourceBundleManager
- .getManager(file.getProject());
+ .getManager(file.getProject());
String bundleName = JSFResourceBundleDetector
- .resolveResourceBundleRefIdentifier(document, startPos);
+ .resolveResourceBundleRefIdentifier(document, startPos);
if (bundleName != null
- && !manager.getResourceBundleIdentifiers().contains(
- bundleName)) {
+ && !manager.getResourceBundleIdentifiers().contains(
+ bundleName)) {
IRegion reg = JSFResourceBundleDetector.getBasenameRegion(
- document, startPos);
+ document, startPos);
String ref = document.get().substring(reg.getOffset(),
- reg.getOffset() + reg.getLength());
-
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
- new String[] { ref }),
- new SLLocation(file, reg.getOffset(), reg
- .getOffset() + reg.getLength(), ref),
- IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
- ref, null, "jsf");
+ reg.getOffset() + reg.getLength());
+
+ EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
+ EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
+ new String[] { ref }),
+ new SLLocation(file, reg.getOffset(), reg.getOffset()
+ + reg.getLength(), ref),
+ IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE, ref, null,
+ "jsf");
return;
}
IRegion evr = JSFResourceBundleDetector.getElementAttrValueRegion(
- document, "value", startPos);
+ document, "value", startPos);
if (evr != null) {
String elementValue = document.get().substring(evr.getOffset(),
- evr.getOffset() + evr.getLength());
+ evr.getOffset() + evr.getLength());
// check all constant string expressions
List<IRegion> regions = JSFResourceBundleDetector
- .getNonELValueRegions(elementValue);
+ .getNonELValueRegions(elementValue);
for (IRegion region : regions) {
// report constant string literals
String constantLiteral = elementValue.substring(
- region.getOffset(),
- region.getOffset() + region.getLength());
-
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
- new String[] { constantLiteral }),
- new SLLocation(file, region.getOffset()
- + evr.getOffset(), evr.getOffset()
- + region.getOffset()
- + region.getLength(),
- constantLiteral),
- IMarkerConstants.CAUSE_CONSTANT_LITERAL,
- constantLiteral, null,
- "jsf");
+ region.getOffset(),
+ region.getOffset() + region.getLength());
+
+ EditorUtils.reportToMarker(
+ EditorUtils.getFormattedMessage(
+ EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
+ new String[] { constantLiteral }),
+ new SLLocation(file, region.getOffset()
+ + evr.getOffset(), evr.getOffset()
+ + region.getOffset() + region.getLength(),
+ constantLiteral),
+ IMarkerConstants.CAUSE_CONSTANT_LITERAL,
+ constantLiteral, null, "jsf");
}
// check el expressions
@@ -151,14 +145,14 @@ public void validateRegion(IRegion dirtyRegion, IValidationContext context,
if ((end - start) > 6) {
String def = document.get().substring(start + 2, end);
String varName = JSFResourceBundleDetector
- .getBundleVariableName(def);
+ .getBundleVariableName(def);
String key = JSFResourceBundleDetector
- .getResourceKey(def);
+ .getResourceKey(def);
if (varName != null && key != null) {
if (varName.length() > 0) {
IRegion refReg = JSFResourceBundleDetector
- .resolveResourceBundleRefPos(document,
- varName);
+ .resolveResourceBundleRefPos(document,
+ varName);
if (refReg == null) {
start = document.get().indexOf("#{", end);
@@ -167,31 +161,32 @@ public void validateRegion(IRegion dirtyRegion, IValidationContext context,
int bundleStart = refReg.getOffset();
int bundleEnd = refReg.getOffset()
- + refReg.getLength();
+ + refReg.getLength();
if (manager.isKeyBroken(
- document.get().substring(
- refReg.getOffset(),
- refReg.getOffset()
- + refReg.getLength()),
- key)) {
+ document.get().substring(
+ refReg.getOffset(),
+ refReg.getOffset()
+ + refReg.getLength()),
+ key)) {
SLLocation subMarker = new SLLocation(file,
- bundleStart, bundleEnd, document
- .get().substring(
- bundleStart,
- bundleEnd));
+ bundleStart, bundleEnd, document
+ .get().substring(
+ bundleStart,
+ bundleEnd));
EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
- new String[] { key, subMarker.getLiteral() }),
- new SLLocation(file,
- start+2, end, key),
- IMarkerConstants.CAUSE_BROKEN_REFERENCE,
- key,
- subMarker,
- "jsf");
+ .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");
}
}
}
@@ -204,6 +199,7 @@ public void validateRegion(IRegion dirtyRegion, IValidationContext context,
}
@Override
- public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) {}
+ 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 15c2d2a5..fe5188e1 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
@@ -24,7 +24,7 @@ public class Activator extends AbstractUIPlugin {
// The shared instance
private static Activator plugin;
-
+
/**
* The constructor
*/
@@ -33,7 +33,10 @@ public Activator() {
/*
* (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
@@ -42,7 +45,10 @@ public void start(BundleContext context) throws Exception {
/*
* (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
@@ -51,7 +57,7 @@ public void stop(BundleContext context) throws Exception {
/**
* Returns the shared instance
- *
+ *
* @return the shared instance
*/
public static Activator getDefault() {
@@ -59,10 +65,11 @@ public static Activator getDefault() {
}
/**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the 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) {
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 4a474902..e7aa31fc 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
@@ -21,13 +21,17 @@
*/
public class Application implements IApplication {
- /* (non-Javadoc)
- * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
+ /*
+ * (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());
+ int returnCode = PlatformUI.createAndRunWorkbench(display,
+ new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
@@ -37,7 +41,9 @@ public Object start(IApplicationContext context) {
}
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop() {
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 e9649ad1..ee1cda38 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
@@ -36,47 +36,51 @@ 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"));
- {
+
+ 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(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 ToolBarContributionItem(fileToolBar,
+ IWorkbenchActionConstants.TOOLBAR_FILE));
}
-
+
coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR));
}
-
+
@Override
protected void fillMenuBar(IMenuManager menuBar) {
super.fillMenuBar(menuBar);
-
+
menuBar.add(fileMenu());
- menuBar.add(new GroupMarker (IWorkbenchActionConstants.MB_ADDITIONS));
+ menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menuBar.add(helpMenu());
}
- private MenuManager helpMenu () {
- MenuManager helpMenu = new MenuManager ("&Help", IWorkbenchActionConstants.M_HELP);
-
+ 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));
@@ -89,17 +93,19 @@ private MenuManager fileMenu() {
menu.add(getAction(ActionFactory.SAVE.getId()));
menu.add(getAction(ActionFactory.SAVE_ALL.getId()));
- menu.add(ContributionItemFactory.REOPEN_EDITORS.create(getActionBarConfigurer().getWindowConfigurer().getWindow()));
+ 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));
@@ -109,10 +115,10 @@ protected void makeActions(IWorkbenchWindow 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 4d0ea4ae..5a897172 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
@@ -20,14 +20,14 @@ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective";
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer) {
+ IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}
public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}
-
+
@Override
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
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 c56933e4..93cb05f9 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
@@ -32,26 +32,26 @@
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
/** Workbench state **/
private IWorkbenchWindow window;
-
+
/** System tray item / icon **/
private TrayItem trayItem;
private Image trayImage;
-
+
/** Command ids **/
- private final static String COMMAND_ABOUT_ID = "org.eclipse.ui.help.aboutAction";
- private final static String COMMAND_EXIT_ID = "org.eclipse.ui.file.exit";
-
- public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
+ 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) {
+ IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
@@ -60,36 +60,36 @@ public void preWindowOpen() {
configurer.setShowFastViewBars(true);
configurer.setShowCoolBar(true);
configurer.setShowStatusLine(true);
- configurer.setInitialSize(new Point (1024, 768));
-
+ configurer.setInitialSize(new Point(1024, 768));
+
/** Init workspace and container project */
try {
FileUtils.getProject();
} catch (CoreException e) {
}
}
-
+
@Override
public void postWindowOpen() {
super.postWindowOpen();
window = getWindowConfigurer().getWindow();
-
+
/** Add the application into the system tray icon section **/
- trayItem = initTrayItem (window);
-
+ 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) {
+ public void shellIconified(ShellEvent e) {
window.getShell().setMinimized(true);
window.getShell().setVisible(false);
}
});
-
+
trayItem.addListener(SWT.DefaultSelection, new Listener() {
- public void handleEvent (Event event) {
+ public void handleEvent(Event event) {
Shell shell = window.getShell();
if (!shell.isVisible() || window.getShell().getMinimized()) {
window.getShell().setMinimized(false);
@@ -97,68 +97,73 @@ public void handleEvent (Event event) {
}
}
});
-
+
// Add actions menu
- hookActionsMenu ();
+ hookActionsMenu();
}
}
-
- private void hookActionsMenu () {
- trayItem.addListener (SWT.MenuDetect, new Listener () {
+
+ 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);
+ 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 () {
+ 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);
+ 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);
-
+
+ MenuItem sep = new MenuItem(menu, SWT.SEPARATOR);
+
// Add exit action
- MenuItem exit = new MenuItem (menu, SWT.NONE);
+ MenuItem exit = new MenuItem(menu, SWT.NONE);
exit.setText("Exit");
- exit.addListener (SWT.Selection, new Listener() {
+ 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);
+ IHandlerService handlerService = (IHandlerService) window
+ .getService(IHandlerService.class);
try {
- handlerService.executeCommand (COMMAND_EXIT_ID, null);
+ handlerService
+ .executeCommand(COMMAND_EXIT_ID, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
-
+
menu.setVisible(true);
}
});
}
-
- private TrayItem initTrayItem (IWorkbenchWindow window) {
+
+ 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();
+ 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 {
@@ -166,7 +171,7 @@ public void dispose() {
} catch (Exception e) {
e.printStackTrace();
}
-
+
try {
if (trayImage != null)
trayImage.dispose();
@@ -176,7 +181,7 @@ public void dispose() {
e.printStackTrace();
}
}
-
+
@Override
public void postWindowClose() {
super.postWindowClose();
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java
index 1eebca8b..910e91fe 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
@@ -14,23 +14,23 @@
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipselabs.tapiji.translator.views.GlossaryView;
-
public class Perspective implements IPerspectiveFactory {
-
+
public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(true);
layout.setFixed(true);
-
- initEditorArea (layout);
- initViewsArea (layout);
+
+ initEditorArea(layout);
+ initViewsArea(layout);
}
private void initViewsArea(IPageLayout layout) {
- layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM, .6f, IPageLayout.ID_EDITOR_AREA);
+ layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM,
+ .6f, IPageLayout.ID_EDITOR_AREA);
}
private void initEditorArea(IPageLayout layout) {
-
+
}
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
index 66fac9ba..3bfaa322 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
@@ -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 1d7339b1..ad78187d 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
@@ -23,7 +23,6 @@
import org.eclipselabs.tapiji.translator.core.GlossaryManager;
import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
/** The workbench window */
@@ -31,28 +30,30 @@ public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
@Override
public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "New Glossary", SWT.SAVE, new String[] {"*.xml"} );
-
+ String fileName = FileUtils.queryFileName(window.getShell(),
+ "New Glossary", SWT.SAVE, new String[] { "*.xml" });
+
if (!fileName.endsWith(".xml")) {
if (fileName.endsWith("."))
fileName += "xml";
else
fileName += ".xml";
}
-
- if (new File (fileName).exists()) {
+
+ 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})))
+
+ 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));
- }
+ IWorkbenchPage page = window.getActivePage();
+ GlossaryManager.newGlossary(new File(fileName));
+ }
}
@Override
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 04ee0f18..2ba8eb2d 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
@@ -22,27 +22,27 @@
import org.eclipselabs.tapiji.translator.core.GlossaryManager;
import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
-
+
/** The workbench window */
private IWorkbenchWindow window;
@Override
public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "Open Glossary", SWT.OPEN, new String[] {"*.xml"} );
+ 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!");
+ MessageDialog.openError(window.getShell(), "Cannot open Glossary",
+ "The choosen file does not represent a Glossary!");
return;
}
-
+
if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
+ IWorkbenchPage page = window.getActivePage();
if (fileName != null) {
- GlossaryManager.loadGlossary(new File (fileName));
+ GlossaryManager.loadGlossary(new File(fileName));
}
- }
+ }
}
@Override
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 5d04f308..e59ed45d 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
@@ -24,16 +24,15 @@
import org.eclipselabs.tapiji.translator.model.Glossary;
-
public class GlossaryManager {
private Glossary glossary;
private File file;
- private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener> ();
-
- public GlossaryManager (File file, boolean overwrite) throws Exception {
+ private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener>();
+
+ public GlossaryManager(File file, boolean overwrite) throws Exception {
this.file = file;
-
+
if (file.exists() && !overwrite) {
// load the existing glossary
glossary = new Glossary();
@@ -42,48 +41,50 @@ public GlossaryManager (File file, boolean overwrite) throws Exception {
glossary = (Glossary) unmarshaller.unmarshal(file);
} else {
// Create a new glossary
- glossary = new Glossary ();
+ glossary = new Glossary();
saveGlossary();
}
}
-
- public void saveGlossary () throws Exception {
+
+ 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) {
+
+ public void setGlossary(Glossary glossary) {
this.glossary = glossary;
}
-
- public Glossary getGlossary () {
+
+ public Glossary getGlossary() {
return glossary;
}
-
- public static void loadGlossary (File file) {
+
+ public static void loadGlossary(File file) {
/* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
+ LoadGlossaryEvent event = new LoadGlossaryEvent(file);
for (ILoadGlossaryListener listener : loadGlossaryListeners) {
listener.glossaryLoaded(event);
}
}
-
- public static void registerLoadGlossaryListener (ILoadGlossaryListener listener) {
+
+ public static void registerLoadGlossaryListener(
+ ILoadGlossaryListener listener) {
loadGlossaryListeners.add(listener);
}
-
- public static void unregisterLoadGlossaryListener (ILoadGlossaryListener listener) {
+
+ public static void unregisterLoadGlossaryListener(
+ ILoadGlossaryListener listener) {
loadGlossaryListeners.remove(listener);
}
public static void newGlossary(File file) {
/* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
+ 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 591edac6..e460f2d1 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
@@ -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 815f31d1..65cbd414 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
@@ -16,25 +16,25 @@ public class LoadGlossaryEvent {
private boolean newGlossary = false;
private File glossaryFile;
-
- public LoadGlossaryEvent (File glossaryFile) {
+
+ public LoadGlossaryEvent(File glossaryFile) {
this.glossaryFile = glossaryFile;
}
-
+
public File getGlossaryFile() {
return glossaryFile;
}
-
+
public void setNewGlossary(boolean newGlossary) {
this.newGlossary = newGlossary;
}
-
+
public boolean isNewGlossary() {
return newGlossary;
}
-
+
public void setGlossaryFile(File glossaryFile) {
this.glossaryFile = glossaryFile;
}
-
+
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
index 0aa1aad6..d03b760e 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
@@ -27,29 +27,29 @@ public class Glossary implements Serializable {
private static final long serialVersionUID = 2070750758712154134L;
public Info info;
-
- @XmlElementWrapper (name="terms")
- @XmlElement (name = "term")
+
+ @XmlElementWrapper(name = "terms")
+ @XmlElement(name = "term")
public List<Term> terms;
-
+
public Glossary() {
- terms = new ArrayList <Term> ();
+ terms = new ArrayList<Term>();
info = new Info();
}
-
- public Term[] getAllTerms () {
- return terms.toArray(new Term [terms.size()]);
+
+ public Term[] getAllTerms() {
+ return terms.toArray(new Term[terms.size()]);
}
public int getIndexOfLocale(String referenceLocale) {
int i = 0;
-
+
for (String locale : info.translations) {
if (locale.equalsIgnoreCase(referenceLocale))
return i;
i++;
}
-
+
return 0;
}
@@ -59,8 +59,8 @@ public void removeTerm(Term elem) {
terms.remove(term);
break;
}
-
- if (term.removeTerm (elem))
+
+ if (term.removeTerm(elem))
break;
}
}
@@ -70,16 +70,16 @@ public void addTerm(Term parentTerm, Term newTerm) {
this.terms.add(newTerm);
return;
}
-
+
for (Term term : terms) {
if (term == parentTerm) {
term.subTerms.add(newTerm);
break;
}
-
- if (term.addTerm (parentTerm, newTerm))
+
+ 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 fbfff0c5..24376dc0 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
@@ -19,24 +19,24 @@
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
-@XmlAccessorType (XmlAccessType.FIELD)
+@XmlAccessorType(XmlAccessType.FIELD)
public class Info implements Serializable {
private static final long serialVersionUID = 8607746669906026928L;
- @XmlElementWrapper (name = "locales")
- @XmlElement (name = "locale")
+ @XmlElementWrapper(name = "locales")
+ @XmlElement(name = "locale")
public List<String> translations;
-
- public Info () {
+
+ public Info() {
this.translations = new ArrayList<String>();
-
+
// Add the default Locale
this.translations.add("Default");
}
-
- public String[] getTranslations () {
- return translations.toArray(new String [translations.size()]);
+
+ 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 16373066..afa6f3d3 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
@@ -20,65 +20,65 @@
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlTransient;
-@XmlAccessorType (XmlAccessType.FIELD)
+@XmlAccessorType(XmlAccessType.FIELD)
public class Term implements Serializable {
-
+
private static final long serialVersionUID = 7004998590181568026L;
- @XmlElementWrapper (name = "translations")
- @XmlElement (name = "translation")
+ @XmlElementWrapper(name = "translations")
+ @XmlElement(name = "translation")
public List<Translation> translations;
-
- @XmlElementWrapper (name = "terms")
- @XmlElement (name = "term")
+
+ @XmlElementWrapper(name = "terms")
+ @XmlElement(name = "term")
public List<Term> subTerms;
-
+
public Term parentTerm;
-
+
@XmlTransient
private Object info;
-
- public Term () {
- translations = new ArrayList<Translation> ();
- subTerms = new ArrayList<Term> ();
+
+ public Term() {
+ translations = new ArrayList<Translation>();
+ subTerms = new ArrayList<Term>();
parentTerm = null;
info = null;
}
-
+
public void setInfo(Object info) {
this.info = info;
}
-
+
public Object getInfo() {
return info;
}
-
- public Term[] getAllSubTerms () {
+
+ public Term[] getAllSubTerms() {
return subTerms.toArray(new Term[subTerms.size()]);
}
-
+
public Term getParentTerm() {
return parentTerm;
}
-
- public boolean hasChildTerms () {
+
+ public boolean hasChildTerms() {
return subTerms != null && subTerms.size() > 0;
}
-
+
public Translation[] getAllTranslations() {
- return translations.toArray(new Translation [translations.size()]);
+ return translations.toArray(new Translation[translations.size()]);
}
-
- public Translation getTranslation (String language) {
+
+ public Translation getTranslation(String language) {
for (Translation translation : translations) {
if (translation.id.equalsIgnoreCase(language))
return translation;
}
-
- Translation newTranslation = new Translation ();
+
+ Translation newTranslation = new Translation();
newTranslation.id = language;
translations.add(newTranslation);
-
+
return newTranslation;
}
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 df44500e..b62184ea 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
@@ -16,19 +16,19 @@
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
-@XmlAccessorType (XmlAccessType.FIELD)
-@XmlType (name = "Translation")
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "Translation")
public class Translation implements Serializable {
private static final long serialVersionUID = 2033276999496196690L;
public String id;
-
+
public String value;
-
- public Translation () {
+
+ 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 62386f6a..949a61bc 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
@@ -25,113 +25,113 @@
import org.junit.Assert;
import org.junit.Test;
-
public class JaxBTest {
@Test
- public void testModel () {
- Glossary glossary = new Glossary ();
- Info info = new Info ();
+ 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 ();
+
+ Translation tranl1 = new Translation();
tranl1.id = "default";
tranl1.value = "Hallo Welt";
-
- Translation tranl2 = new Translation ();
+
+ Translation tranl2 = new Translation();
tranl2.id = "de";
tranl2.value = "Hallo Welt";
-
- Translation tranl3 = new Translation ();
+
+ Translation tranl3 = new Translation();
tranl3.id = "en";
tranl3.value = "Hello World!";
-
- term.translations = new ArrayList <Translation>();
+
+ 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 ();
+
+ Translation tranl12 = new Translation();
tranl12.id = "default";
tranl12.value = "Hallo Welt2";
-
- Translation tranl22 = new Translation ();
+
+ Translation tranl22 = new Translation();
tranl22.id = "de";
tranl22.value = "Hallo Welt2";
-
- Translation tranl32 = new Translation ();
+
+ Translation tranl32 = new Translation();
tranl32.id = "en";
tranl32.value = "Hello World2!";
-
- term2.translations = new ArrayList <Translation>();
+
+ term2.translations = new ArrayList<Translation>();
term2.translations.add(tranl12);
term2.translations.add(tranl22);
term2.translations.add(tranl32);
- //term2.parentTerm = term;
-
+ // term2.parentTerm = term;
+
term.subTerms = new ArrayList<Term>();
term.subTerms.add(term2);
-
+
// Hello World 3
Term term3 = new Term();
-
- Translation tranl13 = new Translation ();
+
+ Translation tranl13 = new Translation();
tranl13.id = "default";
tranl13.value = "Hallo Welt3";
-
- Translation tranl23 = new Translation ();
+
+ Translation tranl23 = new Translation();
tranl23.id = "de";
tranl23.value = "Hallo Welt3";
-
- Translation tranl33 = new Translation ();
+
+ Translation tranl33 = new Translation();
tranl33.id = "en";
tranl33.value = "Hello World3!";
-
- term3.translations = new ArrayList <Translation>();
+
+ 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
+
+ // Serialize model
try {
JAXBContext context = JAXBContext.newInstance(glossary.getClass());
Marshaller marshaller = context.createMarshaller();
- marshaller.marshal(glossary, new FileWriter ("C:\\test.xml"));
+ marshaller.marshal(glossary, new FileWriter("C:\\test.xml"));
} catch (Exception e) {
e.printStackTrace();
Assert.assertFalse(true);
}
}
-
+
@Test
- public void testReadModel () {
+ 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"));
+ 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 38f488dc..5738a3a3 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
@@ -25,119 +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 + ")$";
-
+ /** 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) {
+
+ public static boolean isResourceBundle(String fileName) {
return fileName.toLowerCase().endsWith(".properties");
}
-
- public static boolean isGlossary (String fileName) {
+
+ public static boolean isGlossary(String fileName) {
return fileName.toLowerCase().endsWith(".xml");
}
- public static IWorkspace getWorkspace () {
+ public static IWorkspace getWorkspace() {
if (workspace == null) {
workspace = ResourcesPlugin.getWorkspace();
}
-
+
return workspace;
}
-
- public static IProject getProject () throws CoreException {
+
+ public static IProject getProject() throws CoreException {
if (project == null) {
- project = getWorkspace().getRoot().getProject("ExternalResourceBundles");
+ project = getWorkspace().getRoot().getProject(
+ "ExternalResourceBundles");
}
-
+
if (!project.exists())
project.create(null);
if (!project.isOpen())
project.open(null);
-
+
return project;
}
-
- public static void prePareEditorInputs () {
+
+ 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 */
+
+ 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());
+
+ 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);
- }
- }
-
+ for (String fn : files) {
+ File fo = new File(parentDir, fn);
+ if (!fo.isFile())
+ continue;
+
+ IPath newFilePath = new Path(fo.getAbsolutePath());
+ if (fo.getName().matches(regex)
+ && !path.toFile().getName()
+ .equals(newFilePath.toFile().getName())) {
+ IFile newFile = project
+ .getFile(toProjectRelativePathName(newFilePath));
+ newFile.createLink(newFilePath, IResource.REPLACE, null);
+ }
+ }
+
return file;
}
- protected static String toProjectRelativePathName (IPath path) {
+ 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());
+ 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 );
+ 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();
-
-
+ 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 9917728a..a2828e2b 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
@@ -17,74 +17,86 @@
import org.eclipse.swt.widgets.Display;
import org.eclipselabs.tapiji.translator.Activator;
-
public class FontUtils {
/**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
+ * Gets a system color.
+ *
+ * @param colorId
+ * SWT constant
+ * @return system color
+ */
+ public static Color getSystemColor(int colorId) {
+ return Activator.getDefault().getWorkbench().getDisplay()
+ .getSystemColor(colorId);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style (size is unaffected).
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style) {
+ // TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
+ }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style and relative size.
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style, int relSize) {
+ // TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
+ }
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(int style) {
+ return createFont(style, 0);
+ }
+
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(int style, int relSize) {
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
+ }
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
index ab0eb2f2..b89cd208 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
@@ -10,7 +10,6 @@
******************************************************************************/
package org.eclipselabs.tapiji.translator.views;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
@@ -54,20 +53,19 @@
import org.eclipselabs.tapiji.translator.views.widgets.model.GlossaryViewState;
import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
-
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;
@@ -82,42 +80,45 @@ public class GlossaryView extends ViewPart implements ILoadGlossaryListener {
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 () {
- /** Register the view for being informed each time a new glossary is loaded into the translator */
+ 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.
+ * 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);
+
+ initLayout(parent);
+ initSearchBar(parent);
+ initMessagesTree(parent);
makeActions();
hookContextMenu();
contributeToActionBars();
- initListener (parent);
+ initListener(parent);
}
-
- protected void initListener (Composite parent) {
+
+ protected void initListener(Composite parent) {
filter.addModifyListener(new ModifyListener() {
-
+
@Override
public void modifyText(ModifyEvent e) {
if (glossary != null && glossary.getGlossary() != null)
@@ -125,71 +126,76 @@ public void modifyText(ModifyEvent e) {
}
});
}
-
- protected void initLayout (Composite parent) {
- GridLayout mainLayout = new GridLayout ();
+
+ protected void initLayout(Composite parent) {
+ GridLayout mainLayout = new GridLayout();
mainLayout.numColumns = 1;
parent.setLayout(mainLayout);
-
+
}
-
- protected void initSearchBar (Composite parent) {
+
+ 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);
+ 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);
+
+ 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));
+ 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 = 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 = 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
+ .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;
@@ -197,52 +203,68 @@ public void handleEvent (Event event) {
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;
+
+ 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;
+ ((GridData) lblScale.getLayoutData()).heightHint = 0;
+ ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0;
}
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);
-
+ 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 (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.bindContentToSelection(viewState
+ .isSelectiveViewEnabled());
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;
@@ -258,8 +280,8 @@ protected void initMessagesTree(Composite parent) {
public void setFocus() {
treeViewer.setFocus();
}
-
- protected void redrawTreeViewer () {
+
+ protected void redrawTreeViewer() {
parent.setRedraw(false);
treeViewer.dispose();
try {
@@ -275,34 +297,38 @@ protected void redrawTreeViewer () {
treeViewer.layout(true);
refreshSearchbarState();
}
-
+
/*** ACTIONS ***/
private void makeActions() {
- newEntry = new Action () {
+ newEntry = new Action() {
@Override
public void run() {
super.run();
}
};
- newEntry.setText ("New term ...");
+ newEntry.setText("New term ...");
newEntry.setDescription("Creates a new glossary entry");
newEntry.setToolTipText("Creates a new glossary entry");
-
- enableFuzzyMatching = new Action () {
- public void run () {
+
+ enableFuzzyMatching = new Action() {
+ public void run() {
super.run();
- treeViewer.enableFuzzyMatching(!treeViewer.isFuzzyMatchingEnabled());
- viewState.setFuzzyMatchingEnabled(treeViewer.isFuzzyMatchingEnabled());
+ treeViewer.enableFuzzyMatching(!treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
refreshSearchbarState();
}
};
enableFuzzyMatching.setText("Fuzzy-Matching");
- enableFuzzyMatching.setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
+ enableFuzzyMatching
+ .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled());
- enableFuzzyMatching.setToolTipText(enableFuzzyMatching.getDescription());
-
- editable = new Action () {
- public void run () {
+ enableFuzzyMatching
+ .setToolTipText(enableFuzzyMatching.getDescription());
+
+ editable = new Action() {
+ public void run() {
super.run();
treeViewer.setEditable(!treeViewer.isEditable());
}
@@ -311,39 +337,46 @@ public void run () {
editable.setDescription("Allows you to edit Resource-Bundle entries.");
editable.setChecked(viewState.isEditable());
editable.setToolTipText(editable.getDescription());
-
+
/** New Translation */
- newTranslation = new Action ("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 */
+ /*
+ * 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]);
+ 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 */
+
+ /*
+ * 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());
+ return o1.getDisplayName().compareTo(
+ o2.getDisplayName());
}
});
- ListSelectionDialog dlg = new ListSelectionDialog(getSite().getShell(),
- allLocales,
- new LocaleContentProvider(),
- new LocaleLabelProvider(),
- "Select the Translation:");
+ 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();
@@ -367,35 +400,43 @@ public int compare(Locale o1, Locale o2) {
};
newTranslation.setDescription("Adds a new Locale for translation.");
newTranslation.setToolTipText(newTranslation.getDescription());
-
+
/** Delete Translation */
- deleteTranslation = new Action ("Delete Translation ...") {
+ deleteTranslation = new Action("Delete Translation ...") {
public void run() {
- /* Construct a list of type locale from all existing translations */
+ /*
+ * 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)
+
+ 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]);
+ 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:");
+
+ /*
+ * 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();
@@ -403,7 +444,8 @@ public void run() {
for (Object delLoc : delLocales) {
toRemove.add(strLoc.get(locales.indexOf(delLoc)));
}
- glossary.getGlossary().info.translations.removeAll(toRemove);
+ glossary.getGlossary().info.translations
+ .removeAll(toRemove);
try {
glossary.saveGlossary();
displayActions = null;
@@ -416,33 +458,36 @@ public void run() {
}
};
};
- deleteTranslation.setDescription("Deletes a specific Locale from the translation glossary.");
+ 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());
+ glossaryEditContribution = new GlossaryEntryMenuContribution(
+ treeViewer, !treeViewer.getViewer().getSelection()
+ .isEmpty());
manager.add(this.glossaryEditContribution);
manager.add(new Separator());
}
-
+
manager.add(enableFuzzyMatching);
manager.add(editable);
-
+
if (this.glossary != null && this.glossary.getGlossary() != null) {
manager.add(new Separator());
manager.add(newTranslation);
manager.add(deleteTranslation);
- createMenuAdditions (manager);
+ createMenuAdditions(manager);
}
}
@@ -455,40 +500,43 @@ public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
- Menu menu = menuMgr.createContextMenu(treeViewer.getViewer().getControl());
+ 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());
+ 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);
}
-
- createMenuAdditions (manager);
+
+ createMenuAdditions(manager);
}
-
- private void createShowContentMenu (IMenuManager manager) {
- showMenu = new MenuManager ("&Show", "show");
-
- if (showAll == null || showSelectiveContent == null) {
- showAll = new Action ("All terms", Action.AS_RADIO_BUTTON) {
+
+ 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();
@@ -498,56 +546,63 @@ public void run() {
showAll.setDescription("Display all glossary entries");
showAll.setToolTipText(showAll.getDescription());
showAll.setChecked(!viewState.isSelectiveViewEnabled());
-
- showSelectiveContent = new Action ("Relevant terms", Action.AS_RADIO_BUTTON) {
+
+ 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
+ .setDescription("Displays only terms that are relevant for the currently selected Resource-Bundle entry");
+ showSelectiveContent.setToolTipText(showSelectiveContent
+ .getDescription());
showSelectiveContent.setChecked(viewState.isSelectiveViewEnabled());
}
-
+
showMenu.add(showAll);
showMenu.add(showSelectiveContent);
-
+
manager.add(showMenu);
}
-
+
private void createMenuAdditions(IMenuManager manager) {
// Make reference language actions
- if (glossary != null && glossary.getGlossary() != null) {
+ 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");
+
+ 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) {
+ 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();
+ referenceLanguage = viewState
+ .getReferenceLanguage();
if (!lang.equalsIgnoreCase(referenceLanguage)) {
viewState.setReferenceLanguage(lang);
-
+
// trigger redraw of displayed translations menu
displayActions = null;
-
+
redrawTreeViewer();
}
}
@@ -556,42 +611,46 @@ public void run() {
String referenceLanguage = translations[0];
if (viewState.getReferenceLanguage() != null)
referenceLanguage = viewState.getReferenceLanguage();
- else
+ else
viewState.setReferenceLanguage(referenceLanguage);
-
- refLangAction.setChecked(lang.equalsIgnoreCase(referenceLanguage));
+
+ refLangAction.setChecked(lang
+ .equalsIgnoreCase(referenceLanguage));
refLangAction.setText(l.getDisplayName());
referenceActions.add(refLangAction);
}
}
-
+
for (Action a : referenceActions) {
referenceMenu.add(a);
}
-
+
// Make display language actions
- displayMenu = new MenuManager ("&Displayed Translations", "displaylang");
-
+ 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) {
+ 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();
@@ -613,11 +672,11 @@ public void run() {
displayActions.add(refLangAction);
}
}
-
+
for (Action a : displayActions) {
displayMenu.add(a);
}
-
+
manager.add(new Separator());
manager.add(referenceMenu);
manager.add(displayMenu);
@@ -626,32 +685,36 @@ public void run() {
private void fillLocalToolBar(IToolBarManager manager) {
}
-
+
@Override
- public void saveState (IMemento memento) {
+ public void saveState(IMemento memento) {
super.saveState(memento);
try {
- viewState.setEditable (treeViewer.isEditable());
+ 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.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setMatchingPrecision(treeViewer.getMatchingPrecision());
+ viewState.setSelectiveViewEnabled(treeViewer
+ .isSelectiveViewEnabled());
viewState.saveState(memento);
- } catch (Exception e) {}
+ } 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);
+ glossary = new GlossaryManager(new File(
+ viewState.getGlossaryFile()), false);
} catch (Exception e) {
e.printStackTrace();
}
@@ -662,16 +725,19 @@ public void init(IViewSite site, IMemento memento) throws PartInitException {
public void glossaryLoaded(LoadGlossaryEvent event) {
File glossaryFile = event.getGlossaryFile();
try {
- this.glossary = new GlossaryManager (glossaryFile, event.isNewGlossary());
- viewState.setGlossaryFile (glossaryFile.getAbsolutePath());
-
+ this.glossary = new GlossaryManager(glossaryFile,
+ event.isNewGlossary());
+ viewState.setGlossaryFile(glossaryFile.getAbsolutePath());
+
referenceActions = null;
displayActions = null;
- viewState.setDisplayLangArr(glossary.getGlossary().info.getTranslations());
+ 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!");
+ 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 353d9415..6c8fcec8 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
@@ -17,14 +17,14 @@
import org.eclipse.jface.viewers.Viewer;
public class LocaleContentProvider implements IStructuredContentProvider {
-
+
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
-
+
}
@Override
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 c4f32d11..aa5f64f4 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
@@ -20,12 +20,12 @@ public class LocaleLabelProvider implements ILabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {
-
+
}
@Override
public void dispose() {
-
+
}
@Override
@@ -35,7 +35,7 @@ public boolean isLabelProperty(Object element, String property) {
@Override
public void removeListener(ILabelProviderListener listener) {
-
+
}
@Override
@@ -47,8 +47,8 @@ public Image getImage(Object element) {
@Override
public String getText(Object element) {
if (element != null && element instanceof Locale)
- return ((Locale)element).getDisplayName();
-
+ return ((Locale) element).getDisplayName();
+
return null;
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
index 344947eb..2422e95b 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
@@ -22,9 +22,8 @@
import org.eclipse.ui.PlatformUI;
import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
-
-public class GlossaryEntryMenuContribution extends ContributionItem implements
- ISelectionChangedListener {
+public class GlossaryEntryMenuContribution extends ContributionItem implements
+ ISelectionChangedListener {
private GlossaryWidget parentView;
private boolean legalSelection = false;
@@ -33,10 +32,11 @@ public class GlossaryEntryMenuContribution extends ContributionItem implements
private MenuItem addItem;
private MenuItem removeItem;
- public GlossaryEntryMenuContribution () {
+ public GlossaryEntryMenuContribution() {
}
- public GlossaryEntryMenuContribution (GlossaryWidget view, boolean legalSelection) {
+ public GlossaryEntryMenuContribution(GlossaryWidget view,
+ boolean legalSelection) {
this.legalSelection = legalSelection;
this.parentView = view;
parentView.addSelectionChangedListener(this);
@@ -49,17 +49,17 @@ public void fill(Menu menu, int index) {
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() {
-
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
+ addItem.addSelectionListener(new SelectionListener() {
+
@Override
public void widgetSelected(SelectionEvent e) {
parentView.addNewItem();
}
-
+
@Override
public void widgetDefaultSelected(SelectionEvent e) {
-
+
}
});
@@ -68,18 +68,18 @@ public void widgetDefaultSelected(SelectionEvent e) {
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() {
-
+ .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();
@@ -96,7 +96,7 @@ protected void enableMenuItems() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
legalSelection = !event.getSelection().isEmpty();
-// enableMenuItems ();
+ // 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 2180a60e..4c0c0b47 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
@@ -63,8 +63,8 @@
import org.eclipselabs.tapiji.translator.views.widgets.sorter.GlossaryEntrySorter;
import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-
-public class GlossaryWidget extends Composite implements IResourceChangeListener {
+public class GlossaryWidget extends Composite implements
+ IResourceChangeListener {
private final int TERM_COLUMN_WEIGHT = 1;
private final int DESCRIPTION_COLUMN_WEIGHT = 1;
@@ -99,29 +99,30 @@ public class GlossaryWidget extends Composite implements IResourceChangeListener
/*** ACTIONS ***/
private Action doubleClickAction;
- public GlossaryWidget(IWorkbenchPartSite site,
- Composite parent, int style, GlossaryManager manager, String refLang, List<String> dls) {
+ 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()]);
+ this.translationsToDisplay = dls
+ .toArray(new String[dls.size()]);
else
this.translationsToDisplay = glossary.info.getTranslations();
}
constructWidget();
- if (this.glossary!= null) {
+ if (this.glossary != null) {
initTreeViewer();
initMatchers();
initSorters();
@@ -133,20 +134,21 @@ public GlossaryWidget(IWorkbenchPartSite site,
protected void registerListeners() {
treeViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyPressed (KeyEvent event) {
- if (event.character == SWT.DEL &&
- event.stateMask == 0) {
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
deleteSelectedItems();
}
}
});
-
+
// Listen resource changes
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
}
-
+
protected void initSorters() {
- sorter = new GlossaryEntrySorter(treeViewer, sortInfo, glossary.getIndexOfLocale (referenceLocale), glossary.info.translations);
+ sorter = new GlossaryEntrySorter(treeViewer, sortInfo,
+ glossary.getIndexOfLocale(referenceLocale),
+ glossary.info.translations);
treeViewer.setSorter(sorter);
}
@@ -157,10 +159,10 @@ public void enableFuzzyMatching(boolean enable) {
if (!fuzzyMatchingEnabled && enable) {
if (matcher.getPattern().trim().length() > 1
- && matcher.getPattern().startsWith("*")
- && matcher.getPattern().endsWith("*"))
+ && matcher.getPattern().startsWith("*")
+ && matcher.getPattern().endsWith("*"))
pattern = pattern.substring(1).substring(0,
- pattern.length() - 2);
+ pattern.length() - 2);
matcher.setPattern(null);
}
}
@@ -179,26 +181,28 @@ 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 );
+ contentProvider = new GlossaryContentProvider(this.glossary);
treeViewer.setContentProvider(contentProvider);
- // init label provider
- labelProvider = new GlossaryLabelProvider(this.displayedTranslations.indexOf(referenceLocale), this.displayedTranslations, site.getPage());
+ // init label provider
+ labelProvider = new GlossaryLabelProvider(
+ this.displayedTranslations.indexOf(referenceLocale),
+ this.displayedTranslations, site.getPage());
treeViewer.setLabelProvider(labelProvider);
setTreeStructure(grouped);
@@ -206,10 +210,11 @@ protected void initTreeViewer() {
public void setTreeStructure(boolean grouped) {
this.grouped = grouped;
- ((GlossaryContentProvider)treeViewer.getContentProvider()).setGrouped(this.grouped);
+ ((GlossaryContentProvider) treeViewer.getContentProvider())
+ .setGrouped(this.grouped);
if (treeViewer.getInput() == null)
treeViewer.setUseHashlookup(false);
- treeViewer.setInput(this.glossary);
+ treeViewer.setInput(this.glossary);
treeViewer.refresh();
}
@@ -218,7 +223,7 @@ protected void constructWidget() {
this.setLayout(basicLayout);
treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
- | SWT.BORDER);
+ | SWT.BORDER);
Tree tree = treeViewer.getTree();
if (glossary != null) {
@@ -240,34 +245,39 @@ protected void constructWidget() {
}
/**
- * 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;
- }
-
+ * 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 = 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]);
-
+ 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 = new TreeColumn(tree, SWT.RIGHT_TO_LEFT/* getOrientation(l) */);
+
termColumn.setText(l.getDisplayName());
TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn);
termCol.setEditingSupport(new EditingSupport(treeViewer) {
@@ -277,17 +287,19 @@ protected void constructTreeColumns(Tree tree) {
protected void setValue(Object element, Object value) {
if (element instanceof Term) {
Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(referenceLocale);
-
+ Translation translation = (Translation) term
+ .getTranslation(referenceLocale);
+
if (translation != null) {
translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
+ Glossary gl = ((GlossaryContentProvider) treeViewer
+ .getContentProvider()).getGlossary();
manager.setGlossary(gl);
try {
manager.saveGlossary();
} catch (Exception e) {
e.printStackTrace();
- }
+ }
}
treeViewer.refresh();
}
@@ -301,8 +313,7 @@ protected Object getValue(Object element) {
@Override
protected CellEditor getCellEditor(Object element) {
if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
+ Composite tree = (Composite) treeViewer.getControl();
editor = new TextCellEditor(tree);
}
return editor;
@@ -326,89 +337,92 @@ public void widgetDefaultSelected(SelectionEvent e) {
}
});
basicLayout.setColumnData(termColumn, new ColumnWeightData(
- TERM_COLUMN_WEIGHT));
+ 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]);
-
+
+ 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);
+ 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);
-
+ Translation translation = (Translation) term
+ .getTranslation(sfLocale);
+
if (translation != null) {
translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
+ 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();
+ 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 ++;
+ DESCRIPTION_COLUMN_WEIGHT));
+ iCol++;
}
-
+
}
protected void updateSorter(int idx) {
@@ -436,13 +450,13 @@ protected void hookDragAndDrop() {
// Initialize drag source for copy event
DragSource dragSource = new DragSource(treeViewer.getControl(),
- DND.DROP_MOVE);
+ 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);
+ DND.DROP_MOVE);
dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() });
dropTarget.addDropListener(target);
}
@@ -470,7 +484,6 @@ public void doubleClick(DoubleClickEvent event) {
/*** SELECTION LISTENER ***/
-
private void refreshViewer() {
treeViewer.refresh();
}
@@ -486,7 +499,8 @@ public void setSearchString(String pattern) {
else
grouped = true;
labelProvider.setSearchEnabled(!grouped);
- this.setTreeStructure(grouped && sorter != null && sorter.getSortInfo().getColIdx() == 0);
+ this.setTreeStructure(grouped && sorter != null
+ && sorter.getSortInfo().getColIdx() == 0);
treeViewer.refresh();
}
@@ -519,15 +533,16 @@ public void setEditable(boolean editable) {
public void deleteSelectedItems() {
List<String> ids = new ArrayList<String>();
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
+ this.glossary = ((GlossaryContentProvider) treeViewer
+ .getContentProvider()).getGlossary();
+
ISelection selection = site.getSelectionProvider().getSelection();
if (selection instanceof IStructuredSelection) {
for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
+ .iterator(); iter.hasNext();) {
Object elem = iter.next();
if (elem instanceof Term) {
- this.glossary.removeTerm ((Term)elem);
+ this.glossary.removeTerm((Term) elem);
this.manager.setGlossary(this.glossary);
try {
this.manager.saveGlossary();
@@ -547,7 +562,7 @@ public void addNewItem() {
ISelection selection = site.getSelectionProvider().getSelection();
if (selection instanceof IStructuredSelection) {
for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
+ .iterator(); iter.hasNext();) {
Object elem = iter.next();
if (elem instanceof Term) {
parentTerm = ((Term) elem);
@@ -556,22 +571,24 @@ public void addNewItem() {
}
}
- InputDialog dialog = new InputDialog (this.getShell(), "Neuer Begriff",
- "Please, define the new term:", "", null);
-
+ 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();
-
+ 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 ();
+ Translation defaultTranslation = new Translation();
defaultTranslation.id = referenceLocale;
defaultTranslation.value = dialog.getValue();
newTerm.translations.add(defaultTranslation);
-
- this.glossary.addTerm (parentTerm, newTerm);
-
+
+ this.glossary.addTerm(parentTerm, newTerm);
+
this.manager.setGlossary(this.glossary);
try {
this.manager.saveGlossary();
@@ -594,25 +611,24 @@ public void setMatchingPrecision(float value) {
public float getMatchingPrecision() {
return matchingPrecision;
}
-
+
public Control getControl() {
return treeViewer.getControl();
}
-
- public Glossary getGlossary () {
+
+ public Glossary getGlossary() {
return this.glossary;
}
- public void addSelectionChangedListener(
- ISelectionChangedListener listener) {
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
treeViewer.addSelectionChangedListener(listener);
}
public String getReferenceLanguage() {
return referenceLocale;
}
-
- public void setReferenceLanguage (String lang) {
+
+ public void setReferenceLanguage(String lang) {
this.referenceLocale = lang;
}
@@ -620,11 +636,11 @@ public void bindContentToSelection(boolean enable) {
this.selectiveViewEnabled = enable;
initMatchers();
}
-
+
public boolean isSelectiveViewEnabled() {
return selectiveViewEnabled;
}
-
+
@Override
public void dispose() {
super.dispose();
@@ -636,5 +652,5 @@ 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 2215ea67..5211bff2 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
@@ -22,22 +22,22 @@
import org.eclipselabs.tapiji.translator.model.Term;
import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-
public class GlossaryDragSource implements DragSourceListener {
private final TreeViewer source;
private final GlossaryManager manager;
private List<Term> selectionList;
-
- public GlossaryDragSource (TreeViewer sourceView, GlossaryManager manager) {
+
+ 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());
+ GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source
+ .getContentProvider());
Glossary glossary = contentProvider.getGlossary();
for (Term selectionObject : selectionList)
glossary.removeTerm(selectionObject);
@@ -52,10 +52,11 @@ public void dragFinished(DragSourceEvent event) {
@Override
public void dragSetData(DragSourceEvent event) {
- selectionList = new ArrayList<Term> ();
- for (Object selectionObject : ((IStructuredSelection)source.getSelection()).toList())
+ selectionList = new ArrayList<Term>();
+ for (Object selectionObject : ((IStructuredSelection) source
+ .getSelection()).toList())
selectionList.add((Term) selectionObject);
-
+
event.data = selectionList.toArray(new Term[selectionList.size()]);
}
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 15758404..46cb8805 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
@@ -20,18 +20,17 @@
import org.eclipselabs.tapiji.translator.model.Term;
import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-
public class GlossaryDropTarget extends DropTargetAdapter {
private final TreeViewer target;
private final GlossaryManager manager;
-
- public GlossaryDropTarget (TreeViewer viewer, GlossaryManager manager) {
+
+ public GlossaryDropTarget(TreeViewer viewer, GlossaryManager manager) {
super();
this.target = viewer;
this.manager = manager;
}
-
- public void dragEnter (DropTargetEvent event) {
+
+ 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;
@@ -39,26 +38,28 @@ public void dragEnter (DropTargetEvent event) {
event.detail = DND.DROP_NONE;
}
}
-
- public void drop (DropTargetEvent event) {
- if (TermTransfer.getInstance().isSupportedType (event.currentDataType)) {
+
+ public void drop(DropTargetEvent event) {
+ if (TermTransfer.getInstance().isSupportedType(event.currentDataType)) {
Term parentTerm = null;
-
+
event.detail = DND.DROP_MOVE;
event.feedback = DND.FEEDBACK_INSERT_AFTER;
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof Term) {
+ if (event.item instanceof TreeItem
+ && ((TreeItem) event.item).getData() instanceof Term) {
parentTerm = ((Term) ((TreeItem) event.item).getData());
}
-
+
Term[] moveTerm = (Term[]) event.data;
- Glossary glossary = ((GlossaryContentProvider) target.getContentProvider()).getGlossary();
-
- /* Remove the move term from its initial position
- for (Term selectionObject : moveTerm)
- glossary.removeTerm(selectionObject);*/
-
+ Glossary glossary = ((GlossaryContentProvider) target
+ .getContentProvider()).getGlossary();
+
+ /*
+ * Remove the move term from its initial position for (Term
+ * selectionObject : moveTerm) glossary.removeTerm(selectionObject);
+ */
+
/* Insert the move term on its target position */
if (parentTerm == null) {
for (Term t : moveTerm)
@@ -67,7 +68,7 @@ public void drop (DropTargetEvent event) {
for (Term t : moveTerm)
parentTerm.subTerms.add(t);
}
-
+
manager.setGlossary(glossary);
try {
manager.saveGlossary();
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 1c078ceb..2dc7c984 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
@@ -23,7 +23,6 @@
import org.eclipse.swt.dnd.TransferData;
import org.eclipselabs.tapiji.translator.model.Term;
-
public class TermTransfer extends ByteArrayTransfer {
private static final String TERM = "term";
@@ -37,7 +36,7 @@ public static TermTransfer getInstance() {
}
public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
+ if (!checkType(object) || !isSupportedType(transferData)) {
DND.error(DND.ERROR_INVALID_DATA);
}
Term[] terms = (Term[]) object;
@@ -49,7 +48,7 @@ public void javaToNative(Object object, TransferData transferData) {
}
byte[] buffer = out.toByteArray();
oOut.close();
-
+
super.javaToNative(buffer, transferData);
} catch (IOException e) {
e.printStackTrace();
@@ -73,10 +72,10 @@ public Object nativeToJava(TransferData transferData) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(buffer);
ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
- Term newTerm = (Term) readIn.readObject();
- terms.add(newTerm);
- //}
+ // while (readIn.available() > 0) {
+ Term newTerm = (Term) readIn.readObject();
+ terms.add(newTerm);
+ // }
readIn.close();
} catch (Exception ex) {
ex.printStackTrace();
@@ -98,7 +97,7 @@ protected int[] getTypeIds() {
boolean checkType(Object object) {
if (object == null || !(object instanceof Term[])
- || ((Term[]) object).length == 0) {
+ || ((Term[]) object).length == 0) {
return false;
}
Term[] myTypes = (Term[]) 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 0c2cfb3d..d31d6bc0 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
@@ -16,26 +16,25 @@
import org.eclipselabs.tapiji.translator.model.Term;
import org.eclipselabs.tapiji.translator.model.Translation;
-
public class ExactMatcher extends ViewerFilter {
protected final StructuredViewer viewer;
protected String pattern = "";
protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
+
+ public ExactMatcher(StructuredViewer viewer) {
this.viewer = viewer;
}
-
- public String getPattern () {
+
+ public String getPattern() {
return pattern;
}
-
- public void setPattern (String p) {
+
+ public void setPattern(String p) {
boolean filtering = matcher != null;
if (p != null && p.trim().length() > 0) {
pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
+ matcher = new StringMatcher("*" + pattern + "*", true, false);
if (!filtering)
viewer.addFilter(this);
else
@@ -48,13 +47,13 @@ public void setPattern (String p) {
}
}
}
-
+
@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;
@@ -63,16 +62,17 @@ public boolean select(Viewer viewer, Object parentElement, Object element) {
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());
+ while ((start = value.toLowerCase().indexOf(
+ pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo.addFoundInTranslationRange(locale, start,
+ pattern.length());
}
selected = true;
}
- }
-
+ }
+
term.setInfo(filterInfo);
return selected;
}
-
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
index 281f4244..61a718c3 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
@@ -19,49 +19,49 @@
public class FilterInfo {
- private List<String> foundInTranslation = new ArrayList<String> ();
+ private List<String> foundInTranslation = new ArrayList<String>();
private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>();
private Map<String, Double> localeSimilarity = new HashMap<String, Double>();
-
+
public FilterInfo() {
-
+
}
-
- public void addSimilarity (String l, Double similarity) {
- localeSimilarity.put (l, similarity);
+
+ public void addSimilarity(String l, Double similarity) {
+ localeSimilarity.put(l, similarity);
}
- public Double getSimilarityLevel (String l) {
+ public Double getSimilarityLevel(String l) {
return localeSimilarity.get(l);
}
-
- public void addFoundInTranslation (String loc) {
+
+ public void addFoundInTranslation(String loc) {
foundInTranslation.add(loc);
}
-
- public void removeFoundInTranslation (String loc) {
+
+ public void removeFoundInTranslation(String loc) {
foundInTranslation.remove(loc);
}
-
- public void clearFoundInTranslation () {
+
+ public void clearFoundInTranslation() {
foundInTranslation.clear();
}
- public boolean hasFoundInTranslation (String l) {
+ public boolean hasFoundInTranslation(String l) {
return foundInTranslation.contains(l);
}
-
- public List<Region> getFoundInTranslationRanges (String locale) {
+
+ 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) {
+
+ 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 1a9eba5e..82463cca 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
@@ -21,29 +21,29 @@ public class FuzzyMatcher extends ExactMatcher {
protected ILevenshteinDistanceAnalyzer lvda;
protected float minimumSimilarity = 0.75f;
-
+
public FuzzyMatcher(StructuredViewer viewer) {
super(viewer);
lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
}
- public double getMinimumSimilarity () {
+ public double getMinimumSimilarity() {
return minimumSimilarity;
}
-
- public void setMinimumSimilarity (float 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;
-
+
Term term = (Term) element;
-
+
FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
+
for (Translation translation : term.getAllTranslations()) {
String value = translation.value;
String locale = translation.id;
@@ -54,12 +54,13 @@ public boolean select(Viewer viewer, Object parentElement, Object element) {
filterInfo.addFoundInTranslation(locale);
filterInfo.addSimilarity(locale, dist);
match = true;
- filterInfo.addFoundInTranslationRange(locale, 0, value.length());
+ filterInfo
+ .addFoundInTranslationRange(locale, 0, value.length());
}
}
-
+
term.setInfo(filterInfo);
- return match;
+ 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 daf8ccf8..05dd1649 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
@@ -26,47 +26,49 @@
import org.eclipselabs.tapiji.translator.model.Term;
import org.eclipselabs.tapiji.translator.model.Translation;
-public class SelectiveMatcher extends ViewerFilter
- implements ISelectionListener, ISelectionChangedListener {
+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) {
+
+ 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);
-
+ page.getWorkbenchWindow().getSelectionService()
+ .addSelectionListener(this);
+
viewer.addFilter(this);
viewer.refresh();
}
-
+
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (selectedItem == null)
return false;
-
+
Term term = (Term) element;
FilterInfo filterInfo = new FilterInfo();
boolean selected = false;
-
+
// Iterate translations
for (Translation translation : term.getAllTranslations()) {
String value = translation.value;
-
+
if (value.trim().length() == 0)
continue;
-
+
String locale = translation.id;
-
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
+
+ for (IMessage entry : selectedItem.getMessagesBundleGroup()
+ .getMessages(selectedItem.getMessageKey())) {
String ev = entry.getValue();
String[] subValues = ev.split("[\\s\\p{Punct}]+");
for (String v : subValues) {
@@ -74,8 +76,8 @@ public boolean select(Viewer viewer, Object parentElement, Object element) {
return true;
}
}
- }
-
+ }
+
return false;
}
@@ -84,14 +86,15 @@ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
try {
if (selection.isEmpty())
return;
-
+
if (!(selection instanceof IStructuredSelection))
return;
-
+
IStructuredSelection sel = (IStructuredSelection) selection;
selectedItem = (IKeyTreeNode) sel.iterator().next();
viewer.refresh();
- } catch (Exception e) { }
+ } catch (Exception e) {
+ }
}
@Override
@@ -99,7 +102,8 @@ public void selectionChanged(SelectionChangedEvent event) {
event.getSelection();
}
- public void dispose () {
- page.getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
+ 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 d0433354..39865904 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
@@ -16,436 +16,481 @@
* A string pattern matcher, suppporting "*" and "?" wildcards.
*/
public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
+ protected String fPattern;
+
+ protected int fLength; // pattern length
+
+ protected boolean fIgnoreWildCards;
+
+ protected boolean fIgnoreCase;
+
+ protected boolean fHasLeadingStar;
+
+ protected boolean fHasTrailingStar;
+
+ protected String fSegments[]; // the given pattern is split into * separated
+ // segments
+
+ /* boundary value beyond which we don't need to search in the text */
+ protected int fBound = 0;
+
+ protected static final char fSingleWildCard = '\u0000';
+
+ public static class Position {
+ int start; // inclusive
+
+ int end; // exclusive
+
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getEnd() {
+ return end;
+ }
+ }
+
+ /**
+ * StringMatcher constructor takes in a String object that is a simple
+ * pattern which may contain '*' for 0 and many characters and '?' for
+ * exactly one character.
+ *
+ * Literal '*' and '?' characters must be escaped in the pattern e.g.,
+ * "\*" means literal "*", etc.
+ *
+ * Escaping any other character (including the escape character itself),
+ * just results in that character in the pattern. e.g., "\a" means "a" and
+ * "\\" means "\"
+ *
+ * If invoking the StringMatcher with string literals in Java, don't forget
+ * escape characters are represented by "\\".
+ *
+ * @param pattern
+ * the pattern to match text against
+ * @param ignoreCase
+ * if true, case is ignored
+ * @param ignoreWildCards
+ * if true, wild cards and their escape sequences are ignored
+ * (everything is taken literally).
+ */
+ public StringMatcher(String pattern, boolean ignoreCase,
+ boolean ignoreWildCards) {
+ if (pattern == null) {
throw new IllegalArgumentException();
}
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
+ 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) {
+ int tlen = text.length();
+ if (start < 0) {
start = 0;
}
- if (end > tlen) {
+ if (end > tlen) {
end = tlen;
}
- if (end < 0 || start >= end) {
+ if (end < 0 || start >= end) {
return null;
}
- if (fLength == 0) {
+ if (fLength == 0) {
return new Position(start, start);
}
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
return null;
}
- return new Position(x, x + fLength);
- }
+ return new Position(x, x + fLength);
+ }
- int segCount = fSegments.length;
- if (segCount == 0) {
+ 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) {
+ 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) {
+ if (i == 0) {
matchStart = nextMatch;
}
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
+ 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 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) {
+ 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) {
+ if (start > end) {
return false;
}
- if (fIgnoreWildCards) {
+ if (fIgnoreWildCards) {
return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
}
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
return true;
}
- if (start == end) {
+ if (start == end) {
return fLength == 0;
}
- if (fLength == 0) {
+ if (fLength == 0) {
return start == end;
}
- int tlen = text.length();
- if (start < 0) {
+ int tlen = text.length();
+ if (start < 0) {
start = 0;
}
- if (end > tlen) {
+ if (end > tlen) {
end = tlen;
}
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
+ 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) {
+ 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) {
+ } 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$
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
+
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
+ }
+
+ /**
+ * This method parses the given pattern into segments seperated by wildcard
+ * '*' characters. Since wildcards are not being used in this case, the
+ * pattern consists of a single segment.
+ */
+ private void parseNoWildCards() {
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
+ }
+
+ /**
+ * Parses the given pattern into segments seperated by wildcard '*'
+ * characters.
+ *
+ * @param p
+ * , a String object that is a simple regular expression with '*'
+ * and/or '?'
+ */
+ private void parseWildCards() {
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
fHasLeadingStar = true;
}
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
+
+ Vector temp = new Vector();
+
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
+
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
+
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
+ }
+
+ /**
+ * @param text
+ * a string which contains no wildcard
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int posIn(String text, int start, int end) {// no wild card in
+ // pattern
+ int max = end - fLength;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
return -1;
}
- return i;
- }
+ return i;
+ }
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ 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 -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) {
+ }
+ 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)) {
+ 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)) {
+ // 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 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;
- }
+ return i;
+ }
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
return i;
}
- }
+ }
- return -1;
- }
+ 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 bbc057f8..d7781fed 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
@@ -17,61 +17,61 @@
import org.eclipse.ui.IMemento;
import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-
public class GlossaryViewState {
- private static final String TAG_GLOSSARY_FILE = "glossary_file";
- private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
- private static final String TAG_SELECTIVE_VIEW = "selective_content";
+ private static final String TAG_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) {
+ 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);
+
+ 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) {
@@ -80,47 +80,47 @@ public void saveState (IMemento memento) {
}
}
} catch (Exception e) {
-
+
}
}
-
- public void init (IMemento memento) {
+
+ public void init(IMemento memento) {
try {
if (memento == null)
return;
-
+
if (sortings == null)
sortings = new SortInfo();
sortings.init(memento);
-
+
IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
if (mFuzzyMatching != null)
fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
-
+
IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW);
if (mSelectiveView != null)
selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED);
-
+
IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
if (mMP != null)
matchingPrecision = mMP.getFloat(TAG_VALUE);
-
+
IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
if (mSStr != null)
searchString = mSStr.getString(TAG_VALUE);
-
+
IMemento mEditable = memento.getChild(TAG_EDITABLE);
if (mEditable != null)
editable = mEditable.getBoolean(TAG_ENABLED);
-
+
IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG);
if (mRefLang != null)
referenceLanguage = mRefLang.getString(TAG_VALUE);
-
+
IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE);
if (mGlossaryFile != null)
glossaryFile = mGlossaryFile.getString(TAG_VALUE);
-
+
IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES);
if (memDispLoc != null) {
displayLanguages = new ArrayList<String>();
@@ -129,30 +129,29 @@ public void init (IMemento memento) {
}
}
} catch (Exception e) {
-
+
}
}
-
- public GlossaryViewState(List<Locale> visibleLocales,
- SortInfo sortings, boolean fuzzyMatchingEnabled,
- String selectedBundleId) {
+
+ public GlossaryViewState(List<Locale> visibleLocales, SortInfo sortings,
+ boolean fuzzyMatchingEnabled, String selectedBundleId) {
super();
this.sortings = sortings;
this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
}
-
+
public SortInfo getSortings() {
return sortings;
}
-
+
public void setSortings(SortInfo sortings) {
this.sortings = sortings;
}
-
+
public boolean isFuzzyMatchingEnabled() {
return fuzzyMatchingEnabled;
}
-
+
public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
}
@@ -160,7 +159,7 @@ public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
public void setSearchString(String searchString) {
this.searchString = searchString;
}
-
+
public String getSearchString() {
return searchString;
}
@@ -176,28 +175,28 @@ public void setEditable(boolean editable) {
public float getMatchingPrecision() {
return matchingPrecision;
}
-
- public void setMatchingPrecision (float value) {
+
+ public void setMatchingPrecision(float value) {
this.matchingPrecision = value;
}
public String getReferenceLanguage() {
return this.referenceLanguage;
}
-
- public void setReferenceLanguage (String refLang) {
+
+ public void setReferenceLanguage(String refLang) {
this.referenceLanguage = refLang;
}
-
+
public List<String> getDisplayLanguages() {
return displayLanguages;
}
-
+
public void setDisplayLanguages(List<String> displayLanguages) {
this.displayLanguages = displayLanguages;
}
-
- public void setDisplayLangArr (String[] displayLanguages) {
+
+ public void setDisplayLangArr(String[] displayLanguages) {
this.displayLanguages = new ArrayList<String>();
for (String dl : displayLanguages) {
this.displayLanguages.add(dl);
@@ -207,15 +206,15 @@ public void setDisplayLangArr (String[] displayLanguages) {
public void setGlossaryFile(String absolutePath) {
this.glossaryFile = absolutePath;
}
-
+
public String getGlossaryFile() {
return glossaryFile;
}
-
+
public void setSelectiveViewEnabled(boolean selectiveViewEnabled) {
this.selectiveViewEnabled = selectiveViewEnabled;
}
-
+
public boolean isSelectiveViewEnabled() {
return selectiveViewEnabled;
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
index 8ba0e499..0546c7ad 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
@@ -18,24 +18,23 @@
import org.eclipselabs.tapiji.translator.model.Glossary;
import org.eclipselabs.tapiji.translator.model.Term;
-
public class GlossaryContentProvider implements ITreeContentProvider {
private Glossary glossary;
private boolean grouped = false;
-
- public GlossaryContentProvider (Glossary glossary) {
+
+ public GlossaryContentProvider(Glossary glossary) {
this.glossary = glossary;
}
-
- public Glossary getGlossary () {
+
+ public Glossary getGlossary() {
return glossary;
}
-
- public void setGrouped (boolean grouped) {
+
+ public void setGrouped(boolean grouped) {
this.grouped = grouped;
}
-
+
@Override
public void dispose() {
this.glossary = null;
@@ -49,12 +48,13 @@ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
@Override
public Object[] getElements(Object inputElement) {
- if (!grouped)
- return getAllElements(glossary.terms).toArray(new Term[glossary.terms.size()]);
-
+ if (!grouped)
+ return getAllElements(glossary.terms).toArray(
+ new Term[glossary.terms.size()]);
+
if (glossary != null)
return glossary.getAllTerms();
-
+
return null;
}
@@ -62,10 +62,10 @@ public Object[] getElements(Object inputElement) {
public Object[] getChildren(Object parentElement) {
if (!grouped)
return null;
-
+
if (parentElement instanceof Term) {
Term t = (Term) parentElement;
- return t.getAllSubTerms ();
+ return t.getAllSubTerms();
}
return null;
}
@@ -83,7 +83,7 @@ public Object getParent(Object element) {
public boolean hasChildren(Object element) {
if (!grouped)
return false;
-
+
if (element instanceof Term) {
Term t = (Term) element;
return t.hasChildTerms();
@@ -91,17 +91,17 @@ public boolean hasChildren(Object element) {
return false;
}
- public List<Term> getAllElements (List<Term> terms) {
+ public List<Term> getAllElements(List<Term> terms) {
List<Term> allTerms = new ArrayList<Term>();
-
+
if (terms != null) {
for (Term term : terms) {
allTerms.add(term);
allTerms.addAll(getAllElements(term.subTerms));
}
}
-
+
return allTerms;
}
-
+
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
index c021994b..9c4e6551 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
@@ -36,30 +36,33 @@
import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
public class GlossaryLabelProvider extends StyledCellLabelProvider implements
- ISelectionListener, ISelectionChangedListener {
+ 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 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);
-
+ /*** 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) {
+ public GlossaryLabelProvider(int referenceColumn,
+ List<String> translations, IWorkbenchPage page) {
this.referenceColumn = referenceColumn;
this.translations = translations;
if (page.getActiveEditor() != null) {
@@ -71,7 +74,8 @@ public String getColumnText(Object element, int columnIndex) {
try {
Term term = (Term) element;
if (term != null) {
- Translation transl = term.getTranslation(this.translations.get(columnIndex));
+ Translation transl = term.getTranslation(this.translations
+ .get(columnIndex));
return transl != null ? transl.value : "";
}
} catch (Exception e) {
@@ -80,61 +84,68 @@ public String getColumnText(Object element, int columnIndex) {
return "";
}
- public boolean isSearchEnabled () {
+ public boolean isSearchEnabled() {
return this.searchEnabled;
}
-
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
+
+ protected boolean isMatchingToPattern(Object element, int columnIndex) {
boolean matching = false;
-
+
if (element instanceof Term) {
Term term = (Term) element;
-
+
if (term.getInfo() == null)
return false;
-
+
FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- matching = filterInfo.hasFoundInTranslation(translations.get(columnIndex));
+
+ matching = filterInfo.hasFoundInTranslation(translations
+ .get(columnIndex));
}
-
+
return matching;
}
-
+
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
int columnIndex = cell.getColumnIndex();
cell.setText(this.getColumnText(element, columnIndex));
-
+
if (isCrossRefRegion(cell.getText())) {
- cell.setFont (bold);
+ cell.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) ) {
+ 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));
+ 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()]));
+
+ cell.setStyleRanges(styleRanges
+ .toArray(new StyleRange[styleRanges.size()]));
} else {
cell.setForeground(gray);
}
- }
+ }
}
private boolean isCrossRefRegion(String cellText) {
if (selectedItem != null) {
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
+ for (IMessage entry : selectedItem.getMessagesBundleGroup()
+ .getMessages(selectedItem.getMessageKey())) {
String value = entry.getValue();
String[] subValues = value.split("[\\s\\p{Punct}]+");
for (String v : subValues) {
@@ -143,7 +154,7 @@ private boolean isCrossRefRegion(String cellText) {
}
}
}
-
+
return false;
}
@@ -159,10 +170,10 @@ 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();
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 c92e7d9a..30e603f0 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
@@ -18,22 +18,19 @@
import org.eclipselabs.tapiji.translator.model.Term;
import org.eclipselabs.tapiji.translator.model.Translation;
-
public class GlossaryEntrySorter extends ViewerSorter {
- private StructuredViewer viewer;
- private SortInfo sortInfo;
- private int referenceCol;
- private List<String> translations;
-
- public GlossaryEntrySorter (StructuredViewer viewer,
- SortInfo sortInfo,
- int referenceCol,
- List<String> translations) {
+ 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
@@ -63,33 +60,38 @@ public int compare(Viewer viewer, Object e1, Object e2) {
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));
+ 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));
-
+ 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 125018c5..1118283e 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
@@ -15,13 +15,12 @@
import org.eclipse.ui.IMemento;
-
public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
+
+ 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;
@@ -50,13 +49,13 @@ public List<Locale> getVisibleLocales() {
return visibleLocales;
}
- public void saveState (IMemento memento) {
+ 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) {
+
+ public void init(IMemento memento) {
IMemento mCI = memento.getChild(TAG_SORT_INFO);
if (mCI == null)
return;
|
8138205feb185e74592b9fd6d0da9b7b7272589d
|
Vala
|
glib-2.0: add g_qsort_with_data binding
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi
index 0f21224af2..54d27c445a 100644
--- a/vapi/glib-2.0.vapi
+++ b/vapi/glib-2.0.vapi
@@ -3981,4 +3981,7 @@ namespace GLib {
public static bool unlikely (bool expression);
[CCode (cname = "G_STATIC_ASSERT", cheader_filename = "glib.h")]
public static void static_assert (bool expression);
+
+ [CCode (simple_generics = true)]
+ private static void qsort_with_data<T> (T[] elems, size_t size, [CCode (type = "GCompareDataFunc")] GLib.CompareDataFunc compare_func);
}
|
2b47c1528690b6413060401b254c79a9dc89ce85
|
hbase
|
HBASE-1192 LRU-style map for the block cache--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@780527 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index e2229652313d..4ac7b2f70d94 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -293,6 +293,8 @@ Release 0.20.0 - Unreleased
(Lars George and Alex Newman via Stack)
HBASE-1455 Update DemoClient.py for thrift 1.0 (Tim Sell via Stack)
HBASE-1464 Add hbase.regionserver.logroll.period to hbase-default
+ HBASE-1192 LRU-style map for the block cache (Jon Gray and Ryan Rawson
+ via Stack)
OPTIMIZATIONS
HBASE-1412 Change values for delete column and column family in KeyValue
diff --git a/conf/hbase-default.xml b/conf/hbase-default.xml
index a3a15b158535..f75d1d5d63c0 100644
--- a/conf/hbase-default.xml
+++ b/conf/hbase-default.xml
@@ -394,4 +394,11 @@
mode flag is stored at /hbase/safe-mode.
</description>
</property>
+ <property>
+ <name>hfile.block.cache.size</name>
+ <value>50000000</value>
+ <description>
+ The size of the block cache used by HFile/StoreFile. Set to 0 to disable.
+ </description>
+ </property>
</configuration>
diff --git a/src/java/org/apache/hadoop/hbase/io/HeapSize.java b/src/java/org/apache/hadoop/hbase/io/HeapSize.java
index 13858e91ed44..e6f59e54bd23 100644
--- a/src/java/org/apache/hadoop/hbase/io/HeapSize.java
+++ b/src/java/org/apache/hadoop/hbase/io/HeapSize.java
@@ -55,7 +55,7 @@ public interface HeapSize {
static final int BLOCK_SIZE_TAX = 8;
-
+ static final int BYTE_BUFFER = 56;
/**
* @return Approximate 'exclusive deep size' of implementing object. Includes
diff --git a/src/java/org/apache/hadoop/hbase/io/hfile/HFile.java b/src/java/org/apache/hadoop/hbase/io/hfile/HFile.java
index 05c8dfdf27a9..58f6cf9b6ee3 100644
--- a/src/java/org/apache/hadoop/hbase/io/hfile/HFile.java
+++ b/src/java/org/apache/hadoop/hbase/io/hfile/HFile.java
@@ -526,6 +526,10 @@ private void checkValue(final byte [] value,
}
}
+ public long getTotalBytes() {
+ return this.totalBytes;
+ }
+
public void close() throws IOException {
if (this.outputStream == null) {
return;
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java
index 8b2342cdb324..d3fbb81e95c1 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java
@@ -76,7 +76,7 @@
*
* <p>We maintain multiple HStores for a single HRegion.
*
- * <p>An HStore is a set of rows with some column data; together,
+ * <p>An Store is a set of rows with some column data; together,
* they make up all the data for the rows.
*
* <p>Each HRegion has a 'startKey' and 'endKey'.
@@ -96,9 +96,9 @@
*
* <p>An HRegion is defined by its table and its key extent.
*
- * <p>It consists of at least one HStore. The number of HStores should be
+ * <p>It consists of at least one Store. The number of Stores should be
* configurable, so that data which is accessed together is stored in the same
- * HStore. Right now, we approximate that by building a single HStore for
+ * Store. Right now, we approximate that by building a single Store for
* each column family. (This config info will be communicated via the
* tabledesc.)
*
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index b08e56d14477..c77dd577bbda 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -86,6 +86,7 @@
import org.apache.hadoop.hbase.io.Cell;
import org.apache.hadoop.hbase.io.HbaseMapWritable;
import org.apache.hadoop.hbase.io.RowResult;
+import org.apache.hadoop.hbase.io.hfile.LruBlockCache;
import org.apache.hadoop.hbase.ipc.HBaseRPC;
import org.apache.hadoop.hbase.ipc.HBaseRPCErrorHandler;
import org.apache.hadoop.hbase.ipc.HBaseRPCProtocolVersion;
@@ -1093,6 +1094,16 @@ protected void doMetrics() {
this.metrics.storefiles.set(storefiles);
this.metrics.memcacheSizeMB.set((int)(memcacheSize/(1024*1024)));
this.metrics.storefileIndexSizeMB.set((int)(storefileIndexSize/(1024*1024)));
+
+ LruBlockCache lruBlockCache = (LruBlockCache)StoreFile.getBlockCache(conf);
+ if (lruBlockCache != null) {
+ this.metrics.blockCacheCount.set(lruBlockCache.size());
+ this.metrics.blockCacheFree.set(lruBlockCache.getMemFree());
+ this.metrics.blockCacheSize.set(lruBlockCache.getMemUsed());
+ double ratio = lruBlockCache.getHitRatio();
+ int percent = (int) (ratio * 100);
+ this.metrics.blockCacheHitRatio.set(percent);
+ }
}
/**
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/Store.java b/src/java/org/apache/hadoop/hbase/regionserver/Store.java
index 6d1ad7828cff..a9166861d0c9 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/Store.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/Store.java
@@ -358,7 +358,7 @@ private Map<Long, StoreFile> loadStoreFiles()
}
StoreFile curfile = null;
try {
- curfile = new StoreFile(fs, p);
+ curfile = new StoreFile(fs, p, this.conf);
} catch (IOException ioe) {
LOG.warn("Failed open of " + p + "; presumption is that file was " +
"corrupted at flush and lost edits picked up by commit log replay. " +
@@ -499,7 +499,7 @@ private StoreFile internalFlushCache(final ConcurrentSkipListSet<KeyValue> cache
writer.close();
}
}
- StoreFile sf = new StoreFile(this.fs, writer.getPath());
+ StoreFile sf = new StoreFile(this.fs, writer.getPath(), this.conf);
this.storeSize += sf.getReader().length();
if(LOG.isDebugEnabled()) {
LOG.debug("Added " + sf + ", entries=" + sf.getReader().getEntries() +
@@ -962,7 +962,7 @@ private void completeCompaction(final List<StoreFile> compactedFiles,
LOG.error("Failed move of compacted file " + compactedFile.getPath(), e);
return;
}
- StoreFile finalCompactedFile = new StoreFile(this.fs, p);
+ StoreFile finalCompactedFile = new StoreFile(this.fs, p, this.conf);
this.lock.writeLock().lock();
try {
try {
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/StoreFile.java b/src/java/org/apache/hadoop/hbase/regionserver/StoreFile.java
index 038bb7dda538..7940c0cc1a71 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/StoreFile.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/StoreFile.java
@@ -33,12 +33,17 @@
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.io.HalfHFileReader;
import org.apache.hadoop.hbase.io.Reference;
import org.apache.hadoop.hbase.io.hfile.BlockCache;
import org.apache.hadoop.hbase.io.hfile.Compression;
import org.apache.hadoop.hbase.io.hfile.HFile;
+import org.apache.hadoop.hbase.io.hfile.LruBlockCache;
+import org.apache.hadoop.hbase.io.hfile.Compression.Algorithm;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.Hash;
+import org.apache.hadoop.io.RawComparator;
/**
* A Store data file. Stores usually have one or more of these files. They
@@ -52,6 +57,10 @@
*/
public class StoreFile implements HConstants {
static final Log LOG = LogFactory.getLog(StoreFile.class.getName());
+
+ public static final String HFILE_CACHE_SIZE_KEY = "hfile.block.cache.size";
+
+ private static BlockCache hfileBlockCache = null;
// Make default block size for StoreFiles 8k while testing. TODO: FIX!
// Need to make it 8k for testing.
@@ -88,16 +97,18 @@ public class StoreFile implements HConstants {
// Used making file ids.
private final static Random rand = new Random();
+ private final HBaseConfiguration conf;
/**
- * Constructor.
- * Loads up a Reader (and its indices, etc.).
- * @param fs Filesystem.
- * @param p qualified path
+ * Constructor, loads a reader and it's indices, etc. May allocate a substantial
+ * amount of ram depending on the underlying files (10-20MB?).
+ * @param fs
+ * @param p
+ * @param conf
* @throws IOException
*/
- StoreFile(final FileSystem fs, final Path p)
- throws IOException {
+ StoreFile(final FileSystem fs, final Path p, final HBaseConfiguration conf) throws IOException {
+ this.conf = conf;
this.fs = fs;
this.path = p;
if (isReference(p)) {
@@ -105,6 +116,7 @@ public class StoreFile implements HConstants {
this.referencePath = getReferredToFile(this.path);
}
this.reader = open();
+
}
/**
@@ -196,6 +208,23 @@ public long getMaxSequenceId() {
return this.sequenceid;
}
+ public static synchronized BlockCache getBlockCache(HBaseConfiguration conf) {
+ if (hfileBlockCache != null)
+ return hfileBlockCache;
+
+ long cacheSize = conf.getLong(HFILE_CACHE_SIZE_KEY, 0L);
+ // There should be a better way to optimize this. But oh well.
+ if (cacheSize == 0L)
+ return null;
+
+ hfileBlockCache = new LruBlockCache(cacheSize);
+ return hfileBlockCache;
+ }
+
+ public BlockCache getBlockCache() {
+ return getBlockCache(conf);
+ }
+
/**
* Opens reader on this store file. Called by Constructor.
* @return Reader for the store file.
@@ -208,10 +237,10 @@ protected HFile.Reader open()
throw new IllegalAccessError("Already open");
}
if (isReference()) {
- this.reader = new HalfHFileReader(this.fs, this.referencePath, null,
+ this.reader = new HalfHFileReader(this.fs, this.referencePath, getBlockCache(),
this.reference);
} else {
- this.reader = new StoreFileReader(this.fs, this.path, null);
+ this.reader = new StoreFileReader(this.fs, this.path, getBlockCache());
}
// Load up indices and fileinfo.
Map<byte [], byte []> map = this.reader.loadFileInfo();
@@ -368,13 +397,13 @@ public static HFile.Writer getWriter(final FileSystem fs, final Path dir)
* @param blocksize
* @param algorithm Pass null to get default.
* @param c Pass null to get default.
- * @param bloomfilter
+ * @param filter BloomFilter
* @return HFile.Writer
* @throws IOException
*/
public static HFile.Writer getWriter(final FileSystem fs, final Path dir,
final int blocksize, final Compression.Algorithm algorithm,
- final KeyValue.KeyComparator c, final boolean bloomfilter)
+ final KeyValue.KeyComparator c, final boolean filter)
throws IOException {
if (!fs.exists(dir)) {
fs.mkdirs(dir);
@@ -382,7 +411,7 @@ public static HFile.Writer getWriter(final FileSystem fs, final Path dir,
Path path = getUniqueFile(fs, dir);
return new HFile.Writer(fs, path, blocksize,
algorithm == null? HFile.DEFAULT_COMPRESSION_ALGORITHM: algorithm,
- c == null? KeyValue.KEY_COMPARATOR: c, bloomfilter);
+ c == null? KeyValue.KEY_COMPARATOR: c, filter);
}
/**
@@ -399,10 +428,9 @@ static Path getUniqueFile(final FileSystem fs, final Path p)
}
/**
+ *
* @param fs
* @param dir
- * @param encodedRegionName
- * @param family
* @return Path to a file that doesn't exist at time of this invocation.
* @throws IOException
*/
@@ -412,12 +440,12 @@ static Path getRandomFilename(final FileSystem fs, final Path dir)
}
/**
+ *
* @param fs
* @param dir
- * @param encodedRegionName
- * @param family
* @param suffix
* @return Path to a file that doesn't exist at time of this invocation.
+ * @return
* @throws IOException
*/
static Path getRandomFilename(final FileSystem fs, final Path dir,
@@ -437,8 +465,8 @@ static Path getRandomFilename(final FileSystem fs, final Path dir,
* Write file metadata.
* Call before you call close on the passed <code>w</code> since its written
* as metadata to that file.
- *
- * @param filesystem file system
+ *
+ * @param w
* @param maxSequenceId Maximum sequence id.
* @throws IOException
*/
@@ -488,4 +516,4 @@ static Path split(final FileSystem fs, final Path splitDir,
Path p = new Path(splitDir, f.getPath().getName() + "." + parentRegionName);
return r.write(fs, p);
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java b/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java
index 3c79ef169a07..2a723efb57f0 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java
@@ -49,7 +49,7 @@ public class RegionServerMetrics implements Updater {
private MetricsRegistry registry = new MetricsRegistry();
public final MetricsTimeVaryingRate atomicIncrementTime =
- new MetricsTimeVaryingRate("atomicIncrementTime", registry);
+ new MetricsTimeVaryingRate("atomicIncrementTime", registry);
/**
* Count of regions carried by this regionserver
@@ -57,10 +57,30 @@ public class RegionServerMetrics implements Updater {
public final MetricsIntValue regions =
new MetricsIntValue("regions", registry);
+ /**
+ * Block cache size.
+ */
+ public final MetricsLongValue blockCacheSize = new MetricsLongValue("blockCacheSize", registry);
+
+ /**
+ * Block cache free size.
+ */
+ public final MetricsLongValue blockCacheFree = new MetricsLongValue("blockCacheFree", registry);
+
+ /**
+ * Block cache item count.
+ */
+ public final MetricsLongValue blockCacheCount = new MetricsLongValue("blockCacheCount", registry);
+
+ /**
+ * Block hit ratio.
+ */
+ public final MetricsIntValue blockCacheHitRatio = new MetricsIntValue("blockCacheHitRatio", registry);
+
/*
* Count of requests to the regionservers since last call to metrics update
*/
- private final MetricsRate requests = new MetricsRate("requests");
+ private final MetricsRate requests = new MetricsRate("requests");
/**
* Count of stores open on the regionserver.
@@ -112,6 +132,11 @@ public void doUpdates(MetricsContext unused) {
this.memcacheSizeMB.pushMetric(this.metricsRecord);
this.regions.pushMetric(this.metricsRecord);
this.requests.pushMetric(this.metricsRecord);
+
+ this.blockCacheSize.pushMetric(this.metricsRecord);
+ this.blockCacheFree.pushMetric(this.metricsRecord);
+ this.blockCacheCount.pushMetric(this.metricsRecord);
+ this.blockCacheHitRatio.pushMetric(this.metricsRecord);
}
this.metricsRecord.update();
this.lastUpdate = System.currentTimeMillis();
@@ -162,6 +187,14 @@ public String toString() {
Long.valueOf(memory.getUsed()/MB));
sb = Strings.appendKeyValue(sb, "maxHeap",
Long.valueOf(memory.getMax()/MB));
+ sb = Strings.appendKeyValue(sb, this.blockCacheSize.getName(),
+ Long.valueOf(this.blockCacheSize.get()));
+ sb = Strings.appendKeyValue(sb, this.blockCacheFree.getName(),
+ Long.valueOf(this.blockCacheFree.get()));
+ sb = Strings.appendKeyValue(sb, this.blockCacheCount.getName(),
+ Long.valueOf(this.blockCacheCount.get()));
+ sb = Strings.appendKeyValue(sb, this.blockCacheHitRatio.getName(),
+ Long.valueOf(this.blockCacheHitRatio.get()));
return sb.toString();
}
}
diff --git a/src/test/org/apache/hadoop/hbase/regionserver/TestStoreFile.java b/src/test/org/apache/hadoop/hbase/regionserver/TestStoreFile.java
index 58b390e438cc..9f6601bcd3c5 100644
--- a/src/test/org/apache/hadoop/hbase/regionserver/TestStoreFile.java
+++ b/src/test/org/apache/hadoop/hbase/regionserver/TestStoreFile.java
@@ -73,7 +73,7 @@ public void testBasicHalfMapFile() throws Exception {
new Path(new Path(this.testDir, "regionname"), "familyname"),
2 * 1024, null, null, false);
writeStoreFile(writer);
- checkHalfHFile(new StoreFile(this.fs, writer.getPath()));
+ checkHalfHFile(new StoreFile(this.fs, writer.getPath(), conf));
}
/*
@@ -112,7 +112,7 @@ public void testReference()
HFile.Writer writer = StoreFile.getWriter(this.fs, dir, 8 * 1024, null,
null, false);
writeStoreFile(writer);
- StoreFile hsf = new StoreFile(this.fs, writer.getPath());
+ StoreFile hsf = new StoreFile(this.fs, writer.getPath(), conf);
HFile.Reader reader = hsf.getReader();
// Split on a row, not in middle of row. Midkey returned by reader
// may be in middle of row. Create new one with empty column and
@@ -123,7 +123,7 @@ public void testReference()
byte [] finalKey = hsk.getRow();
// Make a reference
Path refPath = StoreFile.split(fs, dir, hsf, reader.midkey(), Range.top);
- StoreFile refHsf = new StoreFile(this.fs, refPath);
+ StoreFile refHsf = new StoreFile(this.fs, refPath, conf);
// Now confirm that I can read from the reference and that it only gets
// keys from top half of the file.
HFileScanner s = refHsf.getReader().getScanner();
@@ -157,8 +157,8 @@ private void checkHalfHFile(final StoreFile f)
Path bottomPath = StoreFile.split(this.fs, bottomDir,
f, midkey, Range.bottom);
// Make readers on top and bottom.
- HFile.Reader top = new StoreFile(this.fs, topPath).getReader();
- HFile.Reader bottom = new StoreFile(this.fs, bottomPath).getReader();
+ HFile.Reader top = new StoreFile(this.fs, topPath, conf).getReader();
+ HFile.Reader bottom = new StoreFile(this.fs, bottomPath, conf).getReader();
ByteBuffer previous = null;
LOG.info("Midkey: " + Bytes.toString(midkey));
byte [] midkeyBytes = new HStoreKey(midkey).getBytes();
@@ -211,8 +211,8 @@ private void checkHalfHFile(final StoreFile f)
topPath = StoreFile.split(this.fs, topDir, f, badmidkey, Range.top);
bottomPath = StoreFile.split(this.fs, bottomDir, f, badmidkey,
Range.bottom);
- top = new StoreFile(this.fs, topPath).getReader();
- bottom = new StoreFile(this.fs, bottomPath).getReader();
+ top = new StoreFile(this.fs, topPath, conf).getReader();
+ bottom = new StoreFile(this.fs, bottomPath, conf).getReader();
bottomScanner = bottom.getScanner();
int count = 0;
while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) ||
@@ -255,8 +255,8 @@ private void checkHalfHFile(final StoreFile f)
topPath = StoreFile.split(this.fs, topDir, f, badmidkey, Range.top);
bottomPath = StoreFile.split(this.fs, bottomDir, f, badmidkey,
Range.bottom);
- top = new StoreFile(this.fs, topPath).getReader();
- bottom = new StoreFile(this.fs, bottomPath).getReader();
+ top = new StoreFile(this.fs, topPath, conf).getReader();
+ bottom = new StoreFile(this.fs, bottomPath, conf).getReader();
first = true;
bottomScanner = bottom.getScanner();
while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) ||
|
f0a32dff9b9cf53707758226f6598ab32cca6b06
|
hbase
|
HBASE-11370 SSH doesn't need to scan meta if not- using ZK for assignment--
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java
index 87433d3006f0..66edd66dd601 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java
@@ -458,10 +458,10 @@ void joinCluster() throws IOException,
// need to be handled.
// Scan hbase:meta to build list of existing regions, servers, and assignment
- // Returns servers who have not checked in (assumed dead) and their regions
- Map<ServerName, List<HRegionInfo>> deadServers;
+ // Returns servers who have not checked in (assumed dead) that some regions
+ // were assigned to (according to the meta)
+ Set<ServerName> deadServers = rebuildUserRegions();
- deadServers = rebuildUserRegions();
// This method will assign all user regions if a clean server startup or
// it will reconstruct master state and cleanup any leftovers from
// previous master process.
@@ -489,8 +489,8 @@ void joinCluster() throws IOException,
* @throws InterruptedException
*/
boolean processDeadServersAndRegionsInTransition(
- final Map<ServerName, List<HRegionInfo>> deadServers)
- throws KeeperException, IOException, InterruptedException, CoordinatedStateException {
+ final Set<ServerName> deadServers) throws KeeperException,
+ IOException, InterruptedException, CoordinatedStateException {
List<String> nodes = ZKUtil.listChildrenNoWatch(watcher,
watcher.assignmentZNode);
@@ -2702,13 +2702,12 @@ boolean waitUntilNoRegionsInTransition(final long timeout)
/**
* Rebuild the list of user regions and assignment information.
* <p>
- * Returns a map of servers that are not found to be online and the regions
- * they were hosting.
- * @return map of servers not online to their assigned regions, as stored
- * in META
+ * Returns a set of servers that are not found to be online that hosted
+ * some regions.
+ * @return set of servers not online that hosted some regions per meta
* @throws IOException
*/
- Map<ServerName, List<HRegionInfo>> rebuildUserRegions() throws
+ Set<ServerName> rebuildUserRegions() throws
IOException, KeeperException, CoordinatedStateException {
Set<TableName> disabledOrEnablingTables = tableStateManager.getTablesInStates(
ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.ENABLING);
@@ -2722,16 +2721,16 @@ Map<ServerName, List<HRegionInfo>> rebuildUserRegions() throws
List<Result> results = MetaReader.fullScan(this.catalogTracker);
// Get any new but slow to checkin region server that joined the cluster
Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
- // Map of offline servers and their regions to be returned
- Map<ServerName, List<HRegionInfo>> offlineServers =
- new TreeMap<ServerName, List<HRegionInfo>>();
+ // Set of offline servers to be returned
+ Set<ServerName> offlineServers = new HashSet<ServerName>();
// Iterate regions in META
for (Result result : results) {
HRegionInfo regionInfo = HRegionInfo.getHRegionInfo(result);
if (regionInfo == null) continue;
State state = RegionStateStore.getRegionState(result);
+ ServerName lastHost = HRegionInfo.getServerName(result);
ServerName regionLocation = RegionStateStore.getRegionServer(result);
- regionStates.createRegionState(regionInfo, state, regionLocation);
+ regionStates.createRegionState(regionInfo, state, regionLocation, lastHost);
if (!regionStates.isRegionInState(regionInfo, State.OPEN)) {
// Region is not open (either offline or in transition), skip
continue;
@@ -2739,13 +2738,10 @@ Map<ServerName, List<HRegionInfo>> rebuildUserRegions() throws
TableName tableName = regionInfo.getTable();
if (!onlineServers.contains(regionLocation)) {
// Region is located on a server that isn't online
- List<HRegionInfo> offlineRegions = offlineServers.get(regionLocation);
- if (offlineRegions == null) {
- offlineRegions = new ArrayList<HRegionInfo>(1);
- offlineServers.put(regionLocation, offlineRegions);
+ offlineServers.add(regionLocation);
+ if (useZKForAssignment) {
+ regionStates.regionOffline(regionInfo);
}
- regionStates.regionOffline(regionInfo);
- offlineRegions.add(regionInfo);
} else if (!disabledOrEnablingTables.contains(tableName)) {
// Region is being served and on an active server
// add only if region not in disabled or enabling table
@@ -2838,13 +2834,9 @@ private void recoverTableInEnablingState()
* @throws KeeperException
*/
private void processDeadServersAndRecoverLostRegions(
- Map<ServerName, List<HRegionInfo>> deadServers)
- throws IOException, KeeperException {
- if (deadServers != null) {
- for (Map.Entry<ServerName, List<HRegionInfo>> server: deadServers.entrySet()) {
- ServerName serverName = server.getKey();
- // We need to keep such info even if the server is known dead
- regionStates.setLastRegionServerOfRegions(serverName, server.getValue());
+ Set<ServerName> deadServers) throws IOException, KeeperException {
+ if (deadServers != null && !deadServers.isEmpty()) {
+ for (ServerName serverName: deadServers) {
if (!serverManager.isServerDead(serverName)) {
serverManager.expireServer(serverName); // Let SSH do region re-assign
}
@@ -3420,7 +3412,7 @@ private String onRegionSplit(ServerName sn, TransitionCode code,
}
} else if (code == TransitionCode.SPLIT_PONR) {
try {
- regionStateStore.splitRegion(p, a, b, sn);
+ regionStates.splitRegion(p, a, b, sn);
} catch (IOException ioe) {
LOG.info("Failed to record split region " + p.getShortNameToLog());
return "Failed to record the splitting in meta";
@@ -3469,7 +3461,7 @@ private String onRegionMerge(ServerName sn, TransitionCode code,
}
} else if (code == TransitionCode.MERGE_PONR) {
try {
- regionStateStore.mergeRegions(p, a, b, sn);
+ regionStates.mergeRegions(p, a, b, sn);
} catch (IOException ioe) {
LOG.info("Failed to record merged region " + p.getShortNameToLog());
return "Failed to record the merging in meta";
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java
index 153ffcbf4794..360996508179 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
-import java.util.NavigableMap;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -47,14 +46,11 @@
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.backup.HFileArchiver;
-import org.apache.hadoop.hbase.catalog.MetaReader;
-import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.fs.HFileSystem;
import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.wal.HLog;
-import org.apache.hadoop.hbase.regionserver.wal.HLogSplitter;
import org.apache.hadoop.hbase.regionserver.wal.HLogUtil;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
@@ -340,30 +336,6 @@ private List<Path> getLogDirs(final Set<ServerName> serverNames) throws IOExcept
return logDirs;
}
- /**
- * Mark regions in recovering state when distributedLogReplay are set true
- * @param serverNames Set of ServerNames to be replayed wals in order to recover changes contained
- * in them
- * @throws IOException
- */
- public void prepareLogReplay(Set<ServerName> serverNames) throws IOException {
- if (!this.distributedLogReplay) {
- return;
- }
- // mark regions in recovering state
- for (ServerName serverName : serverNames) {
- NavigableMap<HRegionInfo, Result> regions = this.getServerUserRegions(serverName);
- if (regions == null) {
- continue;
- }
- try {
- this.splitLogManager.markRegionsRecoveringInZK(serverName, regions.keySet());
- } catch (KeeperException e) {
- throw new IOException(e);
- }
- }
- }
-
/**
* Mark regions in recovering state when distributedLogReplay are set true
* @param serverName Failed region server whose wals to be replayed
@@ -675,19 +647,6 @@ public HTableDescriptor addColumn(TableName tableName, HColumnDescriptor hcd)
return htd;
}
- private NavigableMap<HRegionInfo, Result> getServerUserRegions(ServerName serverName)
- throws IOException {
- if (!this.master.isStopped()) {
- try {
- this.master.getCatalogTracker().waitForMeta();
- return MetaReader.getServerUserRegions(this.master.getCatalogTracker(), serverName);
- } catch (InterruptedException e) {
- throw (InterruptedIOException)new InterruptedIOException().initCause(e);
- }
- }
- return null;
- }
-
/**
* The function is used in SSH to set recovery mode based on configuration after all outstanding
* log split tasks drained.
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java
index 85677af8cbd6..fd75b3ffa976 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java
@@ -46,6 +46,7 @@
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.zookeeper.KeeperException;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
@@ -248,16 +249,22 @@ public void createRegionStates(
* no effect, and the original state is returned.
*/
public RegionState createRegionState(final HRegionInfo hri) {
- return createRegionState(hri, null, null);
+ return createRegionState(hri, null, null, null);
}
/**
* Add a region to RegionStates with the specified state.
* If the region is already in RegionStates, this call has
* no effect, and the original state is returned.
- */
- public synchronized RegionState createRegionState(
- final HRegionInfo hri, State newState, ServerName serverName) {
+ *
+ * @param hri the region info to create a state for
+ * @param newState the state to the region in set to
+ * @param serverName the server the region is transitioning on
+ * @param lastHost the last server that hosts the region
+ * @return the current state
+ */
+ public synchronized RegionState createRegionState(final HRegionInfo hri,
+ State newState, ServerName serverName, ServerName lastHost) {
if (newState == null || (newState == State.OPEN && serverName == null)) {
newState = State.OFFLINE;
}
@@ -274,16 +281,24 @@ public synchronized RegionState createRegionState(
regionState = new RegionState(hri, newState, serverName);
regionStates.put(encodedName, regionState);
if (newState == State.OPEN) {
- regionAssignments.put(hri, serverName);
- lastAssignments.put(encodedName, serverName);
- Set<HRegionInfo> regions = serverHoldings.get(serverName);
+ if (!serverName.equals(lastHost)) {
+ LOG.warn("Open region's last host " + lastHost
+ + " should be the same as the current one " + serverName
+ + ", ignored the last and used the current one");
+ lastHost = serverName;
+ }
+ lastAssignments.put(encodedName, lastHost);
+ regionAssignments.put(hri, lastHost);
+ } else if (!regionState.isUnassignable()) {
+ regionsInTransition.put(encodedName, regionState);
+ }
+ if (lastHost != null && newState != State.SPLIT) {
+ Set<HRegionInfo> regions = serverHoldings.get(lastHost);
if (regions == null) {
regions = new HashSet<HRegionInfo>();
- serverHoldings.put(serverName, regions);
+ serverHoldings.put(lastHost, regions);
}
regions.add(hri);
- } else if (!regionState.isUnassignable()) {
- regionsInTransition.put(encodedName, regionState);
}
}
return regionState;
@@ -590,6 +605,31 @@ public void tableDeleted(final TableName tableName) {
}
}
+ /**
+ * Get a copy of all regions assigned to a server
+ */
+ public synchronized Set<HRegionInfo> getServerRegions(ServerName serverName) {
+ Set<HRegionInfo> regions = serverHoldings.get(serverName);
+ if (regions == null) return null;
+ return new HashSet<HRegionInfo>(regions);
+ }
+
+ /**
+ * Remove a region from all state maps.
+ */
+ @VisibleForTesting
+ public synchronized void deleteRegion(final HRegionInfo hri) {
+ String encodedName = hri.getEncodedName();
+ regionsInTransition.remove(encodedName);
+ regionStates.remove(encodedName);
+ lastAssignments.remove(encodedName);
+ ServerName sn = regionAssignments.remove(hri);
+ if (sn != null) {
+ Set<HRegionInfo> regions = serverHoldings.get(sn);
+ regions.remove(hri);
+ }
+ }
+
/**
* Checking if a region was assigned to a server which is not online now.
* If so, we should hold re-assign this region till SSH has split its hlogs.
@@ -651,6 +691,38 @@ synchronized void setLastRegionServerOfRegion(
lastAssignments.put(encodedName, serverName);
}
+ void splitRegion(HRegionInfo p,
+ HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException {
+ regionStateStore.splitRegion(p, a, b, sn);
+ synchronized (this) {
+ // After PONR, split is considered to be done.
+ // Update server holdings to be aligned with the meta.
+ Set<HRegionInfo> regions = serverHoldings.get(sn);
+ if (regions == null) {
+ throw new IllegalStateException(sn + " should host some regions");
+ }
+ regions.remove(p);
+ regions.add(a);
+ regions.add(b);
+ }
+ }
+
+ void mergeRegions(HRegionInfo p,
+ HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException {
+ regionStateStore.mergeRegions(p, a, b, sn);
+ synchronized (this) {
+ // After PONR, merge is considered to be done.
+ // Update server holdings to be aligned with the meta.
+ Set<HRegionInfo> regions = serverHoldings.get(sn);
+ if (regions == null) {
+ throw new IllegalStateException(sn + " should host some regions");
+ }
+ regions.remove(a);
+ regions.remove(b);
+ regions.add(p);
+ }
+ }
+
/**
* At cluster clean re/start, mark all user regions closed except those of tables
* that are excluded, such as disabled/disabling/enabling tables. All user regions
@@ -661,8 +733,11 @@ synchronized Map<HRegionInfo, ServerName> closeAllUserRegions(Set<TableName> exc
Set<HRegionInfo> toBeClosed = new HashSet<HRegionInfo>(regionStates.size());
for(RegionState state: regionStates.values()) {
HRegionInfo hri = state.getRegion();
+ if (state.isSplit() || hri.isSplit()) {
+ continue;
+ }
TableName tableName = hri.getTable();
- if (!TableName.META_TABLE_NAME.equals(tableName) && !hri.isSplit()
+ if (!TableName.META_TABLE_NAME.equals(tableName)
&& (noExcludeTables || !excludedTables.contains(tableName))) {
toBeClosed.add(hri);
}
@@ -859,19 +934,4 @@ private RegionState updateRegionState(final HRegionInfo hri,
}
return regionState;
}
-
- /**
- * Remove a region from all state maps.
- */
- private synchronized void deleteRegion(final HRegionInfo hri) {
- String encodedName = hri.getEncodedName();
- regionsInTransition.remove(encodedName);
- regionStates.remove(encodedName);
- lastAssignments.remove(encodedName);
- ServerName sn = regionAssignments.remove(hri);
- if (sn != null) {
- Set<HRegionInfo> regions = serverHoldings.get(sn);
- regions.remove(hri);
- }
- }
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
index 50e09add5e66..70648e1c6cb3 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
@@ -46,6 +46,7 @@
import org.apache.hadoop.hbase.master.ServerManager;
import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
+import org.apache.hadoop.hbase.util.ConfigUtil;
import org.apache.hadoop.hbase.zookeeper.ZKAssign;
import org.apache.zookeeper.KeeperException;
@@ -162,8 +163,16 @@ public void process() throws IOException {
this.server.getCatalogTracker().waitForMeta();
// Skip getting user regions if the server is stopped.
if (!this.server.isStopped()) {
- hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
- this.serverName).keySet();
+ if (ConfigUtil.useZKForAssignment(server.getConfiguration())) {
+ hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
+ this.serverName).keySet();
+ } else {
+ // Not using ZK for assignment, regionStates has everything we want
+ hris = am.getRegionStates().getServerRegions(serverName);
+ if (hris != null) {
+ hris.remove(HRegionInfo.FIRST_META_REGIONINFO);
+ }
+ }
}
break;
} catch (InterruptedException e) {
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
index 10c23356e7cf..b4a780f6a44c 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
@@ -418,7 +418,7 @@ public void preSplitBeforePONR(ObserverContext<RegionCoprocessorEnvironment> ctx
AssignmentManager.TEST_SKIP_SPLIT_HANDLING = true;
// Now try splitting and it should work.
split(hri, server, regionCount);
- // Assert the ephemeral node is up in zk.
+
String path = ZKAssign.getNodeName(TESTING_UTIL.getZooKeeperWatcher(),
hri.getEncodedName());
RegionTransition rt = null;
@@ -437,7 +437,7 @@ public void preSplitBeforePONR(ObserverContext<RegionCoprocessorEnvironment> ctx
}
LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats=" + stats);
assertTrue(rt != null && rt.getEventType().equals(EventType.RS_ZK_REGION_SPLIT));
- // Now crash the server
+ // Now crash the server, for ZK-less assignment, the server is auto aborted
cluster.abortRegionServer(tableRegionIndex);
}
waitUntilRegionServerDead();
@@ -1329,12 +1329,12 @@ private void printOutRegions(final HRegionServer hrs, final String prefix)
private void waitUntilRegionServerDead() throws InterruptedException, InterruptedIOException {
// Wait until the master processes the RS shutdown
for (int i=0; cluster.getMaster().getClusterStatus().
- getServers().size() == NB_SERVERS && i<100; i++) {
+ getServers().size() > NB_SERVERS && i<100; i++) {
LOG.info("Waiting on server to go down");
Thread.sleep(100);
}
assertFalse("Waited too long for RS to die", cluster.getMaster().getClusterStatus().
- getServers().size() == NB_SERVERS);
+ getServers().size() > NB_SERVERS);
}
private void awaitDaughters(byte[] tableName, int numDaughters) throws InterruptedException {
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java
index 0a2e8fd4855a..bd0fbd3347a9 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java
@@ -1426,6 +1426,12 @@ public void testSplitDaughtersNotInMeta() throws Exception {
meta.delete(new Delete(daughters.getSecond().getRegionName()));
meta.flushCommits();
+ // Remove daughters from regionStates
+ RegionStates regionStates = TEST_UTIL.getMiniHBaseCluster().getMaster().
+ getAssignmentManager().getRegionStates();
+ regionStates.deleteRegion(daughters.getFirst());
+ regionStates.deleteRegion(daughters.getSecond());
+
HBaseFsck hbck = doFsck(conf, false);
assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN}); //no LINGERING_SPLIT_PARENT
|
6be295f78a3263f15b3f6e8b168727aa8a729269
|
Vala
|
Align gtk templates to new gtk+/glib api
Based on patch by ebassi.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valagtkmodule.vala b/codegen/valagtkmodule.vala
index b8c8f418ea..aaff2b5ea4 100644
--- a/codegen/valagtkmodule.vala
+++ b/codegen/valagtkmodule.vala
@@ -132,17 +132,45 @@ public class Vala.GtkModule : GSignalModule {
}
}
- private bool is_gtk_template (Class? cl) {
- return cl != null && gtk_widget_type != null && cl.is_subtype_of (gtk_widget_type) && cl.get_attribute ("GtkTemplate") != null;
+ private bool is_gtk_template (Class cl) {
+ var attr = cl.get_attribute ("GtkTemplate");
+ if (attr != null) {
+ if (gtk_widget_type == null || !cl.is_subtype_of (gtk_widget_type)) {
+ if (!cl.error) {
+ Report.error (attr.source_reference, "subclassing Gtk.Widget is required for using Gtk templates");
+ cl.error = true;
+ }
+ return false;
+ }
+ if (!context.require_glib_version (2, 38)) {
+ if (!cl.error) {
+ Report.error (attr.source_reference, "glib 2.38 is required for using Gtk templates (with --target-glib=2.38)");
+ cl.error = true;
+ }
+ return false;
+ }
+ return true;
+ }
+ return false;
}
public override void generate_class_init (Class cl) {
base.generate_class_init (cl);
- if (!is_gtk_template (cl)) {
+ if (cl.error || !is_gtk_template (cl)) {
return;
}
+ // this check is necessary because calling get_instance_private_offset otherwise will result in an error
+ if (cl.has_private_fields) {
+ var private_offset = "%s_private_offset".printf (get_ccode_name (cl));
+ ccode.add_declaration ("gint", new CCodeVariableDeclarator (private_offset));
+
+ var cgetprivcall = new CCodeFunctionCall (new CCodeIdentifier ("g_type_class_get_instance_private_offset"));
+ cgetprivcall.add_argument (new CCodeIdentifier ("klass"));
+ ccode.add_assignment (new CCodeIdentifier (private_offset), cgetprivcall);
+ }
+
/* Gtk builder widget template */
var ui = cl.get_attribute_string ("GtkTemplate", "ui");
if (ui == null) {
@@ -163,7 +191,7 @@ public class Vala.GtkModule : GSignalModule {
base.visit_field (f);
var cl = current_class;
- if (!is_gtk_template (cl) || cl.error) {
+ if (cl == null || cl.error || !is_gtk_template (cl)) {
return;
}
@@ -190,15 +218,21 @@ public class Vala.GtkModule : GSignalModule {
var internal_child = f.get_attribute_bool ("GtkChild", "internal");
- var offset = new CCodeFunctionCall (new CCodeIdentifier ("G_STRUCT_OFFSET"));
+ CCodeExpression offset;
if (f.is_private_symbol ()) {
- offset.add_argument (new CCodeIdentifier ("%sPrivate".printf (get_ccode_name (cl))));
+ // new glib api, we add the private struct offset to get the final field offset out of the instance
+ var private_field_offset = new CCodeFunctionCall (new CCodeIdentifier ("G_STRUCT_OFFSET"));
+ private_field_offset.add_argument (new CCodeIdentifier ("%sPrivate".printf (get_ccode_name (cl))));
+ private_field_offset.add_argument (new CCodeIdentifier (get_ccode_name (f)));
+ offset = new CCodeBinaryExpression (CCodeBinaryOperator.PLUS, new CCodeIdentifier ("%s_private_offset".printf (get_ccode_name (cl))), private_field_offset);
} else {
- offset.add_argument (new CCodeIdentifier (get_ccode_name (cl)));
+ var offset_call = new CCodeFunctionCall (new CCodeIdentifier ("G_STRUCT_OFFSET"));
+ offset_call.add_argument (new CCodeIdentifier (get_ccode_name (cl)));
+ offset_call.add_argument (new CCodeIdentifier (get_ccode_name (f)));
+ offset = offset_call;
}
- offset.add_argument (new CCodeIdentifier (get_ccode_name (f)));
- var call = new CCodeFunctionCall (new CCodeIdentifier ("gtk_widget_class_automate_child"));
+ var call = new CCodeFunctionCall (new CCodeIdentifier ("gtk_widget_class_bind_template_child_full"));
call.add_argument (new CCodeIdentifier ("GTK_WIDGET_CLASS (klass)"));
call.add_argument (new CCodeConstant ("\"%s\"".printf (gtk_name)));
call.add_argument (new CCodeConstant (internal_child ? "TRUE" : "FALSE"));
@@ -212,7 +246,7 @@ public class Vala.GtkModule : GSignalModule {
base.visit_method (m);
var cl = current_class;
- if (!is_gtk_template (cl) || cl.error) {
+ if (cl == null || cl.error || !is_gtk_template (cl)) {
return;
}
@@ -240,7 +274,7 @@ public class Vala.GtkModule : GSignalModule {
} else {
var wrapper = generate_delegate_wrapper (m, signal_type.get_handler_type (), m);
- var call = new CCodeFunctionCall (new CCodeIdentifier ("gtk_widget_class_declare_callback"));
+ var call = new CCodeFunctionCall (new CCodeIdentifier ("gtk_widget_class_bind_template_callback_full"));
call.add_argument (new CCodeIdentifier ("GTK_WIDGET_CLASS (klass)"));
call.add_argument (new CCodeConstant ("\"%s\"".printf (handler_name)));
call.add_argument (new CCodeIdentifier ("G_CALLBACK(%s)".printf (wrapper)));
@@ -253,7 +287,7 @@ public class Vala.GtkModule : GSignalModule {
public override void generate_instance_init (Class cl) {
- if (!is_gtk_template (cl)) {
+ if (cl == null || cl.error || !is_gtk_template (cl)) {
return;
}
|
d77c6eb30ee1f173c65bedabf25f138c9a4e50f2
|
kotlin
|
Exception fix: diagnose an error for a generic- type which is a subtype of itself
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
index 0daa6285114b3..0f6bb6582b50d 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
@@ -249,6 +249,8 @@ public interface Errors {
DiagnosticFactory0<JetDeclaration> TYPE_PARAMETERS_NOT_ALLOWED
= DiagnosticFactory0.create(ERROR, TYPE_PARAMETERS_OR_DECLARATION_SIGNATURE);
+ DiagnosticFactory0<PsiElement> CYCLIC_GENERIC_UPPER_BOUND = DiagnosticFactory0.create(ERROR);
+
// Members
DiagnosticFactory0<JetModifierListOwner> PACKAGE_MEMBER_CANNOT_BE_PROTECTED =
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
index 4272678d51f73..69c0bd405ffe6 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
@@ -421,6 +421,7 @@ public String render(@NotNull JetExpression expression) {
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(CYCLIC_GENERIC_UPPER_BOUND, "Type parameter has itself as an upper bound");
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 interfaces may serve as supertypes");
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
index 5e23f7bef6c82..6bbac29d8f4f3 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
@@ -28,6 +28,7 @@
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.*;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1;
+import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.lexer.JetKeywordToken;
import org.jetbrains.kotlin.lexer.JetModifierKeywordToken;
import org.jetbrains.kotlin.lexer.JetTokens;
@@ -476,6 +477,10 @@ public void resolveGenericBounds(
JetTypeReference extendsBound = jetTypeParameter.getExtendsBound();
if (extendsBound != null) {
JetType type = typeResolver.resolveType(scope, extendsBound, trace, false);
+ if (type.getConstructor().equals(typeParameterDescriptor.getTypeConstructor())) {
+ trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(extendsBound));
+ type = ErrorUtils.createErrorType("Cyclic upper bound: " + type);
+ }
typeParameterDescriptor.addUpperBound(type);
deferredUpperBoundCheckerTasks.add(new UpperBoundCheckerTask(extendsBound, type));
}
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt
new file mode 100644
index 0000000000000..7bc7846fc26bc
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt
@@ -0,0 +1,3 @@
+// !DIAGNOSTICS: -MUST_BE_INITIALIZED
+fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> foo() {}
+val <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> prop
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.txt
new file mode 100644
index 0000000000000..e9d759332ac62
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.txt
@@ -0,0 +1,4 @@
+package
+
+internal val </*0*/ T : [ERROR : Cyclic upper bound: T?]> prop: [ERROR : No type, no body]
+internal fun </*0*/ T : [ERROR : Cyclic upper bound: T?]> foo(): kotlin.Unit
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt
new file mode 100644
index 0000000000000..353988510c342
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt
@@ -0,0 +1,4 @@
+fun bar() {
+ fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> foo() {}
+ foo()
+}
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.txt
new file mode 100644
index 0000000000000..b015afc1ae045
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.txt
@@ -0,0 +1,3 @@
+package
+
+internal fun bar(): kotlin.Unit
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt
new file mode 100644
index 0000000000000..91cc9ac8fc22d
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt
@@ -0,0 +1,5 @@
+// !DIAGNOSTICS: -MUST_BE_INITIALIZED_OR_BE_ABSTRACT
+class My {
+ fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> foo() {}
+ val <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> prop: T
+}
\ No newline at end of file
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.txt
new file mode 100644
index 0000000000000..213f4fddd6446
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.txt
@@ -0,0 +1,10 @@
+package
+
+internal final class My {
+ public constructor My()
+ internal final val </*0*/ T : [ERROR : Cyclic upper bound: T?]> prop: [ERROR : ?]
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ internal final fun </*0*/ T : [ERROR : Cyclic upper bound: T?]> foo(): kotlin.Unit
+ 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/tests/regressions/itselfAsUpperBoundNotNull.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt
new file mode 100644
index 0000000000000..3700e3f423698
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt
@@ -0,0 +1,3 @@
+// !DIAGNOSTICS: -MUST_BE_INITIALIZED
+fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T<!>> foo() {}
+val <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> prop: T
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.txt
new file mode 100644
index 0000000000000..78109cf302724
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.txt
@@ -0,0 +1,4 @@
+package
+
+internal val </*0*/ T : [ERROR : Cyclic upper bound: T?]> prop: [ERROR : ?]
+internal fun </*0*/ T : [ERROR : Cyclic upper bound: T]> foo(): kotlin.Unit
diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
index 3d746285e0495..c3fba608824c5 100644
--- a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
@@ -10224,6 +10224,30 @@ public void testErrorsOnIbjectExpressionsAsParameters() throws Exception {
doTest(fileName);
}
+ @TestMetadata("itselfAsUpperBound.kt")
+ public void testItselfAsUpperBound() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("itselfAsUpperBoundLocal.kt")
+ public void testItselfAsUpperBoundLocal() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("itselfAsUpperBoundMember.kt")
+ public void testItselfAsUpperBoundMember() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("itselfAsUpperBoundNotNull.kt")
+ public void testItselfAsUpperBoundNotNull() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt");
+ doTest(fileName);
+ }
+
@TestMetadata("Jet11.kt")
public void testJet11() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/Jet11.kt");
|
1e971c6aa481b2794369ce66173ebeb77c08350a
|
intellij-community
|
intellilang avoid costly service lookups--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-api/src/com/intellij/lang/injection/InjectedLanguageManager.java b/platform/lang-api/src/com/intellij/lang/injection/InjectedLanguageManager.java
index bf742113bc9f7..9ba141ac9117a 100644
--- a/platform/lang-api/src/com/intellij/lang/injection/InjectedLanguageManager.java
+++ b/platform/lang-api/src/com/intellij/lang/injection/InjectedLanguageManager.java
@@ -26,6 +26,7 @@
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.NotNullLazyKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
@@ -41,8 +42,10 @@ public abstract class InjectedLanguageManager implements ProjectComponent {
@Deprecated
public static final ExtensionPointName<MultiHostInjector> MULTIHOST_INJECTOR_EP_NAME = MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME;
+ private final static NotNullLazyKey<InjectedLanguageManager, Project> INSTANCE_CACHE = ServiceManager.createLazyKey(InjectedLanguageManager.class);
+
public static InjectedLanguageManager getInstance(Project project) {
- return ServiceManager.getService(project, InjectedLanguageManager.class);
+ return INSTANCE_CACHE.getValue(project);
}
@Nullable
|
f1d1b3440b46c48146fde6b3b1c2cd65b51bdbfe
|
apache$mina
|
Modified IoAcceptor and IoConnector to accept IoServiceConfig as a configuration parameter for more flexibility
git-svn-id: https://svn.apache.org/repos/asf/directory/sandbox/trustin/dirmina-158@372453 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/mina
|
diff --git a/core/src/main/java/org/apache/mina/common/IoAcceptor.java b/core/src/main/java/org/apache/mina/common/IoAcceptor.java
index 05d0d1403..5a9179bec 100644
--- a/core/src/main/java/org/apache/mina/common/IoAcceptor.java
+++ b/core/src/main/java/org/apache/mina/common/IoAcceptor.java
@@ -57,7 +57,7 @@ public interface IoAcceptor extends IoService
* @param config the configuration
* @throws IOException if failed to bind
*/
- void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException;
+ void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException;
/**
* Unbinds from the specified <code>address</code> and disconnects all clients
diff --git a/core/src/main/java/org/apache/mina/common/IoConnector.java b/core/src/main/java/org/apache/mina/common/IoConnector.java
index fc74e9faa..715b66384 100644
--- a/core/src/main/java/org/apache/mina/common/IoConnector.java
+++ b/core/src/main/java/org/apache/mina/common/IoConnector.java
@@ -59,7 +59,7 @@ public interface IoConnector extends IoService
* @return {@link ConnectFuture} that will tell the result of the connection attempt
*/
ConnectFuture connect( SocketAddress address, IoHandler handler,
- IoConnectorConfig config );
+ IoServiceConfig config );
/**
* Connects to the specified <code>address</code>. If communication starts
@@ -81,5 +81,5 @@ ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
* @return {@link ConnectFuture} that will tell the result of the connection attempt
*/
ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
- IoHandler handler, IoConnectorConfig config );
+ IoHandler handler, IoServiceConfig config );
}
\ No newline at end of file
diff --git a/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java b/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java
index 73718dbfe..40510603f 100644
--- a/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java
+++ b/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java
@@ -22,7 +22,6 @@
import java.net.SocketAddress;
import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;
@@ -40,7 +39,7 @@ protected BaseIoAcceptor()
public void bind( SocketAddress address, IoHandler handler ) throws IOException
{
- this.bind( address, handler, ( IoAcceptorConfig ) getDefaultConfig() );
+ this.bind( address, handler, getDefaultConfig() );
}
public IoSession newSession( SocketAddress remoteAddress, SocketAddress localAddress )
diff --git a/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java b/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java
index b4927f2ea..721a6bd7a 100644
--- a/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java
+++ b/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java
@@ -22,7 +22,6 @@
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoConnectorConfig;
import org.apache.mina.common.IoHandler;
/**
@@ -39,11 +38,11 @@ protected BaseIoConnector()
public ConnectFuture connect( SocketAddress address, IoHandler handler )
{
- return connect( address, handler, ( IoConnectorConfig ) getDefaultConfig() );
+ return connect( address, handler, getDefaultConfig() );
}
public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler )
{
- return connect( address, localAddress, handler, ( IoConnectorConfig ) getDefaultConfig() );
+ return connect( address, localAddress, handler, getDefaultConfig() );
}
}
diff --git a/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java b/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java
index 46e974f86..194bfbf48 100644
--- a/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java
+++ b/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java
@@ -23,7 +23,6 @@
import java.util.Set;
import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.IoSession;
@@ -59,7 +58,7 @@ public void bind( SocketAddress address, IoHandler handler ) throws IOException
delegate.bind( address, handler );
}
- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException
+ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException
{
delegate.bind( address, handler, config );
}
diff --git a/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java b/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java
index 3b78ba962..74ac8d362 100644
--- a/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java
+++ b/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java
@@ -23,7 +23,6 @@
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoConnectorConfig;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoServiceConfig;
@@ -58,7 +57,7 @@ public ConnectFuture connect( SocketAddress address, IoHandler handler )
return delegate.connect( address, handler );
}
- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config )
+ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config )
{
return delegate.connect( address, handler, config );
}
@@ -70,7 +69,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
}
public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
- IoHandler handler, IoConnectorConfig config )
+ IoHandler handler, IoServiceConfig config )
{
return delegate.connect( address, localAddress, handler, config );
}
diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java
index be095e240..900b0ef4d 100644
--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java
+++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java
@@ -32,7 +32,6 @@
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ExceptionMonitor;
import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.IoSession;
@@ -70,7 +69,7 @@ public DatagramAcceptorDelegate( IoAcceptor wrapper )
this.wrapper = wrapper;
}
- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config )
+ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config )
throws IOException
{
if( address == null )
@@ -79,7 +78,7 @@ public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig con
throw new NullPointerException( "handler" );
if( config == null )
{
- config = ( IoAcceptorConfig ) getDefaultConfig();
+ config = getDefaultConfig();
}
if( !( address instanceof InetSocketAddress ) )
@@ -195,7 +194,7 @@ public IoSession newSession( SocketAddress remoteAddress, SocketAddress localAdd
RegistrationRequest req = ( RegistrationRequest ) key.attachment();
DatagramSessionImpl s = new DatagramSessionImpl(
wrapper, this,
- ( DatagramSessionConfig ) req.config, ch, req.handler );
+ req.config.getSessionConfig(), ch, req.handler );
s.setRemoteAddress( remoteAddress );
s.setSelectionKey( key );
@@ -329,7 +328,7 @@ private void processReadySessions( Set keys )
RegistrationRequest req = ( RegistrationRequest ) key.attachment();
DatagramSessionImpl session = new DatagramSessionImpl(
wrapper, this,
- ( DatagramSessionConfig ) req.config.getSessionConfig(),
+ req.config.getSessionConfig(),
ch, req.handler );
session.setSelectionKey( key );
@@ -615,12 +614,12 @@ private static class RegistrationRequest
{
private final SocketAddress address;
private final IoHandler handler;
- private final IoAcceptorConfig config;
+ private final IoServiceConfig config;
private Throwable exception;
private boolean done;
- private RegistrationRequest( SocketAddress address, IoHandler handler, IoAcceptorConfig config )
+ private RegistrationRequest( SocketAddress address, IoHandler handler, IoServiceConfig config )
{
this.address = address;
this.handler = handler;
diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java
index 5e59c2139..ee7babad4 100644
--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java
+++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java
@@ -31,7 +31,6 @@
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.ExceptionMonitor;
import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoConnectorConfig;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.IoFilter.WriteRequest;
@@ -68,13 +67,13 @@ public DatagramConnectorDelegate( IoConnector wrapper )
this.wrapper = wrapper;
}
- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config )
+ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config )
{
return connect( address, null, handler, config );
}
public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
- IoHandler handler, IoConnectorConfig config )
+ IoHandler handler, IoServiceConfig config )
{
if( address == null )
throw new NullPointerException( "address" );
@@ -93,7 +92,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
if( config == null )
{
- config = ( IoConnectorConfig ) getDefaultConfig();
+ config = getDefaultConfig();
}
DatagramChannel ch = null;
@@ -540,7 +539,7 @@ private void registerNew()
DatagramSessionImpl session = new DatagramSessionImpl(
wrapper, this,
- ( DatagramSessionConfig ) req.config.getSessionConfig(),
+ req.config.getSessionConfig(),
req.channel, req.handler );
boolean success = false;
@@ -618,11 +617,11 @@ private static class RegistrationRequest extends ConnectFuture
{
private final DatagramChannel channel;
private final IoHandler handler;
- private final IoConnectorConfig config;
+ private final IoServiceConfig config;
private RegistrationRequest( DatagramChannel channel,
IoHandler handler,
- IoConnectorConfig config )
+ IoServiceConfig config )
{
this.channel = channel;
this.handler = handler;
diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java
index 443f1f02f..19fa11cea 100644
--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java
+++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java
@@ -61,7 +61,7 @@ class DatagramSessionImpl extends BaseIoSession
*/
DatagramSessionImpl( IoService wrapperManager,
DatagramService managerDelegate,
- DatagramSessionConfig config,
+ IoSessionConfig config,
DatagramChannel ch, IoHandler defaultHandler )
{
this.wrapperManager = wrapperManager;
@@ -74,12 +74,16 @@ class DatagramSessionImpl extends BaseIoSession
this.localAddress = ch.socket().getLocalSocketAddress();
// Apply the initial session settings
- this.config.setBroadcast( config.isBroadcast() );
- this.config.setReceiveBufferSize( config.getReceiveBufferSize() );
- this.readBufferSize = config.getReceiveBufferSize();
- this.config.setReuseAddress( config.isReuseAddress() );
- this.config.setSendBufferSize( config.getSendBufferSize() );
- this.config.setTrafficClass( config.getTrafficClass() );
+ if( config instanceof DatagramSessionConfig )
+ {
+ DatagramSessionConfig cfg = ( DatagramSessionConfig ) config;
+ this.config.setBroadcast( cfg.isBroadcast() );
+ this.config.setReceiveBufferSize( cfg.getReceiveBufferSize() );
+ this.readBufferSize = cfg.getReceiveBufferSize();
+ this.config.setReuseAddress( cfg.isReuseAddress() );
+ this.config.setSendBufferSize( cfg.getSendBufferSize() );
+ this.config.setTrafficClass( cfg.getTrafficClass() );
+ }
}
public IoService getService()
diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java
index 45083b8af..6ff5f8f8b 100644
--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java
+++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java
@@ -85,7 +85,7 @@ public SocketAcceptorDelegate( IoAcceptor wrapper )
*
* @throws IOException if failed to bind
*/
- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException
+ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException
{
if( address == null )
{
@@ -109,7 +109,7 @@ public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig con
if( config == null )
{
- config = ( IoAcceptorConfig ) getDefaultConfig();
+ config = getDefaultConfig();
}
RegistrationRequest request = new RegistrationRequest( address, handler, config );
@@ -230,8 +230,18 @@ public void unbind( SocketAddress address )
// Disconnect all clients
- if( request.registrationRequest.config.isDisconnectOnUnbind() &&
- managedSessions != null )
+ IoServiceConfig cfg = request.registrationRequest.config;
+ boolean disconnectOnUnbind;
+ if( cfg instanceof IoAcceptorConfig )
+ {
+ disconnectOnUnbind = ( ( IoAcceptorConfig ) cfg ).isDisconnectOnUnbind();
+ }
+ else
+ {
+ disconnectOnUnbind = ( ( IoAcceptorConfig ) getDefaultConfig() ).isDisconnectOnUnbind();
+ }
+
+ if( disconnectOnUnbind && managedSessions != null )
{
IoSession[] tempSessions = ( IoSession[] )
managedSessions.toArray( new IoSession[ 0 ] );
@@ -543,11 +553,11 @@ private static class RegistrationRequest
{
private final SocketAddress address;
private final IoHandler handler;
- private final IoAcceptorConfig config;
+ private final IoServiceConfig config;
private IOException exception;
private boolean done;
- private RegistrationRequest( SocketAddress address, IoHandler handler, IoAcceptorConfig config )
+ private RegistrationRequest( SocketAddress address, IoHandler handler, IoServiceConfig config )
{
this.address = address;
this.handler = handler;
diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java
index e354329da..c680a0ce1 100644
--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java
+++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java
@@ -38,7 +38,6 @@
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.support.BaseIoConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
import org.apache.mina.util.Queue;
/**
@@ -68,13 +67,13 @@ public SocketConnectorDelegate( IoConnector wrapper )
this.wrapper = wrapper;
}
- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config )
+ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config )
{
return connect( address, null, handler, config );
}
public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
- IoHandler handler, IoConnectorConfig config )
+ IoHandler handler, IoServiceConfig config )
{
if( address == null )
throw new NullPointerException( "address" );
@@ -91,7 +90,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
if( config == null )
{
- config = ( IoConnectorConfig ) getDefaultConfig();
+ config = getDefaultConfig();
}
SocketChannel ch = null;
@@ -278,11 +277,11 @@ private void processTimedOutSessions( Set keys )
}
}
- private SocketSessionImpl newSession( SocketChannel ch, IoHandler handler, IoConnectorConfig config ) throws IOException
+ private SocketSessionImpl newSession( SocketChannel ch, IoHandler handler, IoServiceConfig config ) throws IOException
{
SocketSessionImpl session = new SocketSessionImpl(
wrapper, managedSessions,
- ( SocketSessionConfig ) config.getSessionConfig(),
+ config.getSessionConfig(),
ch, handler );
try
{
@@ -363,17 +362,26 @@ public void run()
}
}
- private static class ConnectionRequest extends ConnectFuture
+ private class ConnectionRequest extends ConnectFuture
{
private final SocketChannel channel;
private final long deadline;
private final IoHandler handler;
- private final IoConnectorConfig config;
+ private final IoServiceConfig config;
- private ConnectionRequest( SocketChannel channel, IoHandler handler, IoConnectorConfig config )
+ private ConnectionRequest( SocketChannel channel, IoHandler handler, IoServiceConfig config )
{
this.channel = channel;
- this.deadline = System.currentTimeMillis() + config.getConnectTimeoutMillis();
+ long timeout;
+ if( config instanceof IoConnectorConfig )
+ {
+ timeout = ( ( IoConnectorConfig ) config ).getConnectTimeoutMillis();
+ }
+ else
+ {
+ timeout = ( ( IoConnectorConfig ) getDefaultConfig() ).getConnectTimeoutMillis();
+ }
+ this.deadline = System.currentTimeMillis() + timeout;
this.handler = handler;
this.config = config;
}
diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java
index d0544b318..56cacfcec 100644
--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java
+++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java
@@ -63,7 +63,7 @@ class SocketSessionImpl extends BaseIoSession
*/
public SocketSessionImpl(
IoService manager, Set managedSessions,
- SocketSessionConfig config,
+ IoSessionConfig config,
SocketChannel ch, IoHandler defaultHandler )
{
this.manager = manager;
@@ -77,15 +77,19 @@ public SocketSessionImpl(
this.localAddress = ch.socket().getLocalSocketAddress();
// Apply the initial session settings
- this.config.setKeepAlive( config.isKeepAlive() );
- this.config.setOobInline( config.isOobInline() );
- this.config.setReceiveBufferSize( config.getReceiveBufferSize() );
- this.readBufferSize = config.getReceiveBufferSize();
- this.config.setReuseAddress( config.isReuseAddress() );
- this.config.setSendBufferSize( config.getSendBufferSize() );
- this.config.setSoLinger( config.getSoLinger() );
- this.config.setTcpNoDelay( config.isTcpNoDelay() );
- this.config.setTrafficClass( config.getTrafficClass() );
+ if( config instanceof SocketSessionConfig )
+ {
+ SocketSessionConfig cfg = ( SocketSessionConfig ) config;
+ this.config.setKeepAlive( cfg.isKeepAlive() );
+ this.config.setOobInline( cfg.isOobInline() );
+ this.config.setReceiveBufferSize( cfg.getReceiveBufferSize() );
+ this.readBufferSize = cfg.getReceiveBufferSize();
+ this.config.setReuseAddress( cfg.isReuseAddress() );
+ this.config.setSendBufferSize( cfg.getSendBufferSize() );
+ this.config.setSoLinger( cfg.getSoLinger() );
+ this.config.setTcpNoDelay( cfg.isTcpNoDelay() );
+ this.config.setTrafficClass( cfg.getTrafficClass() );
+ }
}
public IoService getService()
diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java
index 7d1378d7a..3ecb2cc9e 100644
--- a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java
+++ b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java
@@ -42,7 +42,7 @@ public IoSessionConfig getSessionConfig()
}
};
- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException
+ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException
{
if( address == null )
throw new NullPointerException( "address" );
@@ -54,7 +54,7 @@ public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig con
if( config == null )
{
- config = ( IoAcceptorConfig ) getDefaultConfig();
+ config = getDefaultConfig();
}
synchronized( boundHandlers )
@@ -109,7 +109,17 @@ public void unbind( SocketAddress address )
Set managedSessions = pipe.getManagedServerSessions();
- if( pipe.getConfig().isDisconnectOnUnbind() && managedSessions != null )
+ IoServiceConfig cfg = pipe.getConfig();
+ boolean disconnectOnUnbind;
+ if( cfg instanceof IoAcceptorConfig )
+ {
+ disconnectOnUnbind = ( ( IoAcceptorConfig ) cfg ).isDisconnectOnUnbind();
+ }
+ else
+ {
+ disconnectOnUnbind = ( ( IoAcceptorConfig ) getDefaultConfig() ).isDisconnectOnUnbind();
+ }
+ if( disconnectOnUnbind && managedSessions != null )
{
IoSession[] tempSessions = ( IoSession[] )
managedSessions.toArray( new IoSession[ 0 ] );
diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java
index 3151fc3b7..d9a304d75 100644
--- a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java
+++ b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java
@@ -7,7 +7,6 @@
import java.net.SocketAddress;
import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.IoConnectorConfig;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.IoSessionConfig;
@@ -35,12 +34,12 @@ public IoSessionConfig getSessionConfig()
}
};
- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config )
+ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config )
{
return connect( address, null, handler, config );
}
- public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler, IoConnectorConfig config )
+ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config )
{
if( address == null )
throw new NullPointerException( "address" );
@@ -52,7 +51,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress,
if( config == null )
{
- config = ( IoConnectorConfig ) getDefaultConfig();
+ config = getDefaultConfig();
}
VmPipe entry = ( VmPipe ) VmPipeAcceptor.boundHandlers.get( address );
diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java b/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java
index 7f9c57516..f767155f9 100644
--- a/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java
+++ b/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java
@@ -7,8 +7,8 @@
import java.util.HashSet;
import java.util.Set;
-import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.common.IoHandler;
+import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.transport.vmpipe.VmPipeAcceptor;
import org.apache.mina.transport.vmpipe.VmPipeAddress;
@@ -17,14 +17,14 @@ public class VmPipe
private final VmPipeAcceptor acceptor;
private final VmPipeAddress address;
private final IoHandler handler;
- private final IoAcceptorConfig config;
+ private final IoServiceConfig config;
private final Set managedClientSessions = Collections.synchronizedSet( new HashSet() );
private final Set managedServerSessions = Collections.synchronizedSet( new HashSet() );
public VmPipe( VmPipeAcceptor acceptor,
VmPipeAddress address,
IoHandler handler,
- IoAcceptorConfig config )
+ IoServiceConfig config )
{
this.acceptor = acceptor;
this.address = address;
@@ -47,7 +47,7 @@ public IoHandler getHandler()
return handler;
}
- public IoAcceptorConfig getConfig()
+ public IoServiceConfig getConfig()
{
return config;
}
|
99ce3f9040c54bac0ce93596f934aefc0eed171b
|
benoker$dockingframes
|
The DockableDisplayer has now more flexibility how to layout its Dockable and DockTitle. That should be helpful when writing a subclass.
git-svn-id: http://svn.javaforge.com/svn/DockingFrames/trunk@22 3428d308-0d2e-0410-b3d4-94d0fefcacdf
|
p
|
https://github.com/benoker/dockingframes
|
diff --git a/dockingFrames/src/bibliothek/gui/dock/DockableDisplayer.java b/dockingFrames/src/bibliothek/gui/dock/DockableDisplayer.java
index 15caebbc9..d76a267db 100644
--- a/dockingFrames/src/bibliothek/gui/dock/DockableDisplayer.java
+++ b/dockingFrames/src/bibliothek/gui/dock/DockableDisplayer.java
@@ -26,6 +26,8 @@
package bibliothek.gui.dock;
+import java.awt.Component;
+import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
@@ -42,7 +44,11 @@
* right, top, bottom). The title may be <code>null</code>, in this case only
* the Dockable is shown.<br>
* Clients using a displayer should try to set the {@link #setController(DockController) controller}
- * and the {@link #setStation(DockStation) station} property.
+ * and the {@link #setStation(DockStation) station} property.<br>
+ * Subclasses may override {@link #getComponent(Dockable)}, {@link #addDockable(Component)},
+ * {@link #removeDockable(Component)}, {@link #getComponent(DockTitle)}, {@link #addTitle(Component)}
+ * and/or {@link #removeTitle(Component)} if they want to introduce a completely
+ * new layout needing more {@link Container Containers}.
* @see DisplayerCollection
* @see DisplayerFactory
* @author Benjamin Sigg
@@ -155,11 +161,11 @@ public Dockable getDockable() {
*/
public void setDockable( Dockable dockable ) {
if( this.dockable != null )
- remove( this.dockable.getComponent() );
+ removeDockable( this.dockable.getComponent() );
this.dockable = dockable;
if( dockable != null )
- add( dockable.getComponent() );
+ addDockable( dockable.getComponent() );
invalidate();
}
@@ -223,15 +229,75 @@ public DockTitle getTitle() {
*/
public void setTitle( DockTitle title ) {
if( this.title != null )
- remove( this.title.getComponent() );
+ removeTitle( this.title.getComponent() );
this.title = title;
if( title != null ){
title.setOrientation( orientation( location ));
- add( title.getComponent() );
+ addTitle( title.getComponent() );
}
invalidate();
+ }
+
+ /**
+ * Inserts a component representing the current {@link #getDockable() dockable}
+ * into the layout. This method is never called twice unless
+ * {@link #removeDockable(Component)} is called before. Note that
+ * the name "add" is inspired by the method {@link Container#add(Component) add}
+ * of <code>Container</code>.
+ * @param component the new Component
+ */
+ protected void addDockable( Component component ){
+ add( component );
+ }
+
+ /**
+ * Removes the Component which represents the current {@link #getDockable() dockable}.
+ * @param component the component
+ */
+ protected void removeDockable( Component component ){
+ remove( component );
+ }
+
+ /**
+ * Gets the Component which should be used to layout the current
+ * Dockable.
+ * @param dockable the current Dockable, never <code>null</code>
+ * @return the component representing <code>dockable</code>
+ */
+ protected Component getComponent( Dockable dockable ){
+ return dockable.getComponent();
+ }
+
+ /**
+ * Inserts a component representing the current {@link #getTitle() title}
+ * into the layout. This method is never called twice unless
+ * {@link #removeTitle(Component)} is called before. Note that
+ * the name "add" is inspired by the method {@link Container#add(Component) add}
+ * of <code>Container</code>.
+ * @param component the new Component
+ */
+ protected void addTitle( Component component ){
+ add( component );
+ }
+
+ /**
+ * Removes the Component which represents the current {@link #getTitle() title}.
+ * @param component the component
+ */
+ protected void removeTitle( Component component ){
+ remove( component );
+ }
+
+ /**
+ * Gets the Component which should be used to layout the current
+ * DockTitle.
+ * @param title the current DockTitle, never <code>null</code>
+ * @return the component representing <code>title</code>
+ */
+ protected Component getComponent( DockTitle title ){
+ return title.getComponent();
}
@Override
@@ -239,20 +305,20 @@ public Dimension getMinimumSize() {
Dimension base;
if( title == null && dockable != null )
- base = dockable.getComponent().getMinimumSize();
+ base = getComponent( dockable ).getMinimumSize();
else if( dockable == null && title != null )
- base = title.getComponent().getMinimumSize();
+ base = getComponent( title ).getMinimumSize();
else if( dockable == null && title == null )
base = new Dimension( 0, 0 );
else if( location == Location.LEFT || location == Location.RIGHT ){
- Dimension titleSize = title.getComponent().getMinimumSize();
- base = dockable.getComponent().getMinimumSize();
+ Dimension titleSize = getComponent( title ).getMinimumSize();
+ base = getComponent( dockable ).getMinimumSize();
base = new Dimension( base.width + titleSize.width,
Math.max( base.height, titleSize.height ));
}
else{
- Dimension titleSize = title.getComponent().getMinimumSize();
- base = dockable.getComponent().getMinimumSize();
+ Dimension titleSize = getComponent( title ).getMinimumSize();
+ base = getComponent( dockable ).getMinimumSize();
base = new Dimension( Math.max( titleSize.width, base.width ),
titleSize.height + base.height );
}
@@ -283,13 +349,13 @@ public void doLayout(){
height = Math.max( 0, height );
if( title == null )
- dockable.getComponent().setBounds( x, y, width, height );
+ getComponent( dockable ).setBounds( x, y, width, height );
else if( dockable == null )
- title.getComponent().setBounds( x, y, width, height );
+ getComponent( title ).setBounds( x, y, width, height );
else{
- Dimension preferred = title.getComponent().getPreferredSize();
+ Dimension preferred = getComponent( title ).getPreferredSize();
int preferredWidth = preferred.width;
int preferredHeight = preferred.height;
@@ -304,20 +370,20 @@ else if( dockable == null )
}
if( location == Location.LEFT ){
- title.getComponent().setBounds( x, y, preferredWidth, preferredHeight );
- dockable.getComponent().setBounds( x+preferredWidth, y, width - preferredWidth, height );
+ getComponent( title ).setBounds( x, y, preferredWidth, preferredHeight );
+ getComponent( dockable ).setBounds( x+preferredWidth, y, width - preferredWidth, height );
}
else if( location == Location.RIGHT ){
- title.getComponent().setBounds( x+width-preferredWidth, y, preferredWidth, preferredHeight );
- dockable.getComponent().setBounds( x, y, width - preferredWidth, preferredHeight );
+ getComponent( title ).setBounds( x+width-preferredWidth, y, preferredWidth, preferredHeight );
+ getComponent( dockable ).setBounds( x, y, width - preferredWidth, preferredHeight );
}
else if( location == Location.BOTTOM ){
- title.getComponent().setBounds( x, y+height - preferredHeight, preferredWidth, preferredHeight );
- dockable.getComponent().setBounds( x, y, preferredWidth, height - preferredHeight );
+ getComponent( title ).setBounds( x, y+height - preferredHeight, preferredWidth, preferredHeight );
+ getComponent( dockable ).setBounds( x, y, preferredWidth, height - preferredHeight );
}
else{
- title.getComponent().setBounds( x, y, preferredWidth, preferredHeight );
- dockable.getComponent().setBounds( x, y+preferredHeight, preferredWidth, height - preferredHeight );
+ getComponent( title ).setBounds( x, y, preferredWidth, preferredHeight );
+ getComponent( dockable ).setBounds( x, y+preferredHeight, preferredWidth, height - preferredHeight );
}
}
}
|
34cab689ebead817a7f6b960ef8fca91f4d0d1d1
|
Vala
|
gtk+-2.0: Fix several GtkIMContext-related bindings
Fixes bug 611533.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi
index d9446367d5..8b3b951bfe 100644
--- a/vapi/gtk+-2.0.vapi
+++ b/vapi/gtk+-2.0.vapi
@@ -1712,8 +1712,8 @@ namespace Gtk {
public virtual bool filter_keypress (Gdk.EventKey event);
public virtual void focus_in ();
public virtual void focus_out ();
- public virtual void get_preedit_string (string str, out unowned Pango.AttrList attrs, int cursor_pos);
- public virtual bool get_surrounding (string text, int cursor_index);
+ public virtual void get_preedit_string (out unowned string str, out Pango.AttrList attrs, out int cursor_pos);
+ public virtual bool get_surrounding (out unowned string text, out int cursor_index);
public virtual void reset ();
public virtual void set_client_window (Gdk.Window window);
public virtual void set_cursor_location (Gdk.Rectangle area);
@@ -1727,15 +1727,6 @@ namespace Gtk {
public virtual signal void preedit_start ();
public virtual signal bool retrieve_surrounding ();
}
- [Compact]
- [CCode (cheader_filename = "gtk/gtk.h")]
- public class IMContextInfo {
- public weak string context_id;
- public weak string context_name;
- public weak string default_locales;
- public weak string domain;
- public weak string domain_dirname;
- }
[CCode (cheader_filename = "gtk/gtk.h")]
public class IMContextSimple : Gtk.IMContext {
[CCode (array_length = false)]
@@ -5858,6 +5849,14 @@ namespace Gtk {
public Gtk.Border copy ();
public void free ();
}
+ [CCode (type_id = "GTK_TYPE_IM_CONTEXT_INFO", cheader_filename = "gtk/gtk.h")]
+ public struct IMContextInfo {
+ public weak string context_id;
+ public weak string context_name;
+ public weak string domain;
+ public weak string domain_dirname;
+ public weak string default_locales;
+ }
[CCode (type_id = "GTK_TYPE_RADIO_ACTION_ENTRY", cheader_filename = "gtk/gtk.h")]
public struct RadioActionEntry {
public weak string name;
diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
index 59db8f1397..ada4ef5ff4 100644
--- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
+++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
@@ -209,6 +209,12 @@ gtk_image_get_stock.stock_id is_out="1" transfer_ownership="1"
gtk_image_get_stock.size is_out="1"
gtk_image_menu_item_new_from_stock.accel_group nullable="1"
GtkIMContext::delete_surrounding has_emitter="1"
+gtk_im_context_get_preedit_string.str is_out="1"
+gtk_im_context_get_preedit_string.attrs transfer_ownership="1"
+gtk_im_context_get_preedit_string.cursor_pos is_out="1"
+gtk_im_context_get_surrounding.text is_out="1"
+gtk_im_context_get_surrounding.cursor_index is_out="1"
+GtkIMContextInfo is_value_type="1"
gtk_init.argc hidden="1"
gtk_init.argv is_array="1" is_ref="1" array_length_pos="0.9"
gtk_init_check.argc hidden="1"
|
221e57d0dc01fe95309987db0e1b5f8264b0c85a
|
Valadoc
|
docbook: improve implicit parameter handling
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index bb2d50005a..417590be8e 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -38,6 +38,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
private ErrorReporter reporter;
private Settings settings;
private Api.Tree tree;
+ private Api.Node? element;
private bool show_warnings;
private Api.SourceComment comment;
@@ -113,8 +114,6 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
- private Api.Node? element;
-
public Comment? parse (Api.Node element, Api.GirSourceComment gir_comment, GirMetaData gir_metadata) {
this.instance_param_name = gir_comment.instance_param_name;
this.current_metadata = gir_metadata;
@@ -1415,101 +1414,6 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
- private string[]? split_type_name (string id) {
- unichar c;
-
- for (unowned string pos = id; (c = pos.get_char ()) != '\0'; pos = pos.next_char ()) {
- switch (c) {
- case '-': // ->
- return {id.substring (0, (long) (((char*) pos) - ((char*) id))), "->", (string) (((char*) pos) + 2)};
-
- case ':': // : or ::
- string sep = (pos.next_char ().get_char () == ':')? "::" : ":";
- return {id.substring (0, (long) (((char*) pos) - ((char*) id))), sep, (string) (((char*) pos) + sep.length)};
-
- case '.':
- return {id.substring (0, (long) (((char*) pos) - ((char*) id))), ".", (string) (((char*) pos) + 1)};
- }
- }
-
- return {id};
- }
-
- private string? resolve_parameter_ctype (string parameter_name, out string? param_name,
- out string? param_array_name, out bool is_return_type_len)
- {
- string[]? parts = split_type_name (parameter_name);
- is_return_type_len = false;
- param_array_name = null;
-
- Api.FormalParameter? param = null; // type parameter or formal parameter
- foreach (Api.Node node in this.element.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false)) {
- if (node.name == parts[0]) {
- param = node as Api.FormalParameter;
- break;
- }
-
- if (((Api.FormalParameter) node).implicit_array_length_cparameter_name == parts[0]) {
- param_array_name = ((Api.FormalParameter) node).name;
- break;
- }
- }
-
- if (this.element is Api.Callable
- && ((Api.Callable) this.element).implicit_array_length_cparameter_name == parts[0])
- {
- is_return_type_len = true;
- }
-
- if (parts.length == 1) {
- param_name = parameter_name;
- return null;
- }
-
-
- Api.Item? inner = null;
-
- if (param_array_name != null || is_return_type_len) {
- inner = tree.search_symbol_str (null, "int");
- } else if (param != null) {
- inner = param.parameter_type;
- }
-
- while (inner != null) {
- if (inner is Api.TypeReference) {
- inner = ((Api.TypeReference) inner).data_type;
- } else if (inner is Api.Pointer) {
- inner = ((Api.Pointer) inner).data_type;
- } else if (inner is Api.Array) {
- inner = ((Api.Array) inner).data_type;
- } else {
- break ;
- }
- }
-
-
- if (inner == null) {
- param_name = parameter_name;
- return null;
- }
-
- string? cname = null;
- if (inner is Api.ErrorDomain) {
- cname = ((Api.ErrorDomain) inner).get_cname ();
- } else if (inner is Api.Struct) {
- cname = ((Api.Struct) inner).get_cname ();
- } else if (inner is Api.Class) {
- cname = ((Api.Class) inner).get_cname ();
- } else if (inner is Api.Enum) {
- cname = ((Api.Enum) inner).get_cname ();
- } else {
- assert_not_reached ();
- }
-
- param_name = (owned) parts[0];
- return "c::" + cname + parts[1] + parts[2];
- }
-
private Run parse_inline_content () {
Run run = factory.create_run (Run.Style.NONE);
@@ -1600,7 +1504,14 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
bool is_return_type_len;
string? param_name;
- string? cname = resolve_parameter_ctype (current.content, out param_name, out param_array_name, out is_return_type_len);
+ string? cname = ImporterHelper.resolve_parameter_ctype (
+ this.tree,
+ this.element,
+ current.content,
+ out param_name,
+ out param_array_name,
+ out is_return_type_len);
+
Run current_run = factory.create_run (Run.Style.MONOSPACED);
run.content.add (current_run);
diff --git a/src/libvaladoc/documentation/gtkdocmarkdownparser.vala b/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
index 9614e6c820..341dff050f 100644
--- a/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
+++ b/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
@@ -86,8 +86,33 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
_run = _factory.create_run (Run.Style.LANG_KEYWORD);
_run.content.add (_factory.create_text ("throws"));
} else {
+ string? param_name;
+ string? param_array_name;
+ bool is_return_type_len;
+
+ ImporterHelper.resolve_parameter_ctype (
+ this._tree,
+ this.element,
+ token.value,
+ out param_name,
+ out param_array_name,
+ out is_return_type_len);
+
_run = _factory.create_run (Run.Style.MONOSPACED);
- _run.content.add (_factory.create_text (token.value));
+
+ if (is_return_type_len) {
+ Run keyword_run = _factory.create_run (Run.Style.LANG_KEYWORD);
+ keyword_run.content.add (_factory.create_text ("return"));
+ _run.content.add (keyword_run);
+
+ _run.content.add (_factory.create_text (".length"));
+ } else if (param_array_name != null) {
+ _run.content.add (_factory.create_text (param_array_name + ".length"));
+ } else {
+ _run.content.add (_factory.create_text (param_name));
+ }
+
+
}
push (_run);
diff --git a/src/libvaladoc/documentation/importerhelper.vala b/src/libvaladoc/documentation/importerhelper.vala
index 36ed06dfe0..3f7501836a 100644
--- a/src/libvaladoc/documentation/importerhelper.vala
+++ b/src/libvaladoc/documentation/importerhelper.vala
@@ -27,6 +27,111 @@ using Gee;
namespace Valadoc.ImporterHelper {
+ //
+ // resolve-parameter-ctype:
+ //
+
+ internal string? resolve_parameter_ctype (Api.Tree tree, Api.Node element, string parameter_name,
+ out string? param_name, out string? param_array_name, out bool is_return_type_len)
+ {
+ string[]? parts = split_type_name (parameter_name);
+ is_return_type_len = false;
+ param_array_name = null;
+
+ Api.FormalParameter? param = null; // type parameter or formal parameter
+ foreach (Api.Node node in element.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false)) {
+ if (node.name == parts[0]) {
+ param = node as Api.FormalParameter;
+ break;
+ }
+
+ if (((Api.FormalParameter) node).implicit_array_length_cparameter_name == parts[0]) {
+ param_array_name = ((Api.FormalParameter) node).name;
+ break;
+ }
+ }
+
+ if (element is Api.Callable
+ && ((Api.Callable) element).implicit_array_length_cparameter_name == parts[0])
+ {
+ is_return_type_len = true;
+ }
+
+ if (parts.length == 1) {
+ param_name = parameter_name;
+ return null;
+ }
+
+
+ Api.Item? inner = null;
+
+ if (param_array_name != null || is_return_type_len) {
+ inner = tree.search_symbol_str (null, "int");
+ } else if (param != null) {
+ inner = param.parameter_type;
+ }
+
+ while (inner != null) {
+ if (inner is Api.TypeReference) {
+ inner = ((Api.TypeReference) inner).data_type;
+ } else if (inner is Api.Pointer) {
+ inner = ((Api.Pointer) inner).data_type;
+ } else if (inner is Api.Array) {
+ inner = ((Api.Array) inner).data_type;
+ } else {
+ break ;
+ }
+ }
+
+
+ if (inner == null) {
+ param_name = parameter_name;
+ return null;
+ }
+
+ string? cname = null;
+ if (inner is Api.ErrorDomain) {
+ cname = ((Api.ErrorDomain) inner).get_cname ();
+ } else if (inner is Api.Struct) {
+ cname = ((Api.Struct) inner).get_cname ();
+ } else if (inner is Api.Class) {
+ cname = ((Api.Class) inner).get_cname ();
+ } else if (inner is Api.Enum) {
+ cname = ((Api.Enum) inner).get_cname ();
+ } else {
+ assert_not_reached ();
+ }
+
+ param_name = (owned) parts[0];
+ return "c::" + cname + parts[1] + parts[2];
+ }
+
+
+ private string[]? split_type_name (string id) {
+ unichar c;
+
+ for (unowned string pos = id; (c = pos.get_char ()) != '\0'; pos = pos.next_char ()) {
+ switch (c) {
+ case '-': // ->
+ return {id.substring (0, (long) (((char*) pos) - ((char*) id))), "->", (string) (((char*) pos) + 2)};
+
+ case ':': // : or ::
+ string sep = (pos.next_char ().get_char () == ':')? "::" : ":";
+ return {id.substring (0, (long) (((char*) pos) - ((char*) id))), sep, (string) (((char*) pos) + sep.length)};
+
+ case '.':
+ return {id.substring (0, (long) (((char*) pos) - ((char*) id))), ".", (string) (((char*) pos) + 1)};
+ }
+ }
+
+ return {id};
+ }
+
+
+
+ //
+ // extract-short-desc:
+ //
internal void extract_short_desc (Comment comment, ContentFactory factory) {
if (comment.content.size == 0) {
@@ -99,8 +204,13 @@ namespace Valadoc.ImporterHelper {
}
private inline Run? split_run (Run run, ContentFactory factory) {
+ if (run.style != Run.Style.NONE) {
+ return null;
+ }
+
Run? sec = null;
+
Iterator<Inline> iter = run.content.iterator ();
for (bool has_next = iter.next (); has_next; has_next = iter.next ()) {
Inline item = iter.get ();
|
07842b163a84c993bd3518654e8302a46ded4dfc
|
Vala
|
vapigen: Hide async *_finish methods
Fixes bug 614045.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi
index e038979b08..7892d26df8 100644
--- a/vapi/gio-2.0.vapi
+++ b/vapi/gio-2.0.vapi
@@ -79,7 +79,6 @@ namespace GLib {
public BufferedInputStream (GLib.InputStream base_stream);
public virtual ssize_t fill (ssize_t count, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async ssize_t fill_async (ssize_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual ssize_t fill_finish (GLib.AsyncResult _result) throws GLib.Error;
public size_t get_available ();
public size_t get_buffer_size ();
public size_t peek (void* buffer, size_t offset, size_t count);
@@ -463,13 +462,11 @@ namespace GLib {
public int64 read_int64 (GLib.Cancellable? cancellable) throws GLib.Error;
public string? read_line (out size_t length, GLib.Cancellable? cancellable) throws GLib.Error;
public async string? read_line_async (int io_priority, GLib.Cancellable? cancellable, out size_t length) throws GLib.Error;
- public string? read_line_finish (GLib.AsyncResult _result, out unowned size_t length) throws GLib.Error;
public uint16 read_uint16 (GLib.Cancellable? cancellable) throws GLib.Error;
public uint32 read_uint32 (GLib.Cancellable? cancellable) throws GLib.Error;
public uint64 read_uint64 (GLib.Cancellable? cancellable) throws GLib.Error;
public string? read_until (string stop_chars, out size_t length, GLib.Cancellable? cancellable) throws GLib.Error;
public async string? read_until_async (string stop_chars, int io_priority, GLib.Cancellable? cancellable, out size_t length) throws GLib.Error;
- public string? read_until_finish (GLib.AsyncResult _result, out unowned size_t length) throws GLib.Error;
public void set_byte_order (GLib.DataStreamByteOrder order);
public void set_newline_type (GLib.DataStreamNewlineType type);
public GLib.DataStreamByteOrder byte_order { get; set; }
@@ -550,7 +547,6 @@ namespace GLib {
public class FileEnumerator : GLib.Object {
public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool close_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
public unowned GLib.File get_container ();
@@ -558,7 +554,6 @@ namespace GLib {
public bool is_closed ();
public virtual GLib.FileInfo next_file (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async GLib.List<GLib.FileInfo> next_files_async (int num_files, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual GLib.List<GLib.FileInfo> next_files_finish (GLib.AsyncResult _result) throws GLib.Error;
public void set_pending (bool pending);
public GLib.File container { construct; }
}
@@ -571,7 +566,6 @@ namespace GLib {
public virtual unowned string get_etag ();
public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual unowned GLib.FileInfo query_info_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
[NoWrapper]
@@ -664,7 +658,6 @@ namespace GLib {
public virtual bool can_seek ();
public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual unowned GLib.FileInfo query_info_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
[NoWrapper]
@@ -691,7 +684,6 @@ namespace GLib {
public virtual unowned string get_etag ();
public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual unowned GLib.FileInfo query_info_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
[NoWrapper]
@@ -766,7 +758,6 @@ namespace GLib {
public void clear_pending ();
public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool close_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual unowned GLib.InputStream get_input_stream ();
@@ -832,7 +823,6 @@ namespace GLib {
public void clear_pending ();
public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool close_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
public bool has_pending ();
@@ -840,13 +830,11 @@ namespace GLib {
public ssize_t read (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
public bool read_all (void* buffer, size_t count, out size_t bytes_read, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async ssize_t read_async (void* buffer, size_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual ssize_t read_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual ssize_t read_fn (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
public bool set_pending () throws GLib.Error;
public virtual ssize_t skip (size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async ssize_t skip_async (size_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual ssize_t skip_finish (GLib.AsyncResult _result) throws GLib.Error;
}
[Compact]
[CCode (cheader_filename = "gio/gio.h")]
@@ -937,23 +925,19 @@ namespace GLib {
public void clear_pending ();
public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool close_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual bool flush (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool flush_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool flush_finish (GLib.AsyncResult _result) throws GLib.Error;
public bool has_pending ();
public bool is_closed ();
public bool is_closing ();
public bool set_pending () throws GLib.Error;
public virtual ssize_t splice (GLib.InputStream source, GLib.OutputStreamSpliceFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async ssize_t splice_async (GLib.InputStream source, GLib.OutputStreamSpliceFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual ssize_t splice_finish (GLib.AsyncResult _result) throws GLib.Error;
public ssize_t write (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
public bool write_all (void* buffer, size_t count, out size_t bytes_written, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async ssize_t write_async (void* buffer, size_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual ssize_t write_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public virtual ssize_t write_fn (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
}
@@ -967,14 +951,12 @@ namespace GLib {
public class Permission : GLib.Object {
public virtual bool acquire (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool acquire_async (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool acquire_finish (GLib.AsyncResult _result) throws GLib.Error;
public bool get_allowed ();
public bool get_can_acquire ();
public bool get_can_release ();
public void impl_update (bool allowed, bool can_acquire, bool can_release);
public virtual bool release (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async bool release_async (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool release_finish (GLib.AsyncResult _result) throws GLib.Error;
public bool allowed { get; }
public bool can_acquire { get; }
public bool can_release { get; }
@@ -985,13 +967,10 @@ namespace GLib {
public static unowned GLib.Resolver get_default ();
public virtual unowned string lookup_by_address (GLib.InetAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async unowned string lookup_by_address_async (GLib.InetAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual unowned string lookup_by_address_finish (GLib.AsyncResult _result) throws GLib.Error;
public virtual GLib.List<GLib.InetAddress> lookup_by_name (string hostname, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async GLib.List<GLib.InetAddress> lookup_by_name_async (string hostname, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual GLib.List<GLib.InetAddress> lookup_by_name_finish (GLib.AsyncResult _result) throws GLib.Error;
public virtual GLib.List<GLib.SrvTarget> lookup_service (string service, string protocol, string domain, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async GLib.List<GLib.SrvTarget> lookup_service_async (string service, string protocol, string domain, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual GLib.List<GLib.SrvTarget> lookup_service_finish (GLib.AsyncResult _result) throws GLib.Error;
public void set_default ();
public virtual signal void reload ();
}
@@ -1173,7 +1152,6 @@ namespace GLib {
public class SocketAddressEnumerator : GLib.Object {
public virtual unowned GLib.SocketAddress next (GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async unowned GLib.SocketAddress next_async (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual unowned GLib.SocketAddress next_finish (GLib.AsyncResult _result) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public class SocketClient : GLib.Object {
@@ -1181,13 +1159,10 @@ namespace GLib {
public SocketClient ();
public unowned GLib.SocketConnection connect (GLib.SocketConnectable connectable, GLib.Cancellable? cancellable) throws GLib.Error;
public async unowned GLib.SocketConnection connect_async (GLib.SocketConnectable connectable, GLib.Cancellable? cancellable) throws GLib.Error;
- public unowned GLib.SocketConnection connect_finish (GLib.AsyncResult _result) throws GLib.Error;
public unowned GLib.SocketConnection connect_to_host (string host_and_port, uint16 default_port, GLib.Cancellable? cancellable) throws GLib.Error;
public async unowned GLib.SocketConnection connect_to_host_async (string host_and_port, uint16 default_port, GLib.Cancellable? cancellable) throws GLib.Error;
- public unowned GLib.SocketConnection connect_to_host_finish (GLib.AsyncResult _result) throws GLib.Error;
public unowned GLib.SocketConnection connect_to_service (string domain, string service, GLib.Cancellable? cancellable) throws GLib.Error;
public async unowned GLib.SocketConnection connect_to_service_async (string domain, string service, GLib.Cancellable? cancellable) throws GLib.Error;
- public unowned GLib.SocketConnection connect_to_service_finish (GLib.AsyncResult _result) throws GLib.Error;
public GLib.SocketFamily get_family ();
public unowned GLib.SocketAddress get_local_address ();
public GLib.SocketProtocol get_protocol ();
@@ -1228,10 +1203,8 @@ namespace GLib {
public SocketListener ();
public unowned GLib.SocketConnection accept (out unowned GLib.Object source_object, GLib.Cancellable? cancellable) throws GLib.Error;
public async unowned GLib.SocketConnection accept_async (GLib.Cancellable? cancellable, out unowned GLib.Object source_object) throws GLib.Error;
- public unowned GLib.SocketConnection accept_finish (GLib.AsyncResult _result, out unowned GLib.Object source_object) throws GLib.Error;
public unowned GLib.Socket accept_socket (out unowned GLib.Object source_object, GLib.Cancellable? cancellable) throws GLib.Error;
public async unowned GLib.Socket accept_socket_async (GLib.Cancellable? cancellable, out unowned GLib.Object source_object) throws GLib.Error;
- public unowned GLib.Socket accept_socket_finish (GLib.AsyncResult _result, out unowned GLib.Object source_object) throws GLib.Error;
public bool add_address (GLib.SocketAddress address, GLib.SocketType type, GLib.SocketProtocol protocol, GLib.Object? source_object, out unowned GLib.SocketAddress effective_address) throws GLib.Error;
public uint16 add_any_inet_port (GLib.Object source_object) throws GLib.Error;
public bool add_inet_port (uint16 port, GLib.Object? source_object) throws GLib.Error;
@@ -1410,9 +1383,7 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public interface AsyncInitable : GLib.Object {
public abstract async bool init_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool init_finish (GLib.AsyncResult res) throws GLib.Error;
public static async unowned GLib.Object new_async (GLib.Type object_type, int io_priority, GLib.Cancellable? cancellable, ...) throws GLib.Error;
- public unowned GLib.Object new_finish (GLib.AsyncResult res) throws GLib.Error;
public static async void new_valist_async (GLib.Type object_type, string first_property_name, void* var_args, int io_priority, GLib.Cancellable? cancellable);
public static async void newv_async (GLib.Type object_type, uint n_parameters, GLib.Parameter parameters, int io_priority, GLib.Cancellable? cancellable);
}
@@ -1434,9 +1405,7 @@ namespace GLib {
public abstract bool can_start_degraded ();
public abstract bool can_stop ();
public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_with_operation_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract unowned string enumerate_identifiers ();
public abstract unowned GLib.Icon get_icon ();
public abstract unowned string get_identifier (string kind);
@@ -1448,11 +1417,8 @@ namespace GLib {
public abstract bool is_media_check_automatic ();
public abstract bool is_media_removable ();
public abstract async bool poll_for_media (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool poll_for_media_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool start (GLib.DriveStartFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool start_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool stop (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool stop_finish (GLib.AsyncResult _result) throws GLib.Error;
public signal void changed ();
public signal void disconnected ();
public signal void eject_button ();
@@ -1462,32 +1428,24 @@ namespace GLib {
public interface File : GLib.Object {
public abstract GLib.FileOutputStream append_to (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.FileOutputStream append_to_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileOutputStream append_to_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract bool copy (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable, GLib.FileProgressCallback? progress_callback) throws GLib.Error;
public abstract async bool copy_async (GLib.File destination, GLib.FileCopyFlags flags, int io_priority, GLib.Cancellable? cancellable, GLib.FileProgressCallback? progress_callback) throws GLib.Error;
public bool copy_attributes (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool copy_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract GLib.FileOutputStream create (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.FileOutputStream create_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileOutputStream create_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract unowned GLib.FileIOStream create_readwrite (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async unowned GLib.FileIOStream create_readwrite_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileIOStream create_readwrite_finish (GLib.AsyncResult res) throws GLib.Error;
public bool @delete (GLib.Cancellable? cancellable) throws GLib.Error;
[NoWrapper]
public abstract bool delete_file (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract unowned GLib.File dup ();
public abstract async bool eject_mountable (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_mountable_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool eject_mountable_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_mountable_with_operation_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract GLib.FileEnumerator enumerate_children (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.FileEnumerator enumerate_children_async (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileEnumerator enumerate_children_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract bool equal (GLib.File file2);
public abstract GLib.Mount find_enclosing_mount (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.Mount find_enclosing_mount_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.Mount find_enclosing_mount_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract string? get_basename ();
public GLib.File get_child (string name);
public abstract GLib.File get_child_for_display_name (string display_name) throws GLib.Error;
@@ -1504,9 +1462,7 @@ namespace GLib {
public abstract bool is_native ();
public bool load_contents (GLib.Cancellable? cancellable, out string contents, out size_t length, out string etag_out) throws GLib.Error;
public async bool load_contents_async (GLib.Cancellable? cancellable, out string contents, out size_t length, out string etag_out) throws GLib.Error;
- public bool load_contents_finish (GLib.AsyncResult res, out string contents, out unowned size_t length, out string etag_out) throws GLib.Error;
public async bool load_partial_contents_async (GLib.Cancellable? cancellable, GLib.FileReadMoreCallback read_more_callback, out string contents, out size_t length, out string etag_out) throws GLib.Error;
- public bool load_partial_contents_finish (GLib.AsyncResult res, out string contents, out unowned size_t length, out string etag_out) throws GLib.Error;
public abstract bool make_directory (GLib.Cancellable? cancellable) throws GLib.Error;
public bool make_directory_with_parents (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract bool make_symbolic_link (string symlink_value, GLib.Cancellable? cancellable) throws GLib.Error;
@@ -1515,19 +1471,15 @@ namespace GLib {
public abstract GLib.FileMonitor monitor_directory (GLib.FileMonitorFlags flags, GLib.Cancellable? cancellable = null) throws GLib.IOError;
public abstract GLib.FileMonitor monitor_file (GLib.FileMonitorFlags flags, GLib.Cancellable? cancellable = null) throws GLib.IOError;
public abstract async bool mount_enclosing_volume (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool mount_enclosing_volume_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async unowned GLib.File mount_mountable (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.File mount_mountable_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract bool move (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable, GLib.FileProgressCallback? progress_callback) throws GLib.Error;
public static GLib.File new_for_commandline_arg (string arg);
public static GLib.File new_for_path (string path);
public static GLib.File new_for_uri (string uri);
public abstract unowned GLib.FileIOStream open_readwrite (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async unowned GLib.FileIOStream open_readwrite_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileIOStream open_readwrite_finish (GLib.AsyncResult res) throws GLib.Error;
public static unowned GLib.File parse_name (string parse_name);
public abstract async bool poll_mountable (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool poll_mountable_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public abstract bool prefix_matches (GLib.File file);
public GLib.AppInfo query_default_handler (GLib.Cancellable? cancellable) throws GLib.Error;
@@ -1535,26 +1487,20 @@ namespace GLib {
public GLib.FileType query_file_type (GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable);
public abstract unowned GLib.FileInfo query_filesystem_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async unowned GLib.FileInfo query_filesystem_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileInfo query_filesystem_info_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract GLib.FileInfo query_info (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.FileInfo query_info_async (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileInfo query_info_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract unowned GLib.FileAttributeInfoList query_settable_attributes (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract unowned GLib.FileAttributeInfoList query_writable_namespaces (GLib.Cancellable? cancellable) throws GLib.Error;
public GLib.FileInputStream read (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.FileInputStream read_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileInputStream read_finish (GLib.AsyncResult res) throws GLib.Error;
[NoWrapper]
public abstract unowned GLib.FileInputStream read_fn (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract GLib.FileOutputStream replace (string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.FileOutputStream replace_async (string? etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
public bool replace_contents (string contents, size_t length, string? etag, bool make_backup, GLib.FileCreateFlags flags, out string? new_etag, GLib.Cancellable? cancellable) throws GLib.Error;
public async bool replace_contents_async (string contents, size_t length, string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable, out string? new_etag) throws GLib.Error;
- public bool replace_contents_finish (GLib.AsyncResult res, out string new_etag) throws GLib.Error;
- public abstract GLib.FileOutputStream replace_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract unowned GLib.FileIOStream replace_readwrite (string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async unowned GLib.FileIOStream replace_readwrite_async (string? etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileIOStream replace_readwrite_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract GLib.File resolve_relative_path (string relative_path);
public abstract bool set_attribute (string attribute, GLib.FileAttributeType type, void* value_p, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public bool set_attribute_byte_string (string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
@@ -1564,21 +1510,15 @@ namespace GLib {
public bool set_attribute_uint32 (string attribute, uint32 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public bool set_attribute_uint64 (string attribute, uint64 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async bool set_attributes_async (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable, out unowned GLib.FileInfo info_out) throws GLib.Error;
- public abstract bool set_attributes_finish (GLib.AsyncResult _result, out unowned GLib.FileInfo info) throws GLib.Error;
public abstract bool set_attributes_from_info (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract unowned GLib.File set_display_name (string display_name, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async unowned GLib.File set_display_name_async (string display_name, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.File set_display_name_finish (GLib.AsyncResult res) throws GLib.Error;
public abstract async bool start_mountable (GLib.DriveStartFlags flags, GLib.MountOperation start_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool start_mountable_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool stop_mountable (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool stop_mountable_finish (GLib.AsyncResult _result) throws GLib.Error;
public bool supports_thread_contexts ();
public abstract bool trash (GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async bool unmount_mountable (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool unmount_mountable_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool unmount_mountable_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool unmount_mountable_with_operation_finish (GLib.AsyncResult _result) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public interface Icon : GLib.Object {
@@ -1602,16 +1542,13 @@ namespace GLib {
public interface LoadableIcon : GLib.Icon, GLib.Object {
public abstract unowned GLib.InputStream load (int size, out unowned string? type, GLib.Cancellable? cancellable) throws GLib.Error;
public abstract async unowned GLib.InputStream load_async (int size, GLib.Cancellable? cancellable, out unowned string? type) throws GLib.Error;
- public abstract unowned GLib.InputStream load_finish (GLib.AsyncResult res, out unowned string type) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public interface Mount : GLib.Object {
public abstract bool can_eject ();
public abstract bool can_unmount ();
public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_with_operation_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract unowned GLib.File get_default_location ();
public abstract unowned GLib.Drive get_drive ();
public abstract unowned GLib.Icon get_icon ();
@@ -1620,16 +1557,12 @@ namespace GLib {
public abstract unowned string get_uuid ();
public abstract unowned GLib.Volume get_volume ();
public abstract async unowned string guess_content_type (bool force_rescan, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned string guess_content_type_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract unowned string guess_content_type_sync (bool force_rescan, GLib.Cancellable? cancellable) throws GLib.Error;
public bool is_shadowed ();
public abstract async bool remount (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool remount_finish (GLib.AsyncResult _result) throws GLib.Error;
public void shadow ();
public abstract async bool unmount (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool unmount_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool unmount_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool unmount_with_operation_finish (GLib.AsyncResult _result) throws GLib.Error;
public void unshadow ();
public signal void changed ();
public signal void pre_unmount ();
@@ -1653,9 +1586,7 @@ namespace GLib {
public abstract bool can_eject ();
public abstract bool can_mount ();
public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool eject_with_operation_finish (GLib.AsyncResult _result) throws GLib.Error;
public abstract unowned string enumerate_identifiers ();
public abstract unowned GLib.File get_activation_root ();
public abstract unowned GLib.Drive get_drive ();
@@ -1665,7 +1596,6 @@ namespace GLib {
public abstract unowned string get_name ();
public abstract unowned string get_uuid ();
public async bool mount (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool mount_finish (GLib.AsyncResult _result) throws GLib.Error;
[NoWrapper]
public abstract void mount_fn (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable, GLib.AsyncReadyCallback callback);
public abstract bool should_automount ();
diff --git a/vapi/libgdata.vapi b/vapi/libgdata.vapi
index 5cbee29244..cfa69c9deb 100644
--- a/vapi/libgdata.vapi
+++ b/vapi/libgdata.vapi
@@ -1165,13 +1165,13 @@ namespace GData {
public unowned GData.PicasaWebAlbum insert_album (GData.PicasaWebAlbum album, GLib.Cancellable cancellable) throws GLib.Error;
[CCode (cname = "gdata_picasaweb_service_query_all_albums")]
public unowned GData.Feed query_all_albums (GData.Query? query, string? username, GLib.Cancellable? cancellable, GData.QueryProgressCallback? progress_callback) throws GLib.Error;
- [CCode (cname = "gdata_picasaweb_service_query_all_albums_async")]
+ [CCode (cname = "gdata_picasaweb_service_query_all_albums_async", finish_name = "gdata_picasa_web_service_query_all_albums_finish")]
public async void query_all_albums_async (GData.Query? query, string username, GLib.Cancellable? cancellable, GData.QueryProgressCallback progress_callback);
[CCode (cname = "gdata_picasaweb_service_query_files")]
public unowned GData.Feed query_files (GData.PicasaWebAlbum album, GData.Query? query, GLib.Cancellable? cancellable, GData.QueryProgressCallback? progress_callback) throws GLib.Error;
[CCode (cname = "gdata_picasaweb_service_upload_file")]
public unowned GData.PicasaWebFile upload_file (GData.PicasaWebAlbum album, GData.PicasaWebFile file_entry, GLib.File file_data, GLib.Cancellable cancellable) throws GLib.Error;
- [CCode (cname = "gdata_picasaweb_service_upload_file_async")]
+ [CCode (cname = "gdata_picasaweb_service_upload_file_async", finish_name = "gdata_picasa_web_service_upload_file_finish")]
public async GData.PicasaWebFile upload_file_async (GData.PicasaWebAlbum album, GData.PicasaWebFile file_entry, GLib.File file_data, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gdata/gdata.h")]
@@ -1244,10 +1244,8 @@ namespace GData {
public virtual void append_query_headers (Soup.Message message);
public bool authenticate (string username, string password, GLib.Cancellable? cancellable) throws GLib.Error;
public async bool authenticate_async (string username, string password, GLib.Cancellable cancellable) throws GLib.Error;
- public bool authenticate_finish (GLib.AsyncResult async_result) throws GLib.Error;
public bool delete_entry (GData.Entry entry, GLib.Cancellable cancellable) throws GLib.Error;
public async bool delete_entry_async (GData.Entry entry, GLib.Cancellable cancellable) throws GLib.Error;
- public bool delete_entry_finish (GLib.AsyncResult async_result) throws GLib.Error;
public static GLib.Quark error_quark ();
public unowned string get_client_id ();
public unowned string get_password ();
@@ -1255,7 +1253,6 @@ namespace GData {
public unowned string get_username ();
public unowned GData.Entry insert_entry (string upload_uri, GData.Entry entry, GLib.Cancellable cancellable) throws GLib.Error;
public async unowned GData.Entry insert_entry_async (string upload_uri, GData.Entry entry, GLib.Cancellable cancellable) throws GLib.Error;
- public unowned GData.Entry insert_entry_finish (GLib.AsyncResult async_result) throws GLib.Error;
public bool is_authenticated ();
[NoWrapper]
public virtual bool parse_authentication_response (uint status, string response_body, int length) throws GLib.Error;
@@ -1263,14 +1260,11 @@ namespace GData {
public virtual void parse_error_response (GData.OperationType operation_type, uint status, string reason_phrase, string response_body, int length) throws GLib.Error;
public unowned GData.Feed query (string feed_uri, GData.Query query, GLib.Type entry_type, GLib.Cancellable cancellable, GData.QueryProgressCallback progress_callback, void* progress_user_data) throws GLib.Error;
public async unowned GData.Feed query_async (string feed_uri, GData.Query query, GLib.Type entry_type, GLib.Cancellable cancellable, GData.QueryProgressCallback progress_callback, void* progress_user_data) throws GLib.Error;
- public unowned GData.Feed query_finish (GLib.AsyncResult async_result) throws GLib.Error;
public unowned GData.Entry query_single_entry (string entry_id, GData.Query query, GLib.Type entry_type, GLib.Cancellable cancellable) throws GLib.Error;
public async unowned GData.Entry query_single_entry_async (string entry_id, GData.Query query, GLib.Type entry_type, GLib.Cancellable cancellable) throws GLib.Error;
- public unowned GData.Entry query_single_entry_finish (GLib.AsyncResult async_result) throws GLib.Error;
public void set_proxy_uri (Soup.URI proxy_uri);
public unowned GData.Entry update_entry (GData.Entry entry, GLib.Cancellable cancellable) throws GLib.Error;
public async unowned GData.Entry update_entry_async (GData.Entry entry, GLib.Cancellable cancellable) throws GLib.Error;
- public unowned GData.Entry update_entry_finish (GLib.AsyncResult async_result) throws GLib.Error;
[NoAccessorMethod]
public bool authenticated { get; }
public string client_id { get; construct; }
diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala
index 9712cec35f..e42a24e633 100644
--- a/vapigen/valagidlparser.vala
+++ b/vapigen/valagidlparser.vala
@@ -1315,7 +1315,10 @@ public class Vala.GIdlParser : CodeVisitor {
}
void handle_async_methods (ObjectTypeSymbol type_symbol) {
- foreach (Method m in type_symbol.get_methods ()) {
+ var methods = type_symbol.get_methods ();
+ for (int method_n = 0 ; method_n < methods.size ; method_n++) {
+ var m = methods.get (method_n);
+
if (m.coroutine) {
string finish_method_base;
if (m.name.has_suffix ("_async")) {
@@ -1353,6 +1356,11 @@ public class Vala.GIdlParser : CodeVisitor {
foreach (DataType error_type in finish_method.get_error_types ()) {
m.add_error_type (error_type.copy ());
}
+ if (methods.index_of (finish_method) < method_n) {
+ method_n--;
+ }
+ type_symbol.scope.remove (finish_method.name);
+ methods.remove (finish_method);
}
}
}
|
0ab9ab9ce7eeaeb195740d36de05daa0fe3b003c
|
hbase
|
HBASE-8921 [thrift2] Add GenericOptionsParser to- Thrift 2 server--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1501982 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java
index 87b89b5f563d..a610bf1b7912 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java
@@ -18,6 +18,7 @@
*/
package org.apache.hadoop.hbase.thrift2;
+import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
@@ -46,6 +47,7 @@
import org.apache.hadoop.hbase.thrift.ThriftMetrics;
import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
import org.apache.hadoop.hbase.util.InfoServer;
+import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
@@ -105,9 +107,12 @@ private static Options getOptions() {
return options;
}
- private static CommandLine parseArguments(Options options, String[] args) throws ParseException {
+ private static CommandLine parseArguments(Configuration conf, Options options, String[] args)
+ throws ParseException, IOException {
+ GenericOptionsParser genParser = new GenericOptionsParser(conf, args);
+ String[] remainingArgs = genParser.getRemainingArgs();
CommandLineParser parser = new PosixParser();
- return parser.parse(options, args);
+ return parser.parse(options, remainingArgs);
}
private static TProtocolFactory getTProtocolFactory(boolean isCompact) {
@@ -222,7 +227,8 @@ public static void main(String[] args) throws Exception {
TServer server = null;
Options options = getOptions();
try {
- CommandLine cmd = parseArguments(options, args);
+ Configuration conf = HBaseConfiguration.create();
+ CommandLine cmd = parseArguments(conf, options, args);
/**
* This is to please both bin/hbase and bin/hbase-daemon. hbase-daemon provides "start" and "stop" arguments hbase
@@ -245,7 +251,6 @@ public static void main(String[] args) throws Exception {
boolean nonblocking = cmd.hasOption("nonblocking");
boolean hsha = cmd.hasOption("hsha");
- Configuration conf = HBaseConfiguration.create();
ThriftMetrics metrics = new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.TWO);
String implType = "threadpool";
|
3d7ec9ba69f2936d30b7ea34cb46369ac5e0de04
|
orientdb
|
Profiler: - all the metrics now have a- description and a type - supported new HTTP REST command /profiler/metadata- to retrieve all the metadata--
|
a
|
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 a396b241130..40e47de7a63 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
@@ -1588,8 +1588,11 @@ protected OChannelBinaryClient beginRequest(final byte iCommand) throws IOExcept
throw new OStorageException("Cannot acquire a connection because the thread has been interrupted");
}
- final long elapsed = Orient.instance().getProfiler()
- .stopChrono("system.network.connectionPool.waitingTime", startToWait);
+ final long elapsed = Orient
+ .instance()
+ .getProfiler()
+ .stopChrono("system.network.connectionPool.waitingTime", "Waiting for a free connection from the pool of channels",
+ startToWait);
if (debug)
System.out.println("Waiting for connection = elapsed: " + elapsed);
diff --git a/commons/src/main/java/com/orientechnologies/common/profiler/OProfiler.java b/commons/src/main/java/com/orientechnologies/common/profiler/OProfiler.java
index 0ee95c2dc8e..8cfa7cd3ab3 100644
--- a/commons/src/main/java/com/orientechnologies/common/profiler/OProfiler.java
+++ b/commons/src/main/java/com/orientechnologies/common/profiler/OProfiler.java
@@ -22,6 +22,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
@@ -40,20 +41,26 @@
* @copyrights Orient Technologies.com
*/
public class OProfiler extends OSharedResourceAbstract implements OProfilerMBean {
- protected long recordingFrom = -1;
- protected Map<OProfilerHookValue, String> hooks = new ConcurrentHashMap<OProfiler.OProfilerHookValue, String>();
- protected Date lastReset = new Date();
+ public enum METRIC_TYPE {
+ CHRONO, COUNTER, STAT, SIZE, ENABLED, TIMES, TEXT
+ }
+
+ protected long recordingFrom = -1;
+ protected Map<String, OProfilerHookValue> hooks = new ConcurrentHashMap<String, OProfilerHookValue>();
+ protected Date lastReset = new Date();
- protected OProfilerData realTime = new OProfilerData();
- protected OProfilerData lastSnapshot;
- protected List<OProfilerData> snapshots = new ArrayList<OProfilerData>();
- protected List<OProfilerData> summaries = new ArrayList<OProfilerData>();
+ protected ConcurrentHashMap<String, String> dictionary = new ConcurrentHashMap<String, String>();
+ protected ConcurrentHashMap<String, METRIC_TYPE> types = new ConcurrentHashMap<String, METRIC_TYPE>();
+ protected OProfilerData realTime = new OProfilerData();
+ protected OProfilerData lastSnapshot;
+ protected List<OProfilerData> snapshots = new ArrayList<OProfilerData>();
+ protected List<OProfilerData> summaries = new ArrayList<OProfilerData>();
- protected int elapsedToCreateSnapshot = 0;
- protected int maxSnapshots = 0;
- protected int maxSummaries = 0;
- protected final static Timer timer = new Timer(true);
- protected TimerTask archiverTask;
+ protected int elapsedToCreateSnapshot = 0;
+ protected int maxSnapshots = 0;
+ protected int maxSummaries = 0;
+ protected final static Timer timer = new Timer(true);
+ protected TimerTask archiverTask;
public interface OProfilerHookValue {
public Object getValue();
@@ -148,6 +155,8 @@ public void stopRecording() {
lastSnapshot = null;
realTime.clear();
+ dictionary.clear();
+ types.clear();
if (archiverTask != null)
archiverTask.cancel();
@@ -205,15 +214,17 @@ public void createSnapshot() {
}
}
- public void updateCounter(final String iStatName, final long iPlus) {
- if (iStatName == null || recordingFrom < 0)
+ public void updateCounter(final String iName, final String iDescription, final long iPlus) {
+ if (iName == null || recordingFrom < 0)
return;
+ updateMetadata(iName, iDescription, METRIC_TYPE.COUNTER);
+
acquireSharedLock();
try {
if (lastSnapshot != null)
- lastSnapshot.updateCounter(iStatName, iPlus);
- realTime.updateCounter(iStatName, iPlus);
+ lastSnapshot.updateCounter(iName, iPlus);
+ realTime.updateCounter(iName, iPlus);
} finally {
releaseSharedLock();
}
@@ -302,6 +313,31 @@ public String toJSON(final String iQuery, final String iFrom, final String iTo)
return buffer.toString();
}
+ public String metadataToJSON() {
+ final StringBuilder buffer = new StringBuilder();
+
+ buffer.append("{ \"metadata\": {\n ");
+ boolean first = true;
+ for (Entry<String, String> entry : dictionary.entrySet()) {
+ final String key = entry.getKey();
+
+ if (first)
+ first = false;
+ else
+ buffer.append(",\n ");
+ buffer.append('"');
+ buffer.append(key);
+ buffer.append("\":{\"description\":\"");
+ buffer.append(entry.getValue());
+ buffer.append("\",\"type\":\"");
+ buffer.append(types.get(key));
+ buffer.append("\"}");
+ }
+ buffer.append("} }");
+
+ return buffer.toString();
+ }
+
public String dump() {
final float maxMem = Runtime.getRuntime().maxMemory() / 1000000f;
final float totMem = Runtime.getRuntime().totalMemory() / 1000000f;
@@ -343,28 +379,36 @@ public long startChrono() {
return System.currentTimeMillis();
}
- public long stopChrono(final String iName, final long iStartTime) {
+ public long stopChrono(final String iName, final String iDescription, final long iStartTime) {
+ return stopChrono(iName, iDescription, iStartTime, null);
+ }
+
+ public long stopChrono(final String iName, final String iDescription, final long iStartTime, final String iPayload) {
// CHECK IF CHRONOS ARE ACTIVED
if (recordingFrom < 0)
return -1;
+ updateMetadata(iName, iDescription, METRIC_TYPE.CHRONO);
+
acquireSharedLock();
try {
if (lastSnapshot != null)
- lastSnapshot.stopChrono(iName, iStartTime);
- return realTime.stopChrono(iName, iStartTime);
+ lastSnapshot.stopChrono(iName, iStartTime, iPayload);
+ return realTime.stopChrono(iName, iStartTime, iPayload);
} finally {
releaseSharedLock();
}
}
- public long updateStat(final String iName, final long iValue) {
+ public long updateStat(final String iName, final String iDescription, final long iValue) {
// CHECK IF CHRONOS ARE ACTIVED
if (recordingFrom < 0)
return -1;
+ updateMetadata(iName, iDescription, METRIC_TYPE.STAT);
+
acquireSharedLock();
try {
@@ -426,19 +470,14 @@ public String dumpHookValues() {
buffer.append(String.format("\n%50s | Value |", "Name"));
buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
- final List<String> names = new ArrayList<String>(hooks.values());
+ final List<String> names = new ArrayList<String>(hooks.keySet());
Collections.sort(names);
for (String k : names) {
- for (Map.Entry<OProfilerHookValue, String> v : hooks.entrySet()) {
- if (v.getValue().equals(k)) {
- final OProfilerHookValue hook = v.getKey();
- if (hook != null) {
- final Object hookValue = hook.getValue();
- buffer.append(String.format("\n%-50s | %-65s |", k, hookValue != null ? hookValue.toString() : "null"));
- }
- break;
- }
+ final OProfilerHookValue v = hooks.get(k);
+ if (v != null) {
+ final Object hookValue = v.getValue();
+ buffer.append(String.format("\n%-50s | %-65s |", k, hookValue != null ? hookValue.toString() : "null"));
}
}
@@ -451,14 +490,8 @@ public String dumpHookValues() {
}
public Object getHookValue(final String iName) {
- for (Map.Entry<OProfilerHookValue, String> v : hooks.entrySet()) {
- if (v.getValue().equals(iName)) {
- final OProfilerHookValue h = v.getKey();
- if (h != null)
- return h.getValue();
- }
- }
- return null;
+ final OProfilerHookValue v = hooks.get(iName);
+ return v != null ? v.getValue() : null;
}
public String[] getCountersAsString() {
@@ -519,21 +552,18 @@ public OProfilerEntry getChrono(final String iChronoName) {
}
}
- public void registerHookValue(final String iName, final OProfilerHookValue iHookValue) {
+ public void registerHookValue(final String iName, final String iDescription, final METRIC_TYPE iType,
+ final OProfilerHookValue iHookValue) {
unregisterHookValue(iName);
- hooks.put(iHookValue, iName);
+ updateMetadata(iName, iDescription, iType);
+ hooks.put(iName, iHookValue);
}
public void unregisterHookValue(final String iName) {
if (recordingFrom < 0)
return;
- for (Map.Entry<OProfilerHookValue, String> entry : hooks.entrySet()) {
- if (entry.getValue().equals(iName)) {
- hooks.remove(entry.getKey());
- break;
- }
- }
+ hooks.remove(iName);
}
public void setAutoDump(final int iSeconds) {
@@ -559,9 +589,17 @@ protected Map<String, Object> archiveHooks() {
final Map<String, Object> result = new HashMap<String, Object>();
- for (Map.Entry<OProfilerHookValue, String> v : hooks.entrySet())
- result.put(v.getValue(), v.getKey().getValue());
+ for (Map.Entry<String, OProfilerHookValue> v : hooks.entrySet())
+ result.put(v.getKey(), v.getValue().getValue());
return result;
}
+
+ /**
+ * Updates the metric metadata.
+ */
+ protected void updateMetadata(final String iName, final String iDescription, final METRIC_TYPE iType) {
+ if (dictionary.putIfAbsent(iName, iDescription) == null)
+ types.put(iName, iType);
+ }
}
diff --git a/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerData.java b/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerData.java
index d47b27c34cd..f5fbdfa0dc9 100644
--- a/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerData.java
+++ b/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerData.java
@@ -52,6 +52,8 @@ public class OProfilerEntry {
public long max = 0;
public long average = 0;
public long total = 0;
+ public String payLoad;
+ public String description;
public void toJSON(final StringBuilder buffer) {
buffer.append(String.format("\"%s\":{", name));
@@ -61,6 +63,8 @@ public void toJSON(final StringBuilder buffer) {
buffer.append(String.format("\"%s\":%d,", "max", max));
buffer.append(String.format("\"%s\":%d,", "average", average));
buffer.append(String.format("\"%s\":%d", "total", total));
+ if (payLoad != null)
+ buffer.append(String.format("\"%s\":%d", "payload", payLoad));
buffer.append("}");
}
@@ -275,8 +279,8 @@ public String dumpCounters() {
}
}
- public long stopChrono(final String iName, final long iStartTime) {
- return updateEntry(chronos, iName, System.currentTimeMillis() - iStartTime);
+ public long stopChrono(final String iName, final long iStartTime, final String iPayload) {
+ return updateEntry(chronos, iName, System.currentTimeMillis() - iStartTime, iPayload);
}
public String dumpChronos() {
@@ -284,7 +288,7 @@ public String dumpChronos() {
}
public long updateStat(final String iName, final long iValue) {
- return updateEntry(stats, iName, iValue);
+ return updateEntry(stats, iName, iValue, null);
}
public String dumpStats() {
@@ -417,7 +421,8 @@ public OProfilerEntry getChrono(final String iChronoName) {
}
}
- protected synchronized long updateEntry(final Map<String, OProfilerEntry> iValues, final String iName, final long iValue) {
+ protected synchronized long updateEntry(final Map<String, OProfilerEntry> iValues, final String iName, final long iValue,
+ final String iPayload) {
synchronized (iValues) {
OProfilerEntry c = iValues.get(iName);
@@ -428,6 +433,7 @@ protected synchronized long updateEntry(final Map<String, OProfilerEntry> iValue
}
c.name = iName;
+ c.payLoad = iPayload;
c.entries++;
c.last = iValue;
c.total += c.last;
diff --git a/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerMBean.java b/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerMBean.java
index 1dda7eb8795..3108b9f2004 100644
--- a/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerMBean.java
+++ b/commons/src/main/java/com/orientechnologies/common/profiler/OProfilerMBean.java
@@ -19,7 +19,7 @@
public interface OProfilerMBean {
- public void updateCounter(String iStatName, long iPlus);
+ public void updateCounter(String iStatName, String iDescription, long iPlus);
public long getCounter(String iStatName);
@@ -29,7 +29,7 @@ public interface OProfilerMBean {
public long startChrono();
- public long stopChrono(String iName, long iStartTime);
+ public long stopChrono(String iName, String iDescription, long iStartTime);
public String dumpChronos();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java b/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java
index ced33367b78..3a30f3525eb 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java
@@ -18,6 +18,7 @@
import java.util.HashSet;
import java.util.Set;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.id.ORID;
@@ -136,23 +137,29 @@ public int getMaxSize() {
public void startup() {
underlying.startup();
- Orient.instance().getProfiler().registerHookValue(profilerPrefix + "enabled", new OProfilerHookValue() {
- public Object getValue() {
- return isEnabled();
- }
- });
-
- Orient.instance().getProfiler().registerHookValue(profilerPrefix + "current", new OProfilerHookValue() {
- public Object getValue() {
- return getSize();
- }
- });
-
- Orient.instance().getProfiler().registerHookValue(profilerPrefix + "max", new OProfilerHookValue() {
- public Object getValue() {
- return getMaxSize();
- }
- });
+ Orient.instance().getProfiler()
+ .registerHookValue(profilerPrefix + "enabled", "Cache enabled", METRIC_TYPE.ENABLED, new OProfilerHookValue() {
+ public Object getValue() {
+ return isEnabled();
+ }
+ });
+
+ Orient.instance().getProfiler()
+ .registerHookValue(profilerPrefix + "current", "Number of entries in cache", METRIC_TYPE.SIZE, new OProfilerHookValue() {
+ public Object getValue() {
+ return getSize();
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue(profilerPrefix + "max", "Maximum number of entries in cache", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return getMaxSize();
+ }
+ });
}
/**
diff --git a/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel1RecordCache.java b/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel1RecordCache.java
index dbaf91912a3..d93922eb43d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel1RecordCache.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel1RecordCache.java
@@ -107,7 +107,10 @@ record = secondary.retrieveRecord(rid);
underlying.unlock(rid);
}
- Orient.instance().getProfiler().updateCounter(record != null ? CACHE_HIT : CACHE_MISS, 1L);
+ if (record != null)
+ Orient.instance().getProfiler().updateCounter(CACHE_HIT, "Record found in Level1 Cache", 1L);
+ else
+ Orient.instance().getProfiler().updateCounter(CACHE_MISS, "Record not found in Level1 Cache", 1L);
return record;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel2RecordCache.java b/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel2RecordCache.java
index a5098822e1e..bbea14b51ac 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel2RecordCache.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/cache/OLevel2RecordCache.java
@@ -107,7 +107,7 @@ protected ORecordInternal<?> retrieveRecord(final ORID iRID) {
record = underlying.remove(iRID);
if (record == null || record.isDirty()) {
- Orient.instance().getProfiler().updateCounter(CACHE_MISS, 1);
+ Orient.instance().getProfiler().updateCounter(CACHE_MISS, "Record not found in Level2 Cache", +1);
return null;
}
@@ -122,7 +122,7 @@ record = underlying.remove(iRID);
underlying.unlock(iRID);
}
- Orient.instance().getProfiler().updateCounter(CACHE_HIT, 1);
+ Orient.instance().getProfiler().updateCounter(CACHE_HIT, "Record found in Level2 Cache", +1);
return record;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java
index a79c4dc9cd2..78bf420dea5 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java
@@ -96,7 +96,7 @@ private void releaseIndexes(Collection<? extends OIndex<?>> indexesToRelease) {
}
@Override
- public void freeze(boolean throwException) {
+ public void freeze(final boolean throwException) {
if (!(getStorage() instanceof OStorageLocal)) {
OLogManager.instance().error(this,
"We can not freeze non local storage. " + "If you use remote client please use OServerAdmin instead.");
@@ -114,7 +114,7 @@ public void freeze(boolean throwException) {
super.freeze(throwException);
- Orient.instance().getProfiler().stopChrono("document.database.freeze", startTime);
+ Orient.instance().getProfiler().stopChrono("document.database.freeze", "Time to freeze the database", startTime);
}
@Override
@@ -136,7 +136,7 @@ public void freeze() {
super.freeze();
- Orient.instance().getProfiler().stopChrono("document.database.freeze", startTime);
+ Orient.instance().getProfiler().stopChrono("document.database.freeze", "Time to freeze the database", startTime);
}
@Override
@@ -154,7 +154,7 @@ public void release() {
Collection<? extends OIndex<?>> indexes = getMetadata().getIndexManager().getIndexes();
releaseIndexes(indexes);
- Orient.instance().getProfiler().stopChrono("document.database.release", startTime);
+ Orient.instance().getProfiler().stopChrono("document.database.release", "Time to release the database", startTime);
}
/**
@@ -363,7 +363,7 @@ public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iRecor
for (; i < clusterIds.length; ++i)
if (clusterIds[i] == id)
break;
-
+
if (i == clusterIds.length)
throw new IllegalArgumentException("Cluster name " + iClusterName + " is not configured to store the class "
+ doc.getClassName());
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
index 2723a820cd1..a045295f13e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
@@ -32,6 +32,7 @@
import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveExternal;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.common.log.OLogManager;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.orient.core.Orient;
@@ -143,7 +144,8 @@ public OIndexInternal<?> create(final String iName, final OIndexDefinition iInde
iValueSerializer, indexDefinition.getTypes().length, maxUpdatesBeforeSave);
}
} else
- map = new OMVRBTreeDatabaseLazySave<Object, T>(iClusterIndexName, new OSimpleKeySerializer(), iValueSerializer, 1, maxUpdatesBeforeSave);
+ map = new OMVRBTreeDatabaseLazySave<Object, T>(iClusterIndexName, new OSimpleKeySerializer(), iValueSerializer, 1,
+ maxUpdatesBeforeSave);
installHooks(iDatabase);
@@ -720,7 +722,7 @@ protected void installHooks(final ODatabaseRecord iDatabase) {
final OJVMProfiler profiler = Orient.instance().getProfiler();
final String profilerPrefix = profiler.getDatabaseMetric(iDatabase.getName(), "index." + name + '.');
- profiler.registerHookValue(profilerPrefix + "items", new OProfilerHookValue() {
+ profiler.registerHookValue(profilerPrefix + "items", "Index size", METRIC_TYPE.SIZE, new OProfilerHookValue() {
public Object getValue() {
acquireSharedLock();
try {
@@ -731,23 +733,26 @@ public Object getValue() {
}
});
- profiler.registerHookValue(profilerPrefix + "entryPointSize", new OProfilerHookValue() {
- public Object getValue() {
- return map != null ? map.getEntryPointSize() : "-";
- }
- });
+ profiler.registerHookValue(profilerPrefix + "entryPointSize", "Number of entrypoints in an index", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return map != null ? map.getEntryPointSize() : "-";
+ }
+ });
- profiler.registerHookValue(profilerPrefix + "maxUpdateBeforeSave", new OProfilerHookValue() {
- public Object getValue() {
- return map != null ? map.getMaxUpdatesBeforeSave() : "-";
- }
- });
+ profiler.registerHookValue(profilerPrefix + "maxUpdateBeforeSave", "Maximum number of updates in a index before force saving",
+ METRIC_TYPE.SIZE, new OProfilerHookValue() {
+ public Object getValue() {
+ return map != null ? map.getMaxUpdatesBeforeSave() : "-";
+ }
+ });
- profiler.registerHookValue(profilerPrefix + "optimizationThreshold", new OProfilerHookValue() {
- public Object getValue() {
- return map != null ? map.getOptimizeThreshold() : "-";
- }
- });
+ profiler.registerHookValue(profilerPrefix + "optimizationThreshold",
+ "Number of times as threshold to execute a background index optimization", METRIC_TYPE.SIZE, new OProfilerHookValue() {
+ public Object getValue() {
+ return map != null ? map.getOptimizeThreshold() : "-";
+ }
+ });
Orient.instance().getMemoryWatchDog().addListener(watchDog);
iDatabase.registerListener(this);
@@ -921,8 +926,7 @@ public String getDatabaseName() {
}
private int lazyUpdates() {
- return isAutomatic() ?
- OGlobalConfiguration.INDEX_AUTO_LAZY_UPDATES.getValueAsInteger() :
- OGlobalConfiguration.INDEX_MANUAL_LAZY_UPDATES.getValueAsInteger();
+ return isAutomatic() ? OGlobalConfiguration.INDEX_AUTO_LAZY_UPDATES.getValueAsInteger()
+ : OGlobalConfiguration.INDEX_MANUAL_LAZY_UPDATES.getValueAsInteger();
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/memory/OMemoryWatchDog.java b/core/src/main/java/com/orientechnologies/orient/core/memory/OMemoryWatchDog.java
index 92ef9f96c30..b575a75e142 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/memory/OMemoryWatchDog.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/memory/OMemoryWatchDog.java
@@ -23,6 +23,7 @@
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.log.OLogManager;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
@@ -63,11 +64,15 @@ public OMemoryWatchDog() {
}
public void run() {
- Orient.instance().getProfiler().registerHookValue("system.memory.alerts", new OProfilerHookValue() {
- public Object getValue() {
- return alertTimes;
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.memory.alerts", "Number of alerts received by JVM to free memory resources",
+ METRIC_TYPE.COUNTER, new OProfilerHookValue() {
+ public Object getValue() {
+ return alertTimes;
+ }
+ });
while (true) {
try {
@@ -96,7 +101,7 @@ public Object getValue() {
}
}
- Orient.instance().getProfiler().stopChrono("OMemoryWatchDog.freeResources", timer);
+ Orient.instance().getProfiler().stopChrono("OMemoryWatchDog.freeResources", "WatchDog free resources", timer);
} catch (Exception e) {
} finally {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadata.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadata.java
index ce69fde9ab8..1bc3f51b6a0 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadata.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadata.java
@@ -66,7 +66,8 @@ public void load() {
if (schemaClusterId == -1 || getDatabase().countClusterElements(CLUSTER_INTERNAL_NAME) == 0)
return;
} finally {
- PROFILER.stopChrono(PROFILER.getDatabaseMetric(getDatabase().getName(), "metadata.load"), timer);
+ PROFILER.stopChrono(PROFILER.getDatabaseMetric(getDatabase().getName(), "metadata.load"), "Loading of database metadata",
+ timer);
}
}
@@ -168,7 +169,7 @@ public void reload() {
schema.reload();
indexManager.load();
security.load();
- //functionLibrary.load();
+ // functionLibrary.load();
}
/**
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/function/OFunction.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/function/OFunction.java
index 87bd31aaeaa..962b0244455 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/function/OFunction.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/function/OFunction.java
@@ -151,8 +151,11 @@ public Object execute(final Map<Object, Object> iArgs) {
final Object result = command.execute(iArgs);
if (Orient.instance().getProfiler().isRecording())
- Orient.instance().getProfiler()
- .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".function.execute", start);
+ Orient
+ .instance()
+ .getProfiler()
+ .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".function.execute",
+ "Time to execute a function", start);
return result;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java b/core/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java
index 3fbe0e18913..4850208431b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java
@@ -34,60 +34,64 @@ public class OJVMProfiler extends OProfiler implements OMemoryWatchDog.Listener
private final int metricProcessors = Runtime.getRuntime().availableProcessors();
public OJVMProfiler() {
- registerHookValue(getSystemMetric("config.cpus"), new OProfilerHookValue() {
+ registerHookValue(getSystemMetric("config.cpus"), "Number of CPUs", METRIC_TYPE.COUNTER, new OProfilerHookValue() {
@Override
public Object getValue() {
return metricProcessors;
}
});
- registerHookValue(getSystemMetric("config.os.name"), new OProfilerHookValue() {
+ registerHookValue(getSystemMetric("config.os.name"), "Operative System name", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("os.name");
}
});
- registerHookValue(getSystemMetric("config.os.version"), new OProfilerHookValue() {
+ registerHookValue(getSystemMetric("config.os.version"), "Operative System version", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("os.version");
}
});
- registerHookValue(getSystemMetric("config.os.arch"), new OProfilerHookValue() {
- @Override
- public Object getValue() {
- return System.getProperty("os.arch");
- }
- });
- registerHookValue(getSystemMetric("config.java.vendor"), new OProfilerHookValue() {
+ registerHookValue(getSystemMetric("config.os.arch"), "Operative System architecture", METRIC_TYPE.TEXT,
+ new OProfilerHookValue() {
+ @Override
+ public Object getValue() {
+ return System.getProperty("os.arch");
+ }
+ });
+ registerHookValue(getSystemMetric("config.java.vendor"), "Java vendor", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("java.vendor");
}
});
- registerHookValue(getSystemMetric("config.java.version"), new OProfilerHookValue() {
+ registerHookValue(getSystemMetric("config.java.version"), "Java version", METRIC_TYPE.TEXT, new OProfilerHookValue() {
@Override
public Object getValue() {
return System.getProperty("java.version");
}
});
- registerHookValue(getProcessMetric("runtime.availableMemory"), new OProfilerHookValue() {
- @Override
- public Object getValue() {
- return Runtime.getRuntime().freeMemory();
- }
- });
- registerHookValue(getProcessMetric("runtime.maxMemory"), new OProfilerHookValue() {
- @Override
- public Object getValue() {
- return Runtime.getRuntime().maxMemory();
- }
- });
- registerHookValue(getProcessMetric("runtime.totalMemory"), new OProfilerHookValue() {
- @Override
- public Object getValue() {
- return Runtime.getRuntime().totalMemory();
- }
- });
+ registerHookValue(getProcessMetric("runtime.availableMemory"), "Available memory for the process", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ @Override
+ public Object getValue() {
+ return Runtime.getRuntime().freeMemory();
+ }
+ });
+ registerHookValue(getProcessMetric("runtime.maxMemory"), "Maximum memory usable for the process", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ @Override
+ public Object getValue() {
+ return Runtime.getRuntime().maxMemory();
+ }
+ });
+ registerHookValue(getProcessMetric("runtime.totalMemory"), "Total memory used by the process", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ @Override
+ public Object getValue() {
+ return Runtime.getRuntime().totalMemory();
+ }
+ });
final File[] roots = File.listRoots();
for (final File root : roots) {
@@ -98,21 +102,21 @@ public Object getValue() {
final String metricPrefix = "system.disk." + volumeName;
- registerHookValue(metricPrefix + ".totalSpace", new OProfilerHookValue() {
+ registerHookValue(metricPrefix + ".totalSpace", "Total used disk space", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return root.getTotalSpace();
}
});
- registerHookValue(metricPrefix + ".freeSpace", new OProfilerHookValue() {
+ registerHookValue(metricPrefix + ".freeSpace", "Total free disk space", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return root.getFreeSpace();
}
});
- registerHookValue(metricPrefix + ".usableSpace", new OProfilerHookValue() {
+ registerHookValue(metricPrefix + ".usableSpace", "Total usable disk space", METRIC_TYPE.SIZE, new OProfilerHookValue() {
@Override
public Object getValue() {
return root.getUsableSpace();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/OMemoryStream.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/OMemoryStream.java
index 87b40c16aa4..852cda87ce9 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/OMemoryStream.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/OMemoryStream.java
@@ -19,6 +19,7 @@
import java.io.OutputStream;
import java.util.Arrays;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.common.util.OArrays;
import com.orientechnologies.orient.core.Orient;
@@ -39,11 +40,15 @@ public class OMemoryStream extends OutputStream {
private static long metricResize = 0;
static {
- Orient.instance().getProfiler().registerHookValue("system.memory.stream.resize", new OProfilerHookValue() {
- public Object getValue() {
- return metricResize;
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.memory.stream.resize", "Number of resizes of memory stream buffer", METRIC_TYPE.COUNTER,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricResize;
+ }
+ });
}
public OMemoryStream() {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
index bd58e6814cd..0e319456138 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
@@ -245,7 +245,7 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
if (link != null)
// OVERWRITE CONTENT
iRecord.field(iName, link);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), "Serialize link to string", timer);
}
break;
}
@@ -255,7 +255,8 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
if (iValue instanceof ORecordLazyList && ((ORecordLazyList) iValue).getStreamedContent() != null) {
iOutput.append(((ORecordLazyList) iValue).getStreamedContent());
- PROFILER.updateCounter(PROFILER.getProcessMetric("serializer.record.string.linkList2string.cached"), +1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("serializer.record.string.linkList2string.cached"),
+ "Serialize linklist to string in stream mode", +1);
} else {
final ORecordLazyList coll;
final Iterator<OIdentifiable> it;
@@ -273,7 +274,8 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
if (coll.getStreamedContent() != null) {
// APPEND STREAMED CONTENT
iOutput.append(coll.getStreamedContent());
- PROFILER.updateCounter(PROFILER.getProcessMetric("serializer.record.string.linkList2string.cached"), +1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("serializer.record.string.linkList2string.cached"),
+ "Serialize linklist to string in stream mode", +1);
it = coll.newItemsIterator();
} else
it = coll.rawIterator();
@@ -302,7 +304,8 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
}
iOutput.append(OStringSerializerHelper.COLLECTION_END);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkList2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkList2string"), "Serialize linklist to string",
+ timer);
break;
}
@@ -320,7 +323,8 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
coll = (OMVRBTreeRIDSet) iValue;
linkSetToStream(iOutput, iRecord, coll);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkSet2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkSet2string"), "Serialize linkset to string",
+ timer);
break;
}
@@ -366,7 +370,8 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
}
iOutput.append(OStringSerializerHelper.MAP_END);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkMap2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkMap2string"), "Serialize linkmap to string",
+ timer);
break;
}
@@ -377,22 +382,26 @@ public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput,
iOutput.append(OStringSerializerHelper.EMBEDDED_END);
} else if (iValue != null)
iOutput.append(iValue.toString());
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), timer);
+ PROFILER
+ .stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), "Serialize embedded to string", timer);
break;
case EMBEDDEDLIST:
embeddedCollectionToStream(null, iObjHandler, iOutput, iLinkedClass, iLinkedType, iValue, iMarshalledRecords, iSaveOnlyDirty);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"),
+ "Serialize embeddedlist to string", timer);
break;
case EMBEDDEDSET:
embeddedCollectionToStream(null, iObjHandler, iOutput, iLinkedClass, iLinkedType, iValue, iMarshalledRecords, iSaveOnlyDirty);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), "Serialize embeddedset to string",
+ timer);
break;
case EMBEDDEDMAP: {
embeddedMapToStream(null, iObjHandler, iOutput, iLinkedClass, iLinkedType, iValue, iMarshalledRecords, iSaveOnlyDirty);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), "Serialize embeddedmap to string",
+ timer);
break;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerStringAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerStringAbstract.java
index 625a40922b3..e5cb2dd33c6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerStringAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerStringAbstract.java
@@ -79,7 +79,8 @@ public ORecordInternal<?> fromStream(final byte[] iSource, final ORecordInternal
return fromString(OBinaryProtocol.bytes2string(iSource), iRecord, iFields);
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.fromStream"), timer);
+ PROFILER
+ .stopChrono(PROFILER.getProcessMetric("serializer.record.string.fromStream"), "Deserialize record from stream", timer);
}
}
@@ -91,7 +92,7 @@ public byte[] toStream(final ORecordInternal<?> iRecord, boolean iOnlyDelta) {
OSerializationLongIdThreadLocal.INSTANCE.get(), iOnlyDelta, true).toString());
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.toStream"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.toStream"), "Serialize record to stream", timer);
}
}
@@ -165,62 +166,64 @@ public static void fieldTypeToString(final StringBuilder iBuffer, OType iType, f
switch (iType) {
case STRING:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.string2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.string2string"), "Serialize string to string", timer);
break;
case BOOLEAN:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.bool2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.bool2string"), "Serialize boolean to string", timer);
break;
case INTEGER:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.int2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.int2string"), "Serialize integer to string", timer);
break;
case FLOAT:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.float2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.float2string"), "Serialize float to string", timer);
break;
case DECIMAL:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.decimal2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.decimal2string"), "Serialize decimal to string",
+ timer);
break;
case LONG:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.long2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.long2string"), "Serialize long to string", timer);
break;
case DOUBLE:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.double2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.double2string"), "Serialize double to string", timer);
break;
case SHORT:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.short2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.short2string"), "Serialize short to string", timer);
break;
case BYTE:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.byte2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.byte2string"), "Serialize byte to string", timer);
break;
case BINARY:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.binary2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.binary2string"), "Serialize binary to string", timer);
break;
case DATE:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.date2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.date2string"), "Serialize date to string", timer);
break;
case DATETIME:
simpleValueToStream(iBuffer, iType, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.datetime2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.datetime2string"), "Serialize datetime to string",
+ timer);
break;
case LINK:
@@ -228,35 +231,39 @@ public static void fieldTypeToString(final StringBuilder iBuffer, OType iType, f
((ORecordId) iValue).toString(iBuffer);
else
((ORecord<?>) iValue).getIdentity().toString(iBuffer);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), "Serialize link to string", timer);
break;
case EMBEDDEDSET:
ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
null, iBuffer, null, null, iValue, null, true);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), "Serialize embeddedset to string",
+ timer);
break;
case EMBEDDEDLIST:
ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
null, iBuffer, null, null, iValue, null, true);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"),
+ "Serialize embeddedlist to string", timer);
break;
case EMBEDDEDMAP:
ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null,
iBuffer, null, null, iValue, null, true);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), "Serialize embeddedmap to string",
+ timer);
break;
case EMBEDDED:
OStringSerializerEmbedded.INSTANCE.toStream(iBuffer, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), timer);
+ PROFILER
+ .stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), "Serialize embedded to string", timer);
break;
case CUSTOM:
OStringSerializerAnyStreamable.INSTANCE.toStream(iBuffer, iValue);
- PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.custom2string"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.custom2string"), "Serialize custom to string", timer);
break;
default:
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexProxy.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexProxy.java
index d943a5a3c75..877353beb90 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexProxy.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexProxy.java
@@ -361,13 +361,15 @@ private void updateStatistic(OIndex<?> index) {
final OJVMProfiler profiler = Orient.instance().getProfiler();
if (profiler.isRecording()) {
- Orient.instance().getProfiler().updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), 1);
+ Orient.instance().getProfiler()
+ .updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), "Used index in query", +1);
final int paramCount = index.getDefinition().getParamCount();
if (paramCount > 1) {
final String profiler_prefix = profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed");
- profiler.updateCounter(profiler_prefix, 1);
- profiler.updateCounter(profiler_prefix + "." + paramCount, 1);
+ profiler.updateCounter(profiler_prefix, "Used composite index in query", +1);
+ profiler.updateCounter(profiler_prefix + "." + paramCount, "Used composite index in query with " + paramCount + " params",
+ +1);
}
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperator.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperator.java
index f569a69665a..b4b3ade7f36 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperator.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperator.java
@@ -212,15 +212,16 @@ protected void updateProfiler(final OCommandContext iContext, final OIndex<?> in
final OJVMProfiler profiler = Orient.instance().getProfiler();
if (profiler.isRecording()) {
- profiler.updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), +1);
+ profiler.updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), "Used index in query", +1);
int params = indexDefinition.getParamCount();
if (params > 1) {
final String profiler_prefix = profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed");
- profiler.updateCounter(profiler_prefix, 1);
- profiler.updateCounter(profiler_prefix + "." + params, 1);
- profiler.updateCounter(profiler_prefix + "." + params + '.' + keyParams.size(), 1);
+ profiler.updateCounter(profiler_prefix, "Used composite index in query", +1);
+ profiler.updateCounter(profiler_prefix + "." + params, "Used composite index in query with " + params + " params", +1);
+ profiler.updateCounter(profiler_prefix + "." + params + '.' + keyParams.size(), "Used composite index in query with "
+ + params + " params and " + keyParams.size() + " keys", +1);
}
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
index 09c69c82fe1..20b2a420f59 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
@@ -100,8 +100,11 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE
throw new OCommandExecutionException("Error on execution of command: " + iCommand, e);
} finally {
- Orient.instance().getProfiler()
- .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.getText(), beginTime);
+ Orient
+ .instance()
+ .getProfiler()
+ .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.getText(),
+ "Execution of command", beginTime);
}
}
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 0bb4f0b43c1..1d7ab3d53c3 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
@@ -26,6 +26,7 @@
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.common.util.OByteBufferUtils;
import com.orientechnologies.orient.core.Orient;
@@ -61,21 +62,33 @@ public class OFileMMap extends OAbstractFile {
private static long metricNonPooledBufferUsed = 0;
static {
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.pooledBufferCreated", new OProfilerHookValue() {
- public Object getValue() {
- return metricPooledBufferCreated;
- }
- });
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.pooledBufferUsed", new OProfilerHookValue() {
- public Object getValue() {
- return metricPooledBufferUsed;
- }
- });
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.nonPooledBufferUsed", new OProfilerHookValue() {
- public Object getValue() {
- return metricNonPooledBufferUsed;
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.pooledBufferCreated", "Number of file buffers created", METRIC_TYPE.COUNTER,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricPooledBufferCreated;
+ }
+ });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.pooledBufferUsed", "Number of times a file buffers has been reused",
+ METRIC_TYPE.COUNTER, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricPooledBufferUsed;
+ }
+ });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.nonPooledBufferUsed", "Number of times a file buffers has not been reused",
+ METRIC_TYPE.COUNTER, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricNonPooledBufferUsed;
+ }
+ });
}
@Override
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapBufferEntry.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapBufferEntry.java
index d43703a7964..1d417a9e5b6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapBufferEntry.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapBufferEntry.java
@@ -89,9 +89,9 @@ boolean flush() {
if (dirty)
OLogManager.instance().debug(this, "Cannot commit memory buffer to disk after %d retries", FORCE_RETRY);
else
- PROFILER.updateCounter(PROFILER.getProcessMetric("file.mmap.pagesCommitted"), +1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("file.mmap.pagesCommitted"), "Memory mapped pages committed to disk", +1);
- PROFILER.stopChrono(PROFILER.getProcessMetric("file.mmap.commitPages"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("file.mmap.commitPages"), "Commit memory mapped pages to disk", timer);
return !dirty;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerNew.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerNew.java
index e721884e808..d1308807006 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerNew.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerNew.java
@@ -21,6 +21,7 @@
import java.util.concurrent.ConcurrentHashMap;
import com.orientechnologies.common.concur.lock.OLockManager;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
@@ -48,16 +49,24 @@ public class OMMapManagerNew extends OMMapManagerAbstract implements OMMapManage
private long metricReusedPages = 0;
public void init() {
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.mappedPages", new OProfilerHookValue() {
- public Object getValue() {
- return metricMappedPages;
- }
- });
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.reusedPages", new OProfilerHookValue() {
- public Object getValue() {
- return metricReusedPages;
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.mappedPages", "Number of memory mapped pages used", METRIC_TYPE.COUNTER,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricMappedPages;
+ }
+ });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.reusedPages", "Number of times memory mapped pages have been reused",
+ METRIC_TYPE.TIMES, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricReusedPages;
+ }
+ });
}
/**
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerOld.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerOld.java
index 9a3930b157d..fca60dddd1b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerOld.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerOld.java
@@ -29,6 +29,7 @@
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
@@ -66,68 +67,110 @@ public void init() {
maxMemory = OGlobalConfiguration.FILE_MMAP_MAX_MEMORY.getValueAsLong();
setOverlapStrategy(OGlobalConfiguration.FILE_MMAP_OVERLAP_STRATEGY.getValueAsInteger());
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.totalMemory", new OProfilerHookValue() {
- public Object getValue() {
- return totalMemory;
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.maxMemory", new OProfilerHookValue() {
- public Object getValue() {
- return maxMemory;
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.blockSize", new OProfilerHookValue() {
- public Object getValue() {
- return blockSize;
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.blocks", new OProfilerHookValue() {
- public Object getValue() {
- lock.readLock().lock();
- try {
- return bufferPoolLRU.size();
- } finally {
- lock.readLock().unlock();
- }
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.alloc.strategy", new OProfilerHookValue() {
- public Object getValue() {
- return lastStrategy;
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.overlap.strategy", new OProfilerHookValue() {
- public Object getValue() {
- return overlapStrategy;
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.usedChannel", new OProfilerHookValue() {
- public Object getValue() {
- return metricUsedChannel;
- }
- });
-
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.reusedPagesBetweenLast", new OProfilerHookValue() {
- public Object getValue() {
- return metricReusedPagesBetweenLast;
- }
- });
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.reusedPages", new OProfilerHookValue() {
- public Object getValue() {
- return metricReusedPages;
- }
- });
- Orient.instance().getProfiler().registerHookValue("system.file.mmap.overlappedPageUsingChannel", new OProfilerHookValue() {
- public Object getValue() {
- return metricOverlappedPageUsingChannel;
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.totalMemory", "Total memory used by memory mapping", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return totalMemory;
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.maxMemory", "Maximum memory usable by memory mapping", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return maxMemory;
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.blockSize", "Total block size used for memory mapping", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return blockSize;
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.blocks", "Total memory used by memory mapping", METRIC_TYPE.COUNTER,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ lock.readLock().lock();
+ try {
+ return bufferPoolLRU.size();
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.alloc.strategy", "Memory mapping allocation strategy", METRIC_TYPE.TEXT,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return lastStrategy;
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.overlap.strategy", "Memory mapping overlapping strategy", METRIC_TYPE.TEXT,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return overlapStrategy;
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.usedChannel",
+ "Number of times the memory mapping has been bypassed to use direct file channel", METRIC_TYPE.TIMES,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricUsedChannel;
+ }
+ });
+
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.reusedPagesBetweenLast",
+ "Number of times a memory mapped page has been reused in short time", METRIC_TYPE.TIMES, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricReusedPagesBetweenLast;
+ }
+ });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.reusedPages", "Number of times a memory mapped page has been reused",
+ METRIC_TYPE.TIMES, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricReusedPages;
+ }
+ });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("system.file.mmap.overlappedPageUsingChannel",
+ "Number of times a direct file channel access has been used because overlapping", METRIC_TYPE.TIMES,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricOverlappedPageUsingChannel;
+ }
+ });
}
public OMMapBufferEntry[] acquire(final OFileMMap iFile, final long iBeginOffset, final int iSize,
@@ -479,7 +522,7 @@ private static OMMapBufferEntry mapBuffer(final OFileMMap iFile, final long iBeg
try {
return new OMMapBufferEntry(iFile, iFile.map(iBeginOffset, iSize), iBeginOffset, iSize);
} finally {
- Orient.instance().getProfiler().stopChrono("OMMapManager.loadPage", timer);
+ Orient.instance().getProfiler().stopChrono("OMMapManager.loadPage", "Load a memory mapped page in memory", timer);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocal.java
index 119a9ef0ef2..97de75e7bc3 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocal.java
@@ -325,7 +325,7 @@ public long setRecord(final long iPosition, final ORecordId iRid, final byte[] i
// USE THE OLD SPACE SINCE SIZE ISN'T CHANGED
file.write(pos[1] + RECORD_FIX_SIZE, iContent);
- Orient.instance().getProfiler().updateCounter(PROFILER_UPDATE_REUSED_ALL, +1);
+ Orient.instance().getProfiler().updateCounter(PROFILER_UPDATE_REUSED_ALL, "", +1);
return iPosition;
} else if (recordSize - contentLength > RECORD_FIX_SIZE + 50) {
// USE THE OLD SPACE BUT UPDATE THE CURRENT SIZE. IT'S PREFEREABLE TO USE THE SAME INSTEAD OF FINDING A BEST SUITED FOR IT
@@ -335,7 +335,8 @@ public long setRecord(final long iPosition, final ORecordId iRid, final byte[] i
// CREATE A HOLE WITH THE DIFFERENCE OF SPACE
createHole(iPosition + RECORD_FIX_SIZE + contentLength, recordSize - contentLength - RECORD_FIX_SIZE);
- Orient.instance().getProfiler().updateCounter(PROFILER_UPDATE_REUSED_PARTIAL, +1);
+ Orient.instance().getProfiler()
+ .updateCounter(PROFILER_UPDATE_REUSED_PARTIAL, "Space reused partially in data segment during record update", +1);
} else {
// CREATE A HOLE FOR THE ENTIRE OLD RECORD
createHole(iPosition, recordSize);
@@ -344,7 +345,8 @@ public long setRecord(final long iPosition, final ORecordId iRid, final byte[] i
pos = getFreeSpace(contentLength + RECORD_FIX_SIZE);
writeRecord(pos, iRid.clusterId, iRid.clusterPosition, iContent);
- Orient.instance().getProfiler().updateCounter(PROFILER_UPDATE_NOT_REUSED, +1);
+ Orient.instance().getProfiler()
+ .updateCounter(PROFILER_UPDATE_NOT_REUSED, "Space not reused in data segment during record update", +1);
}
return getAbsolutePosition(pos);
@@ -430,7 +432,7 @@ private void createHole(final long iRecordOffset, final int iRecordSize) throws
final ODataHoleInfo closestHole = getCloserHole(iRecordOffset, iRecordSize, file, pos);
- Orient.instance().getProfiler().stopChrono(PROFILER_HOLE_FIND_CLOSER, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_HOLE_FIND_CLOSER, "Time to find the closer hole in data segment", timer);
if (closestHole == null)
// CREATE A NEW ONE
@@ -461,7 +463,7 @@ else if (closestHole.dataOffset + closestHole.size == iRecordOffset) {
files[(int) pos[0]].writeInt(pos[1], holeSize * -1);
} finally {
- Orient.instance().getProfiler().stopChrono(PROFILER_HOLE_CREATE, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_HOLE_CREATE, "Time to create the hole in data segment", timer);
}
}
@@ -564,7 +566,7 @@ else if (sizeMoved != item[1])
final long[] pos = getRelativePosition(holePositionOffset);
files[(int) pos[0]].writeInt(pos[1], holeSize * -1);
- Orient.instance().getProfiler().stopChrono(PROFILER_HOLE_CREATE, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_HOLE_CREATE, "Time to create the hole in data segment", timer);
}
private ODataHoleInfo getCloserHole(final long iRecordOffset, final int iRecordSize, final OFile file, final long[] pos) {
@@ -631,7 +633,7 @@ private int moveRecord(final long iSourcePosition, final long iDestinationPositi
writeRecord(getRelativePosition(iDestinationPosition), clusterId, clusterPosition, content);
- Orient.instance().getProfiler().stopChrono(PROFILER_MOVE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_MOVE_RECORD, "Time to move a chunk in data segment", timer);
return recordSize + RECORD_FIX_SIZE;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocalHole.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocalHole.java
index 75df511bd6b..e096e3be1a7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocalHole.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODataLocalHole.java
@@ -126,7 +126,7 @@ public synchronized void createHole(final long iRecordOffset, final int iRecordS
file.writeLong(p, iRecordOffset);
file.writeInt(p + OBinaryProtocol.SIZE_LONG, iRecordSize);
- Orient.instance().getProfiler().stopChrono(PROFILER_DATA_HOLE_CREATE, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_DATA_HOLE_CREATE, "Time to create a hole in data segment", timer);
}
public synchronized ODataHoleInfo getCloserHole(final long iHolePosition, final int iHoleSize, final long iLowerRange,
@@ -185,7 +185,8 @@ protected synchronized long popFirstAvailableHole(final int iRecordSize) throws
ODataHoleInfo hole = availableHolesBySize.get(cursor);
if (hole != null && hole.size == iRecordSize) {
// PERFECT MATCH: DELETE THE HOLE
- Orient.instance().getProfiler().stopChrono(PROFILER_DATA_RECYCLED_COMPLETE, timer);
+ Orient.instance().getProfiler()
+ .stopChrono(PROFILER_DATA_RECYCLED_COMPLETE, "Time to recycle the hole space completely in data segment", timer);
final long pos = hole.dataOffset;
deleteHole(hole.holeOffset);
return pos;
@@ -196,13 +197,15 @@ protected synchronized long popFirstAvailableHole(final int iRecordSize) throws
if (hole.size > iRecordSize + ODataLocal.RECORD_FIX_SIZE + 50) {
// GOOD MATCH SINCE THE HOLE IS BIG ENOUGH ALSO FOR ANOTHER RECORD: UPDATE THE HOLE WITH THE DIFFERENCE
final long pos = hole.dataOffset;
- Orient.instance().getProfiler().stopChrono(PROFILER_DATA_RECYCLED_PARTIAL, timer);
+ Orient.instance().getProfiler()
+ .stopChrono(PROFILER_DATA_RECYCLED_PARTIAL, "Time to recycle the hole space partially in data segment", timer);
updateHole(hole, hole.dataOffset + iRecordSize, hole.size - iRecordSize);
return pos;
}
}
- Orient.instance().getProfiler().stopChrono(PROFILER_DATA_RECYCLED_NOTFOUND, timer);
+ Orient.instance().getProfiler()
+ .stopChrono(PROFILER_DATA_RECYCLED_NOTFOUND, "Time to recycle a hole space in data segment, but without luck", timer);
return -1;
}
@@ -260,7 +263,8 @@ public synchronized void updateHole(final ODataHoleInfo iHole, final long iNewDa
if (sizeChanged)
file.writeInt(holePosition + OBinaryProtocol.SIZE_LONG, iNewRecordSize);
- Orient.instance().getProfiler().stopChrono(PROFILER_DATA_HOLE_UPDATE, timer);
+ Orient.instance().getProfiler()
+.stopChrono(PROFILER_DATA_HOLE_UPDATE, "Time to update a hole in data segment", timer);
}
/**
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 c52f99f746e..a9f44d8614f 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
@@ -32,6 +32,7 @@
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.parser.OSystemVariableResolver;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.common.util.OArrays;
import com.orientechnologies.orient.core.Orient;
@@ -205,7 +206,7 @@ public synchronized void open(final String iUserName, final String iUserPassword
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".open", timer);
+ Orient.instance().getProfiler().stopChrono("db." + name + ".open", "Open a local database", timer);
}
}
@@ -288,7 +289,7 @@ public void create(final Map<String, Object> iProperties) {
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".create", timer);
+ Orient.instance().getProfiler().stopChrono("db." + name + ".create", "Create a local database", timer);
}
}
@@ -345,7 +346,7 @@ public void close(final boolean iForce) {
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".close", timer);
+ Orient.instance().getProfiler().stopChrono("db." + name + ".close", "Close a local database", timer);
}
}
@@ -420,7 +421,7 @@ public void delete() {
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".delete", timer);
+ Orient.instance().getProfiler().stopChrono("db." + name + ".drop", "Drop a local database", timer);
}
}
@@ -694,7 +695,7 @@ public ODataLocal getDataSegmentById(final int iDataSegmentId) {
try {
if (iDataSegmentId >= dataSegments.length)
- throw new IllegalArgumentException("Data segment #" + iDataSegmentId + " does not exist in storage '" + name + "'");
+ throw new IllegalArgumentException("Data segment #" + iDataSegmentId + " does not exist in database '" + name + "'");
return dataSegments[iDataSegmentId];
@@ -716,7 +717,7 @@ public int getDataSegmentIdByName(final String iDataSegmentName) {
if (d != null && d.getName().equalsIgnoreCase(iDataSegmentName))
return d.getId();
}
- throw new IllegalArgumentException("Data segment '" + iDataSegmentName + "' does not exist in storage '" + name + "'");
+ throw new IllegalArgumentException("Data segment '" + iDataSegmentName + "' does not exist in database '" + name + "'");
} finally {
lock.releaseSharedLock();
@@ -823,7 +824,7 @@ public boolean dropCluster(final int iClusterId) {
if (iClusterId < 0 || iClusterId >= clusters.length)
throw new IllegalArgumentException("Cluster id '" + iClusterId + "' is outside the of range of configured clusters (0-"
- + (clusters.length - 1) + ") in storage '" + name + "'");
+ + (clusters.length - 1) + ") in database '" + name + "'");
final OCluster cluster = clusters[iClusterId];
if (cluster == null)
@@ -887,7 +888,7 @@ public long count(final int[] iClusterIds) {
for (int i = 0; i < iClusterIds.length; ++i) {
if (iClusterIds[i] >= clusters.length)
- throw new OConfigurationException("Cluster id " + iClusterIds[i] + " was not found in storage '" + name + "'");
+ throw new OConfigurationException("Cluster id " + iClusterIds[i] + " was not found in database '" + name + "'");
if (iClusterIds[i] > -1) {
final OCluster c = clusters[iClusterIds[i]];
@@ -922,7 +923,7 @@ public long[] getClusterDataRange(final int iClusterId) {
public long count(final int iClusterId) {
if (iClusterId == -1)
- throw new OStorageException("Cluster Id " + iClusterId + " is invalid in storage '" + name + "'");
+ throw new OStorageException("Cluster Id " + iClusterId + " is invalid in database '" + name + "'");
// COUNT PHYSICAL CLUSTER IF ANY
checkOpeness();
@@ -1174,7 +1175,7 @@ public void synch() {
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".synch", timer);
+ Orient.instance().getProfiler().stopChrono("db." + name + ".synch", "Synch a local database", timer);
}
}
@@ -1199,7 +1200,7 @@ protected void synchRecordUpdate(final OCluster cluster, final OPhysicalPosition
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + "record.synch", timer);
+ Orient.instance().getProfiler().stopChrono("db." + name + "record.synch", "Synch a record to local database", timer);
}
}
@@ -1324,7 +1325,7 @@ public OCluster getClusterByName(final String iClusterName) {
final OCluster cluster = clusterMap.get(iClusterName.toLowerCase());
if (cluster == null)
- throw new IllegalArgumentException("Cluster " + iClusterName + " does not exist in storage '" + name + "'");
+ throw new IllegalArgumentException("Cluster " + iClusterName + " does not exist in database '" + name + "'");
return cluster;
} finally {
@@ -1478,7 +1479,7 @@ private int registerCluster(final OCluster iCluster) throws IOException {
// CHECK FOR DUPLICATION OF NAMES
if (clusterMap.containsKey(iCluster.getName()))
throw new OConfigurationException("Cannot add segment '" + iCluster.getName()
- + "' because it is already registered in storage '" + name + "'");
+ + "' because it is already registered in database '" + name + "'");
// CREATE AND ADD THE NEW REF SEGMENT
clusterMap.put(iCluster.getName(), iCluster);
id = iCluster.getId();
@@ -1493,7 +1494,7 @@ private int registerCluster(final OCluster iCluster) throws IOException {
private void checkClusterSegmentIndexRange(final int iClusterId) {
if (iClusterId > clusters.length - 1)
- throw new IllegalArgumentException("Cluster segment #" + iClusterId + " does not exist in storage '" + name + "'");
+ throw new IllegalArgumentException("Cluster segment #" + iClusterId + " does not exist in database '" + name + "'");
}
protected OPhysicalPosition createRecord(final ODataLocal iDataSegment, final OCluster iClusterSegment, final byte[] iContent,
@@ -1555,7 +1556,7 @@ protected OPhysicalPosition createRecord(final ODataLocal iDataSegment, final OC
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_CREATE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_CREATE_RECORD, "Create a record in local database", timer);
}
}
@@ -1600,7 +1601,8 @@ public void changeRecordIdentity(ORID originalId, ORID newId) {
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".changeRecordIdentity", timer);
+ Orient.instance().getProfiler()
+ .stopChrono("db." + name + ".changeRecordIdentity", "Change the identity of a record in local database", timer);
}
}
@@ -1612,7 +1614,8 @@ public boolean isLHClustersAreUsed() {
@Override
protected ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock) {
if (iRid.clusterPosition < 0)
- throw new IllegalArgumentException("Cannot read record " + iRid + " since the position is invalid in storage '" + name + '\'');
+ throw new IllegalArgumentException("Cannot read record " + iRid + " since the position is invalid in database '" + name
+ + '\'');
// NOT FOUND: SEARCH IT IN THE STORAGE
final long timer = Orient.instance().getProfiler().startChrono();
@@ -1648,7 +1651,7 @@ protected ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId
if (iAtomicLock)
lock.releaseSharedLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_READ_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_READ_RECORD, "Read a record from local database", timer);
}
}
@@ -1732,7 +1735,7 @@ protected OPhysicalPosition updateRecord(final OCluster iClusterSegment, final O
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_UPDATE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_UPDATE_RECORD, "Update a record to local database", timer);
}
return null;
@@ -1777,23 +1780,31 @@ protected OPhysicalPosition deleteRecord(final OCluster iClusterSegment, final O
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_DELETE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_DELETE_RECORD, "Delete a record from local database", timer);
}
return null;
}
private void installProfilerHooks() {
- Orient.instance().getProfiler().registerHookValue("db." + name + ".data.holes", new OProfilerHookValue() {
- public Object getValue() {
- return getHoles();
- }
- });
- Orient.instance().getProfiler().registerHookValue("db." + name + ".data.holeSize", new OProfilerHookValue() {
- public Object getValue() {
- return getHoleSize();
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("db." + name + ".data.holes", "Number of the holes in local database", METRIC_TYPE.COUNTER,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return getHoles();
+ }
+ });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("db." + name + ".data.holeSize", "Size of the holes in local database", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return getHoleSize();
+ }
+ });
}
private void formatMessage(final boolean iVerbose, final OCommandOutputListener iListener, final String iMessage,
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 621e7783ecd..8347cf10fd3 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
@@ -307,7 +307,7 @@ public OStorageOperationResult<OPhysicalPosition> createRecord(final int iDataSe
} finally {
lock.releaseSharedLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_CREATE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_CREATE_RECORD, "Create a record in memory database", timer);
}
}
@@ -350,7 +350,7 @@ protected ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId
} finally {
lock.releaseSharedLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_READ_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_READ_RECORD, "Read a record from memory database", timer);
}
}
@@ -403,7 +403,7 @@ public OStorageOperationResult<Integer> updateRecord(final ORecordId iRid, final
} finally {
lock.releaseSharedLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_UPDATE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_UPDATE_RECORD, "Update a record to memory database", timer);
}
}
@@ -453,7 +453,7 @@ public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRid, final
} finally {
lock.releaseSharedLock();
- Orient.instance().getProfiler().stopChrono(PROFILER_DELETE_RECORD, timer);
+ Orient.instance().getProfiler().stopChrono(PROFILER_DELETE_RECORD, "Delete a record from memory database", timer);
}
}
@@ -707,7 +707,8 @@ public void changeRecordIdentity(ORID originalId, ORID newId) {
} finally {
lock.releaseExclusiveLock();
- Orient.instance().getProfiler().stopChrono("db." + name + ".changeRecordIdentity", timer);
+ Orient.instance().getProfiler()
+ .stopChrono("db." + name + ".changeRecordIdentity", "Change the identity of a record in memory database", timer);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
index e71fd46de48..96035e85752 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
@@ -215,7 +215,7 @@ public void clear() {
} catch (IOException e) {
OLogManager.instance().error(this, "Error on deleting the tree: " + dataProvider, e, OStorageException.class);
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.clear"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.clear"), "Clear a MVRBTree", timer);
}
}
@@ -245,7 +245,7 @@ public void unload() {
} catch (Exception e) {
OLogManager.instance().error(this, "Error on unload the tree: " + dataProvider, e, OStorageException.class);
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.unload"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.unload"), "Unload a MVRBTree", timer);
}
}
@@ -371,7 +371,7 @@ public int optimize(final boolean iForce) {
checkTreeStructure(root);
}
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.optimize"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.optimize"), "Optimize a MVRBTree", timer);
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(this, "Optimization completed in %d ms\n", System.currentTimeMillis() - timer);
@@ -446,7 +446,7 @@ public V put(final K key, final V value) {
return v;
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.put"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.put"), "Put a value into a MVRBTree", timer);
}
}
@@ -461,7 +461,7 @@ public void putAll(final Map<? extends K, ? extends V> map) {
commitChanges();
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.putAll"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.putAll"), "Put multiple values into a MVRBTree", timer);
}
}
@@ -488,7 +488,7 @@ public V remove(final Object key) {
}
}
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.remove"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.remove"), "Remove a value from a MVRBTree", timer);
}
throw new OLowMemoryException("OMVRBTreePersistent.remove()");
@@ -536,7 +536,7 @@ public int commitChanges() {
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.commitChanges"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.commitChanges"), "Commit pending changes to a MVRBTree", timer);
}
return totalCommitted;
@@ -570,7 +570,7 @@ public V get(final Object iKey) {
throw new OLowMemoryException("OMVRBTreePersistent.get()");
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.get"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.get"), "Get a value from a MVRBTree", timer);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java
index 5d87526c468..934efb165f7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java
@@ -152,7 +152,7 @@ public void putAll(final Collection<OIdentifiable> coll) {
commitChanges();
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.putAll"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.putAll"), "Put multiple values in a MVRBTreeRID", timer);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapEntryProvider.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapEntryProvider.java
index 01a1782f4d2..a1c655b27fb 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapEntryProvider.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapEntryProvider.java
@@ -66,7 +66,7 @@ public K getKeyAt(final int iIndex) {
K k = keys[iIndex];
if (k == null)
try {
- PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.unserializeKey"), 1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.unserializeKey"), "Deserialize a MVRBTree entry key", 1);
k = (K) keyFromStream(iIndex);
@@ -87,7 +87,8 @@ public V getValueAt(final int iIndex) {
V v = values[iIndex];
if (v == null)
try {
- PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.unserializeValue"), 1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.unserializeValue"), "Deserialize a MVRBTree entry value",
+ 1);
v = (V) valueFromStream(iIndex);
@@ -289,7 +290,7 @@ public OSerializableStream fromStream(byte[] iStream) throws OSerializationExcep
} catch (IOException e) {
throw new OSerializationException("Can not unmarshall tree node with id ", e);
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.entry.fromStream"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.entry.fromStream"), "Deserialize a MVRBTree entry", timer);
}
}
@@ -307,7 +308,7 @@ public byte[] toStream() throws OSerializationException {
} catch (IOException e) {
throw new OSerializationException("Cannot marshall RB+Tree node", e);
} finally {
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.entry.toStream"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.entry.toStream"), "Serialize a MVRBTree entry", timer);
}
}
@@ -405,7 +406,7 @@ private int serializeBinaryValue(byte[] newBuffer, int offset, int i) {
final OBinarySerializer<V> valueSerializer = (OBinarySerializer<V>) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer;
if (serializedValues[i] <= 0) {
- PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeValue"), 1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeValue"), "Serialize a MVRBTree entry value", 1);
valueSerializer.serialize(values[i], newBuffer, offset);
offset += valueSerializer.getObjectSize(values[i]);
} else {
@@ -420,7 +421,7 @@ private int serializeBinaryValue(byte[] newBuffer, int offset, int i) {
private int serializeKey(byte[] newBuffer, int offset, int i) {
final OBinarySerializer<K> keySerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer;
if (serializedKeys[i] <= 0) {
- PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeKey"), 1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeKey"), "Serialize a MVRBTree entry key", 1);
keySerializer.serialize(keys[i], newBuffer, offset);
offset += keySerializer.getObjectSize(keys[i]);
} else {
@@ -468,12 +469,16 @@ private void toStreamUsingBinaryStreamSerializer() throws IOException {
}
final OMemoryStream outStream = new OMemoryStream(outBuffer);
- outStream.jump(offset);
+ try {
+ outStream.jump(offset);
- for (int i = 0; i < size; ++i)
- serializedValues[i] = outStream.set(serializeStreamValue(i));
+ for (int i = 0; i < size; ++i)
+ serializedValues[i] = outStream.set(serializeStreamValue(i));
- buffer = outStream.toByteArray();
+ buffer = outStream.toByteArray();
+ } finally {
+ outStream.close();
+ }
if (stream == null)
stream = new OMemoryStream(buffer);
@@ -546,7 +551,7 @@ private void fromStreamUsingBinaryStreamSerializer(final byte[] inBuffer) {
protected byte[] serializeStreamValue(final int iIndex) throws IOException {
if (serializedValues[iIndex] <= 0) {
// NEW OR MODIFIED: MARSHALL CONTENT
- PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeValue"), 1);
+ PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeValue"), "Serialize a MVRBTree entry value", 1);
return ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer.toStream(values[iIndex]);
}
// RETURN ORIGINAL CONTENT
@@ -569,38 +574,43 @@ protected Object valueFromStream(final int iIndex) throws IOException {
private byte[] convertIntoNewSerializationFormat(byte[] stream) throws IOException {
final OMemoryStream oldStream = new OMemoryStream(stream);
- int oldPageSize = oldStream.getAsInteger();
+ try {
+ int oldPageSize = oldStream.getAsInteger();
- ORecordId oldParentRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE));
- ORecordId oldLeftRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE));
- ORecordId oldRightRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE));
+ ORecordId oldParentRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE));
+ ORecordId oldLeftRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE));
+ ORecordId oldRightRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE));
- boolean oldColor = oldStream.getAsBoolean();
- int oldSize = oldStream.getAsInteger();
+ boolean oldColor = oldStream.getAsBoolean();
+ int oldSize = oldStream.getAsInteger();
- if (oldSize > oldPageSize)
- throw new OConfigurationException("Loaded index with page size set to " + oldPageSize + " while the loaded was built with: "
- + oldSize);
+ if (oldSize > oldPageSize)
+ throw new OConfigurationException("Loaded index with page size set to " + oldPageSize
+ + " while the loaded was built with: " + oldSize);
- K[] oldKeys = (K[]) new Object[oldPageSize];
- for (int i = 0; i < oldSize; ++i) {
- oldKeys[i] = (K) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).streamKeySerializer.fromStream(oldStream.getAsByteArray());
- }
+ K[] oldKeys = (K[]) new Object[oldPageSize];
+ for (int i = 0; i < oldSize; ++i) {
+ oldKeys[i] = (K) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).streamKeySerializer.fromStream(oldStream.getAsByteArray());
+ }
- V[] oldValues = (V[]) new Object[oldPageSize];
- for (int i = 0; i < oldSize; ++i) {
- oldValues[i] = (V) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer.fromStream(oldStream.getAsByteArray());
- }
+ V[] oldValues = (V[]) new Object[oldPageSize];
+ for (int i = 0; i < oldSize; ++i) {
+ oldValues[i] = (V) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer.fromStream(oldStream.getAsByteArray());
+ }
- byte[] result;
- if (((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer instanceof OBinarySerializer)
- result = convertNewSerializationFormatBinarySerializer(oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid, oldColor,
- oldKeys, oldValues);
- else
- result = convertNewSerializationFormatStreamSerializer(oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid, oldColor,
- oldKeys, oldValues);
+ byte[] result;
+ if (((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer instanceof OBinarySerializer)
+ result = convertNewSerializationFormatBinarySerializer(oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid,
+ oldColor, oldKeys, oldValues);
+ else
+ result = convertNewSerializationFormatStreamSerializer(oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid,
+ oldColor, oldKeys, oldValues);
+
+ return result;
- return result;
+ } finally {
+ oldStream.close();
+ }
}
private byte[] convertNewSerializationFormatBinarySerializer(int oldSize, int oldPageSize, ORecordId oldParentRid,
@@ -661,11 +671,16 @@ private byte[] convertNewSerializationFormatStreamSerializer(int oldSize, int ol
}
final OMemoryStream outStream = new OMemoryStream(outBuffer);
- outStream.jump(offset);
+ try {
+ outStream.jump(offset);
- for (int i = 0; i < oldSize; ++i)
- outStream.set(valueSerializer.toStream(oldValues[i]));
+ for (int i = 0; i < oldSize; ++i)
+ outStream.set(valueSerializer.toStream(oldValues[i]));
+
+ return outStream.toByteArray();
- return outStream.toByteArray();
+ } finally {
+ outStream.close();
+ }
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapProvider.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapProvider.java
index 8441b2060d9..9a89f1a5db4 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapProvider.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeMapProvider.java
@@ -116,7 +116,7 @@ public byte[] toStream() throws OSerializationException {
return result;
} finally {
- profiler.stopChrono(profiler.getProcessMetric("mvrbtree.toStream"), timer);
+ profiler.stopChrono(profiler.getProcessMetric("mvrbtree.toStream"), "Serialize a MVRBTree", timer);
}
}
@@ -176,7 +176,7 @@ public OSerializableStream fromStream(final byte[] iStream) throws OSerializatio
OLogManager.instance().error(this, "Error on unmarshalling OMVRBTreeMapProvider object from record: %s", e,
OSerializationException.class, root);
} finally {
- profiler.stopChrono(profiler.getProcessMetric("mvrbtree.fromStream"), timer);
+ profiler.stopChrono(profiler.getProcessMetric("mvrbtree.fromStream"), "Deserialize a MVRBTree", timer);
}
return this;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeRIDProvider.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeRIDProvider.java
index 28bb5aa8d8a..9ad111e1bb0 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeRIDProvider.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/provider/OMVRBTreeRIDProvider.java
@@ -161,7 +161,7 @@ public OStringBuilderSerializable toStream(final StringBuilder iBuffer) throws O
} finally {
marshalling = false;
- PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.toStream"), timer);
+ PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.toStream"), "Serialize a MVRBTreeRID", timer);
}
iBuffer.append(buffer);
diff --git a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/OChannel.java b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/OChannel.java
index e2092534510..472449d567f 100644
--- a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/OChannel.java
+++ b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/OChannel.java
@@ -22,6 +22,7 @@
import java.util.concurrent.atomic.AtomicLong;
import com.orientechnologies.common.concur.resource.OSharedResourceExternalTimeout;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OContextConfiguration;
@@ -54,21 +55,24 @@ public abstract class OChannel extends OSharedResourceExternalTimeout {
static {
final String profilerMetric = PROFILER.getProcessMetric("network.channel.binary");
- PROFILER.registerHookValue(profilerMetric + ".transmittedBytes", new OProfilerHookValue() {
- public Object getValue() {
- return metricGlobalTransmittedBytes.get();
- }
- });
- PROFILER.registerHookValue(profilerMetric + ".receivedBytes", new OProfilerHookValue() {
- public Object getValue() {
- return metricGlobalReceivedBytes.get();
- }
- });
- PROFILER.registerHookValue(profilerMetric + ".flushes", new OProfilerHookValue() {
- public Object getValue() {
- return metricGlobalFlushes.get();
- }
- });
+ PROFILER.registerHookValue(profilerMetric + ".transmittedBytes", "Bytes transmitted to all the network channels",
+ METRIC_TYPE.SIZE, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricGlobalTransmittedBytes.get();
+ }
+ });
+ PROFILER.registerHookValue(profilerMetric + ".receivedBytes", "Bytes received from all the network channels", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricGlobalReceivedBytes.get();
+ }
+ });
+ PROFILER.registerHookValue(profilerMetric + ".flushes", "Number of times the network channels have been flushed",
+ METRIC_TYPE.TIMES, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricGlobalFlushes.get();
+ }
+ });
}
public OChannel(final Socket iSocket, final OContextConfiguration iConfig) throws IOException {
@@ -110,21 +114,24 @@ public void connected() {
profilerMetric = PROFILER.getProcessMetric("network.channel.binary." + socket.getRemoteSocketAddress().toString()
+ socket.getLocalPort() + "".replace('.', '_'));
- PROFILER.registerHookValue(profilerMetric + ".transmittedBytes", new OProfilerHookValue() {
- public Object getValue() {
- return metricTransmittedBytes;
- }
- });
- PROFILER.registerHookValue(profilerMetric + ".receivedBytes", new OProfilerHookValue() {
- public Object getValue() {
- return metricReceivedBytes;
- }
- });
- PROFILER.registerHookValue(profilerMetric + ".flushes", new OProfilerHookValue() {
- public Object getValue() {
- return metricFlushes;
- }
- });
+ PROFILER.registerHookValue(profilerMetric + ".transmittedBytes", "Bytes transmitted to a network channel", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricTransmittedBytes;
+ }
+ });
+ PROFILER.registerHookValue(profilerMetric + ".receivedBytes", "Bytes received from a network channel", METRIC_TYPE.SIZE,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricReceivedBytes;
+ }
+ });
+ PROFILER.registerHookValue(profilerMetric + ".flushes", "Number of times the network channel has been flushed",
+ METRIC_TYPE.TIMES, new OProfilerHookValue() {
+ public Object getValue() {
+ return metricFlushes;
+ }
+ });
}
@Override
diff --git a/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntitySerializer.java b/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntitySerializer.java
index a2b9be9ee60..da9473f3c5d 100644
--- a/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntitySerializer.java
+++ b/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntitySerializer.java
@@ -1050,7 +1050,7 @@ else if (ver.getClass().equals(Object.class))
OObjectSerializationThreadLocal.INSTANCE.get().remove(identityRecord);
- Orient.instance().getProfiler().stopChrono("Object.toStream", timer);
+ Orient.instance().getProfiler().stopChrono("Object.toStream", "Serialize a POJO", timer);
return (T) iProxiedPojo;
}
diff --git a/object/src/main/java/com/orientechnologies/orient/object/serialization/OObjectSerializerHelper.java b/object/src/main/java/com/orientechnologies/orient/object/serialization/OObjectSerializerHelper.java
index 32f904dd251..bcb19e8e3e6 100644
--- a/object/src/main/java/com/orientechnologies/orient/object/serialization/OObjectSerializerHelper.java
+++ b/object/src/main/java/com/orientechnologies/orient/object/serialization/OObjectSerializerHelper.java
@@ -371,7 +371,7 @@ public static Object fromStream(final ODocument iRecord, final Object iPojo, fin
// CALL AFTER UNMARSHALLING
invokeCallback(iPojo, iRecord, OAfterDeserialization.class);
- Orient.instance().getProfiler().stopChrono("Object.fromStream", timer);
+ Orient.instance().getProfiler().stopChrono("Object.fromStream", "Deserialize object from stream", timer);
return iPojo;
}
@@ -637,7 +637,7 @@ else if (ver.getClass().equals(Object.class))
OSerializationThreadLocal.INSTANCE.get().remove(identityRecord);
- Orient.instance().getProfiler().stopChrono("Object.toStream", timer);
+ Orient.instance().getProfiler().stopChrono("Object.toStream", "Serialize object to stream", timer);
return iRecord;
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
index ff8aef0444c..15bad387921 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
@@ -28,6 +28,7 @@
import com.orientechnologies.common.concur.resource.OSharedResourceAbstract;
import com.orientechnologies.common.log.OLogManager;
+import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
@@ -74,11 +75,15 @@ public void run() {
}
}, delay, delay);
- Orient.instance().getProfiler().registerHookValue("server.connections.actives", new OProfilerHookValue() {
- public Object getValue() {
- return metricActiveConnections;
- }
- });
+ Orient
+ .instance()
+ .getProfiler()
+ .registerHookValue("server.connections.actives", "Number of active network connections", METRIC_TYPE.COUNTER,
+ new OProfilerHookValue() {
+ public Object getValue() {
+ return metricActiveConnections;
+ }
+ });
}
/**
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java
index e375956cad3..8faee9565e1 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java
@@ -99,7 +99,7 @@ public void config(final OServer iServer, final Socket iSocket, final OContextCo
}
public void service() throws ONetworkProtocolException, IOException {
- Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".requests", +1);
+ Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".requests", "Execution of HTTP request", +1);
++connection.data.totalRequests;
connection.data.commandInfo = null;
@@ -518,23 +518,26 @@ protected void execute() throws Exception {
readAllContent(request);
} finally {
if (connection.data.lastCommandReceived > -1)
- Orient.instance().getProfiler()
- .stopChrono("server.http." + listeningAddress + ".request", connection.data.lastCommandReceived);
+ Orient
+ .instance()
+ .getProfiler()
+ .stopChrono("server.http." + listeningAddress + ".request", "Execution of HTTP request",
+ connection.data.lastCommandReceived);
}
}
protected void connectionClosed() {
- Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".closed", +1);
+ Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".closed", "Close HTTP connection", +1);
sendShutdown();
}
protected void timeout() {
- Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".timeout", +1);
+ Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".timeout", "Timeout of HTTP connection", +1);
sendShutdown();
}
protected void connectionError() {
- Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".error", +1);
+ Orient.instance().getProfiler().updateCounter("server.http." + listeningAddress + ".error", "Error on HTTP connection", +1);
sendShutdown();
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetProfiler.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetProfiler.java
index 58559d70d1d..40c8b20b745 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetProfiler.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetProfiler.java
@@ -42,19 +42,24 @@ public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) thr
final String command = parts[1];
if (command.equalsIgnoreCase("start")) {
Orient.instance().getProfiler().startRecording();
- iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, "Recording started", null);
+ iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Recording started", null);
} else if (command.equalsIgnoreCase("stop")) {
Orient.instance().getProfiler().stopRecording();
- iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, "Recording stopped", null);
+ iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Recording stopped", null);
} else if (command.equalsIgnoreCase("configure")) {
Orient.instance().getProfiler().configure(parts[2]);
- iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, "Profiler configured with: " + parts[2], null);
+ iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, "Profiler configured with: " + parts[2],
+ null);
} else if (command.equalsIgnoreCase("status")) {
final String status = Orient.instance().getProfiler().isRecording() ? "on" : "off";
- iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, status, null);
+ iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, status, null);
+
+ } else if (command.equalsIgnoreCase("metadata")) {
+ iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, Orient.instance().getProfiler().metadataToJSON(),
+ null);
} else {
final String from = parts.length > 2 ? parts[2] : null;
@@ -68,8 +73,7 @@ public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) thr
}
} catch (Exception e) {
- iResponse.send(OHttpUtils.STATUS_BADREQ_CODE, OHttpUtils.STATUS_BADREQ_DESCRIPTION, OHttpUtils.CONTENT_TEXT_PLAIN, e,
- null);
+ iResponse.send(OHttpUtils.STATUS_BADREQ_CODE, OHttpUtils.STATUS_BADREQ_DESCRIPTION, OHttpUtils.CONTENT_TEXT_PLAIN, e, null);
}
return false;
}
|
2c653b7fb8844ba81fbfc55e9b76827e01969763
|
Mylyn Reviews
|
322734: Load review data from remote task
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
index 766c7cef..8ff64941 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
@@ -1,46 +1,82 @@
package org.eclipse.mylyn.reviews.core;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import org.eclipse.core.runtime.CoreException;
import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.tasks.core.IRepositoryModel;
import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
public class ReviewDataManager {
private Map<ITask, ReviewData> cached = new HashMap<ITask, ReviewData>();
private ReviewDataStore store;
-
- public ReviewDataManager(ReviewDataStore store) {
+ private ITaskDataManager taskDataManager;
+ private IRepositoryModel repositoryModel;
+
+ public ReviewDataManager(ReviewDataStore store,
+ ITaskDataManager taskDataManager, IRepositoryModel repositoryModel) {
this.store = store;
+ this.taskDataManager = taskDataManager;
+ this.repositoryModel = repositoryModel;
+
}
public void storeOutgoingTask(ITask task, Review review) {
ReviewData reviewData = new ReviewData(task, review);
reviewData.setOutgoing();
cached.put(task, reviewData);
- store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(), review, "review");
+ store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(),
+ review, "review");
}
public ReviewData getReviewData(ITask task) {
if (task == null)
return null;
ReviewData reviewData = cached.get(task);
- if(reviewData == null) {
+ if (reviewData == null) {
reviewData = loadFromDiskAddCache(task);
}
+ if (reviewData == null) {
+ reviewData = loadFromTask(task);
+ }
return reviewData;
}
+ private ReviewData loadFromTask(ITask task) {
+ try {
+ List<Review> reviews = ReviewsUtil.getReviewAttachmentFromTask(
+ taskDataManager, repositoryModel, task);
+ // for(Review review : reviews) {
+ // reviews.
+ // }
+ storeTask(task, reviews.get(reviews.size() - 1));
+
+ return getReviewData(task);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
private ReviewData loadFromDiskAddCache(ITask task) {
- Review review = store.loadReviewData(task.getRepositoryUrl(), task.getTaskId()).get(0);
-
- return new ReviewData(task, review);
+ List<Review> reviews = store.loadReviewData(task.getRepositoryUrl(),
+ task.getTaskId());
+ if (reviews.size() > 0) {
+ Review review = reviews.get(0);
+ return new ReviewData(task, review);
+ }
+ return null;
}
public void storeTask(ITask task, Review review) {
ReviewData reviewData = new ReviewData(task, review);
cached.put(task, reviewData);
- store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(), review, "review");
+ store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(),
+ review, "review");
}
}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
index 695ec0c2..64343541 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
@@ -12,6 +12,7 @@
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.mylyn.internal.tasks.ui.ITasksUiPreferenceConstants;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.reviews.core.ReviewDataManager;
import org.eclipse.mylyn.reviews.core.ReviewDataStore;
import org.eclipse.ui.plugin.AbstractUIPlugin;
@@ -50,13 +51,16 @@ public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
- String DIRECTORY_METADATA = ".metadata"; //$NON-NLS-1$
+ String DIRECTORY_METADATA = ".metadata"; //$NON-NLS-1$
String NAME_DATA_DIR = ".mylyn"; //$NON-NLS-1$
-String storeDir = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA + '/'
-+ NAME_DATA_DIR;
+ String storeDir = ResourcesPlugin.getWorkspace().getRoot()
+ .getLocation().toString()
+ + '/' + DIRECTORY_METADATA + '/' + NAME_DATA_DIR;
ReviewDataStore store = new ReviewDataStore(storeDir);
- reviewDataManager = new ReviewDataManager(store);
+ reviewDataManager = new ReviewDataManager(store,
+ TasksUiPlugin.getTaskDataManager(),
+ TasksUiPlugin.getRepositoryModel());
}
/*
|
2ba7cee1e2a02194ac7b6536f6fa0fdd268c7c18
|
coremedia$jangaroo-tools
|
Finished the specified JIRA tickets with the following limitations:
* JOO-5: "this." is now guessed by exclusion: every identifier that is not declared in any scope is assumed to be an inherited member. Since this situation might also be a missing declaration, a warning is issued, which you can get rid of by writing "this." explicitly. Be sure to import *everything*! "window" is no longer in scope, write "window." explicitly ("window" is predefined and does not need to be declared).
* JOO-30: Type casts are now left out is a function is assumed to be a type. Since you can also import package-namespaced functions (not supported by Jangaroo, but could be "native" JavaScript), there is a heuristic that uppercase imports declare types.
* JOO-40: Automatic binding only works for methods declared in the same file. For other situations, I plan to add a [Bound] annotation.
[git-p4: depot-paths = "//coremedia/jangaroo/": change = 145172]
|
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 0ab729498..c3aa189c0 100644
--- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
+++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
@@ -133,7 +133,7 @@ nonterminal FunctionExpr functionExpr;
nonterminal Ide ide;
nonterminal Implements implements;
nonterminal Implements interfaceExtends;
-nonterminal ImportDirective directive;
+nonterminal Node directive;
nonterminal Directives directives;
nonterminal Expr lvalue;
nonterminal MethodDeclaration methodDeclaration;
@@ -267,12 +267,12 @@ constOrVar ::=
;
directive ::=
- IMPORT:i qualifiedIde:ide
- {: RESULT = new ImportDirective(i,new IdeType(ide)); :}
+ IMPORT:i qualifiedIde:ide SEMICOLON:s
+ {: RESULT = new ImportDirective(i,new IdeType(ide), s); :}
| LBRACK:lb ide:ide RBRACK:rb
- {: RESULT = null; :}
- | LBRACK:lb ide:ide LPAREN:lb2 annotationFields:of RPAREN:rb2 RBRACK:rb
- {: RESULT = null; :}
+ {: RESULT = new Annotation(lb, ide, rb); :}
+ | LBRACK:lb ide:ide LPAREN:lb2 annotationFields:af RPAREN:rb2 RBRACK:rb
+ {: RESULT = new Annotation(lb, ide, af, rb); :}
;
nonEmptyAnnotationFields ::=
@@ -283,8 +283,10 @@ nonEmptyAnnotationFields ::=
;
annotationField ::=
- ide:name EQ:eq STRING_LITERAL:value
- {: RESULT = new ObjectField(new IdeExpr(name),eq,new LiteralExpr(value)); :}
+ ide:name EQ:eq expr:value
+ {: RESULT = new ObjectField(new IdeExpr(name),eq,value); :}
+ | expr:value
+ {: RESULT = new ObjectField(new IdeExpr(new Ide(new JooSymbol(""))),null,value); :}
;
annotationFields ::=
@@ -295,8 +297,6 @@ annotationFields ::=
directives ::=
{: RESULT = null; :}
- | SEMICOLON:s directives:ds
- {: RESULT = ds; :}
| directive:d directives:ds
{: RESULT = new Directives(d,ds); :}
;
diff --git a/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java
index 89b689865..b41b6d9e8 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java
@@ -57,12 +57,12 @@ public boolean isConst() {
return optSymConstOrVar != null && optSymConstOrVar.sym == sym.CONST;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (optInitializer == null && isConst())
Jooc.error(optSymConstOrVar, "constant must be initialized");
if (optInitializer != null)
- optInitializer.analyze(context);
+ optInitializer.analyze(this, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java b/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java
index 4a436336a..eb6c4304d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java
@@ -20,7 +20,7 @@
*/
public class AccessorIde extends Ide {
- private JooSymbol symGetOrSet;
+ JooSymbol symGetOrSet;
public AccessorIde(JooSymbol symGetOrSet, Ide ide) {
super(ide.ide);
@@ -29,7 +29,10 @@ public AccessorIde(JooSymbol symGetOrSet, Ide ide) {
@Override
public String getName() {
- return symGetOrSet.getText()+"$"+super.getName();
+ return symGetOrSet.getText()+" "+super.getName();
}
+ public String getFunctionName() {
+ return symGetOrSet.getText()+"$"+super.getName();
+ }
}
\ No newline at end of file
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Annotation.java b/jooc/src/main/java/net/jangaroo/jooc/Annotation.java
new file mode 100644
index 000000000..02d347146
--- /dev/null
+++ b/jooc/src/main/java/net/jangaroo/jooc/Annotation.java
@@ -0,0 +1,54 @@
+/*
+ * 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;
+
+/**
+ * An annotation (sqare bracket meta data).
+ */
+public class Annotation extends NodeImplBase {
+
+ JooSymbol leftBracket;
+ Ide ide;
+ ObjectFields annotationFields;
+ JooSymbol rightBracket;
+
+ public Annotation(JooSymbol leftBracket, Ide ide, JooSymbol rightBracket) {
+ this(leftBracket, ide, null, rightBracket);
+ }
+
+ public Annotation(JooSymbol leftBracket, Ide ide, ObjectFields annotationFields, JooSymbol rightBracket) {
+ this.leftBracket = leftBracket;
+ this.ide = ide;
+ this.annotationFields = annotationFields;
+ this.rightBracket = rightBracket;
+ }
+
+ public JooSymbol getSymbol() {
+ return ide.getSymbol();
+ }
+
+ public void generateCode(JsWriter out) throws IOException {
+ out.beginComment();
+ out.writeSymbol(leftBracket);
+ ide.generateCode(out);
+ if (annotationFields!=null) {
+ annotationFields.generateCode(out);
+ }
+ out.writeSymbol(rightBracket);
+ out.endComment();
+ }
+}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java
index 4414affe5..0015ffa5c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java
@@ -23,6 +23,7 @@
class ApplyExpr extends Expr {
Expr fun;
+ boolean isType;
JooSymbol lParen;
Arguments args;
JooSymbol rParen;
@@ -34,12 +35,14 @@ public ApplyExpr(Expr fun, JooSymbol lParen, Arguments args, JooSymbol rParen) {
this.rParen = rParen;
}
- protected void generateFunCode(JsWriter out) throws IOException {
- fun.generateCode(out);
- }
-
public void generateCode(JsWriter out) throws IOException {
- generateFunCode(out);
+ if (isType) {
+ out.beginComment();
+ fun.generateCode(out);
+ out.endComment();
+ } else {
+ fun.generateCode(out);
+ }
generateArgsCode(out);
}
@@ -50,10 +53,23 @@ protected void generateArgsCode(JsWriter out) throws IOException {
out.writeSymbol(rParen);
}
- public void analyze(AnalyzeContext context) {
- fun.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ // leave out constructor function if called as type cast function!
+ if (fun instanceof IdeExpr) {
+ Ide funIde = ((IdeExpr)fun).ide;
+ // heuristic for types: start with upper case letter.
+ // otherwise, it is most likely an imported package-namespaced function.
+ if (Character.isUpperCase(funIde.getName().charAt(0))) {
+ Scope scope = context.getScope().findScopeThatDeclares(funIde);
+ if (scope!=null) {
+ isType = scope.getDeclaration()==context.getScope().getPackageDeclaration();
+ }
+ }
+ }
+ fun.analyze(this, context);
if (args != null)
- args.analyze(context);
+ args.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Arguments.java b/jooc/src/main/java/net/jangaroo/jooc/Arguments.java
index 44f2ab760..557bfcf8f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Arguments.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Arguments.java
@@ -44,10 +44,11 @@ public void generateCode(JsWriter out) throws IOException {
}
- public void analyze(AnalyzeContext context) {
- arg.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ arg.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java b/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java
index 5058605f7..001e6b6b2 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java
@@ -40,9 +40,10 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(rBracket);
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (args != null)
- args.analyze(context);
+ args.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java b/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java
index ac88b3dbd..98adaeb35 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java
@@ -37,9 +37,10 @@ public void generateCode(JsWriter out) throws IOException {
arg2.generateCode(out);
}
- public void analyze(AnalyzeContext context) {
- arg1.analyze(context);
- arg2.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ arg1.analyze(this, context);
+ arg2.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java b/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java
index cc1222f8a..1bd1bb14c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java
@@ -55,8 +55,9 @@ public void setParameters(Parameters params) {
this.params = params;
}
- public void analyze(AnalyzeContext context) {
- analyze(statements, context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ analyze(this, statements, context);
}
// TODO: Check when analyzing the super call
diff --git a/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java b/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java
index 1fd2da61c..8e6238025 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java
@@ -31,8 +31,9 @@ public CaseStatement(JooSymbol symCase, Expr expr, JooSymbol symColon) {
this.symColon = symColon;
}
- public void analyze(AnalyzeContext context) {
- expr.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ expr.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Catch.java b/jooc/src/main/java/net/jangaroo/jooc/Catch.java
index 13afa08a7..13026469f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Catch.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Catch.java
@@ -43,9 +43,10 @@ public void generateCode(JsWriter out) throws IOException {
block.generateCode(out);
}
- public void analyze(AnalyzeContext context) {
- param.analyze(context);
- block.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ param.analyze(this, context);
+ block.analyze(this, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java b/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java
index 3daf2bdd7..d49984fe1 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java
@@ -45,8 +45,9 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbolWhitespace(rBrace);
}
- public void analyze(AnalyzeContext context) {
- analyze(declararations, context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ analyze(this, declararations, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java
index 8dbfed9c6..25424f981 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java
@@ -114,12 +114,15 @@ public void generateCode(JsWriter out) throws IOException {
out.write("];}");
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ // do *not* call super!
+ this.parentNode = parentNode;
+ context.getScope().declareIde(getName(), this);
parentDeclaration = context.getScope().getPackageDeclaration();
context.enterScope(this);
- if (optExtends != null) optExtends.analyze(context);
- if (optImplements != null) optImplements.analyze(context);
- body.analyze(context);
+ if (optExtends != null) optExtends.analyze(this, context);
+ if (optImplements != null) optImplements.analyze(this, context);
+ body.analyze(this, context);
context.leaveScope(this);
computeModifiers();
}
@@ -145,7 +148,7 @@ public boolean isPrivateStaticMember(String memberName) {
public Type getSuperClassType() {
return optExtends != null
? optExtends.superClass
- : new IdeType(new Ide(new JooSymbol(sym.IDE, "", -1, -1, "", "Object")));
+ : new IdeType(new Ide(new JooSymbol("Object")));
}
public String getSuperClassPath() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java b/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java
index 8cbbb67cc..da94fff80 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java
@@ -83,9 +83,49 @@ public void generateCode(JsWriter out) throws IOException {
out.write(");");
}
- public void analyze(AnalyzeContext context) {
- packageDeclaration.analyze(context);
- classDeclaration.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ // establish global scope for built-in identifiers:
+ IdeType globalObject = new IdeType("globalObject");
+ context.enterScope(globalObject);
+ declareIdes(context.getScope(), new String[]{
+ "undefined",
+ "window", // TODO: or rather have to import?
+ "int",
+ "uint",
+ "Object",
+ "Function",
+ "Class",
+ "Array",
+ "Boolean",
+ "String",
+ "Number",
+ "RegExp",
+ "Date",
+ "Math",
+ "parseInt",
+ "parseFloat",
+ "isNaN",
+ "NaN",
+ "isFinite",
+ "encodeURIComponent",
+ "decodeURIComponent",
+ "trace",
+ "joo"});
+ super.analyze(parentNode, context);
+ context.enterScope(packageDeclaration);
+ packageDeclaration.analyze(this, context);
+ if (directives!=null) {
+ directives.analyze(this, context);
+ }
+ classDeclaration.analyze(this, context);
+ context.leaveScope(packageDeclaration);
+ context.leaveScope(globalObject);
+ }
+
+ private void declareIdes(Scope scope, String[] identifiers) {
+ for (String identifier: identifiers) {
+ scope.declareIde(identifier, new IdeType(identifier));
+ }
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java b/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java
index d090b8b36..a871c7468 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java
@@ -21,10 +21,10 @@
public class CompileLog {
protected boolean errors = false;
+ protected boolean warnings = false;
public void error(JooSymbol sym, String msg) {
- error(formatError(sym.getFileName(), sym.getLine(), sym.getColumn(), msg));
- errors = true;
+ error(formatError(sym.getFileName(), sym.getLine(), sym.getColumn(), "Error", msg));
}
public void error(String msg) {
@@ -32,14 +32,24 @@ public void error(String msg) {
errors = true;
}
+ public void warning(JooSymbol sym, String msg) {
+ warning(formatError(sym.getFileName(), sym.getLine(), sym.getColumn(), "Warning", msg));
+ }
+
+ public void warning(String msg) {
+ System.out.println(msg);
+ warnings = true;
+ }
+
public boolean hasErrors() {
return errors;
}
- String formatError(String fileName, int line, int column, String message) {
+ String formatError(String fileName, int line, int column, String debugLevel, String message) {
StringBuffer m = new StringBuffer();
m.append(fileName + "(" + line + "): ");
- m.append("Error: ");
+ m.append(debugLevel);
+ m.append(": ");
m.append("in column " + column + ": ");
m.append(message);
return m.toString();
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java
index 343fa8d6c..a611dcfb5 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java
@@ -44,10 +44,11 @@ public void generateCode(JsWriter out) throws IOException {
ifFalse.generateCode(out);
}
- public void analyze(AnalyzeContext context) {
- cond.analyze(context);
- ifTrue.analyze(context);
- ifFalse.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ cond.analyze(this, context);
+ ifTrue.analyze(this, context);
+ ifFalse.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java
index 77a38331e..a95509195 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java
@@ -31,7 +31,7 @@ public ConditionalLoopStatement(JooSymbol symLoop, Expr optCond, Statement body)
protected void analyzeLoopHeader(AnalyzeContext context) {
if (optCond != null)
- optCond.analyze(context);
+ optCond.analyze(this, context);
}
protected void generateLoopHeaderCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java
index 1c8c3d208..e5f15d407 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java
@@ -24,8 +24,4 @@ public ContinueStatement(JooSymbol symContinue, Ide optLabel, JooSymbol symSemic
super(symContinue, optLabel, symSemicolon);
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- }
-
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java
index cc29c88d3..e5f11d767 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java
@@ -142,8 +142,8 @@ protected boolean writeRuntimeModifiersUnclosed(JsWriter out) throws IOException
return false;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
parentDeclaration = context.getScope().getDeclaration();
classDeclaration = context.getCurrentClass();
computeModifiers();
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java b/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java
index fb4140116..448d3db03 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java
@@ -29,9 +29,9 @@ public DeclarationStatement(Declaration decl, JooSymbol symSemicolon) {
this.decl = decl;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- decl.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ decl.analyze(this, context);
}
protected void generateStatementCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java b/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java
index 162270c08..bf832161d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java
@@ -35,10 +35,6 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(symColon);
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- }
-
public JooSymbol getSymbol() {
return symDefault;
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Directives.java b/jooc/src/main/java/net/jangaroo/jooc/Directives.java
index ad7862ab3..29b1ba9a2 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Directives.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Directives.java
@@ -22,20 +22,21 @@
*/
class Directives extends NodeImplBase {
- ImportDirective directive; // other directive types may follow later
+ Node directive; // other directive types may follow later
Directives tail;
- public Directives(ImportDirective directive, Directives tail) {
+ public Directives(Node directive, Directives tail) {
this.directive = directive;
this.tail = tail;
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (directive!=null) {
- directive.analyze(context);
+ directive.analyze(this, context);
}
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java b/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java
index 1c78c74a0..4632e0cb3 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java
@@ -34,7 +34,7 @@ protected void analyzeLoopHeader(AnalyzeContext context) {
}
protected void analyzeLoopFooter(AnalyzeContext context) {
- optCond.analyze(context);
+ optCond.analyze(this, context);
}
protected void generateLoopHeaderCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java
index 6c5155b4e..2dd88732d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java
@@ -23,14 +23,14 @@
*/
class DotExpr extends BinaryOpExpr {
- private ClassDeclaration classDeclaration;
+ ClassDeclaration classDeclaration;
public DotExpr(Expr expr, JooSymbol symDot, Ide ide) {
super(expr, symDot, new IdeExpr(ide));
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
classDeclaration = context.getCurrentClass();
}
@@ -63,6 +63,28 @@ public void generateCode(JsWriter out) throws IOException {
if (classDeclaration!=null
&& arg2 instanceof IdeExpr) {
String property = ((IdeExpr)arg2).ide.getName();
+ // check and handle instance methods declared in same file, accessed as function:
+ if (arg1 instanceof ThisExpr
+ && !(parentNode instanceof DotExpr)
+ && !(parentNode instanceof ApplyExpr)
+ && !(parentNode instanceof DeleteStatement)
+ && !((parentNode instanceof AssignmentOpExpr) && ((AssignmentOpExpr)parentNode).arg1==this)) {
+ MemberDeclaration memberDeclaration = classDeclaration.getMemberDeclaration(property);
+ if (memberDeclaration!=null && memberDeclaration.isMethod()) {
+ //Jooc.warning(arg2.getSymbol(), "Found method used as function, have to bind!");
+ out.writeToken("joo.bind(");
+ arg1.generateCode(out);
+ out.write(",");
+ out.writeSymbolWhitespace(arg2.getSymbol());
+ if (memberDeclaration.isPrivate()) {
+ out.write("$"+property);
+ } else {
+ out.write("\""+property+"\"");
+ }
+ out.write(")");
+ return;
+ }
+ }
// check and handle private instance members and super method access:
if ( arg1 instanceof ThisExpr && classDeclaration.isPrivateMember(property)
|| arg1 instanceof SuperExpr) {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java
index da37e3913..e7e65210a 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java
@@ -36,9 +36,10 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(symSemicolon);
}
- public void analyze(AnalyzeContext context) {
- if (optExpr != null)
- optExpr.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (optExpr != null)
+ optExpr.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java
index 1d7a5475e..df515edc2 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java
@@ -46,8 +46,8 @@ protected void generateLoopHeaderCode(JsWriter out) throws IOException {
}
protected void analyzeLoopHeader(AnalyzeContext context) {
- decl.analyze(context);
- expr.analyze(context);
+ decl.analyze(this, context);
+ expr.analyze(this, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java b/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java
index 960960e0f..63070a2ce 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java
@@ -33,12 +33,12 @@ public ForInitializer(Expr expr) {
this.expr = expr;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (decl!=null)
- decl.analyze(context);
+ decl.analyze(this, context);
if (expr!=null)
- expr.analyze(context);
+ expr.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java
index 982c8470a..a62e02a12 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java
@@ -54,7 +54,7 @@ protected void generateLoopHeaderCode(JsWriter out) throws IOException {
protected void analyzeLoopHeader(AnalyzeContext context) {
if (forInit!=null)
- forInit.analyze(context);
+ forInit.analyze(this, context);
super.analyzeLoopHeader(context);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java b/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java
index 282b11852..d863e308f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java
@@ -46,16 +46,19 @@ public ClassDeclaration getClassDeclaration() {
return classDeclaration;
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
classDeclaration = context.getCurrentClass();
Debug.assertTrue(classDeclaration != null, "classDeclaration != null");
- super.analyze(context);
+ super.analyze(parentNode, context);
context.enterScope(this);
if (params != null)
- params.analyze(context);
+ params.analyze(this, context);
+ if (context.getScope().getIdeDeclaration("arguments")==null) {
+ context.getScope().declareIde("arguments", this); // is always defined inside a function!
+ }
if (optTypeRelation != null)
- optTypeRelation.analyze(context);
- body.analyze(context);
+ optTypeRelation.analyze(this, context);
+ body.analyze(this, context);
context.leaveScope(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Ide.java b/jooc/src/main/java/net/jangaroo/jooc/Ide.java
index 2a751257b..7877e2d64 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Ide.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Ide.java
@@ -33,7 +33,7 @@ public void generateCode(JsWriter out) throws IOException {
}
public String[] getQualifiedName() {
- return new String[] { ide.getText() };
+ return new String[] { getName() };
}
public String getName() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java
index ffe741f9a..fe20de111 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java
@@ -30,7 +30,7 @@ protected IdeDeclaration(JooSymbol[] modifiers, int allowedModifiers, Ide ide) {
super(modifiers, allowedModifiers);
this.ide = ide;
if (ide!=null && PRIVATE_MEMBER_NAME.matcher(ide.getName()).matches()) {
- System.err.println("WARNING: Jangaroo identifier must not be an ActionScript identifier prefixed with a dollar sign ('$'): "+ide.getName());
+ Jooc.warning(ide.getSymbol(), "Jangaroo identifier must not be an ActionScript identifier prefixed with a dollar sign ('$').");
}
}
@@ -73,9 +73,10 @@ public String getPath() {
return toPath(getQualifiedName());
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- context.getScope().declareIde(this);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (context.getScope().declareIde(getName(), this)!=null)
+ Jooc.error(getSymbol(), "duplicate declaration of identifier '" + getName() + "'");
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/IdeType.java b/jooc/src/main/java/net/jangaroo/jooc/IdeType.java
index e46731cda..798ec9a37 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/IdeType.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/IdeType.java
@@ -28,6 +28,10 @@ public Ide getIde() {
Ide ide;
+ public IdeType(String name) {
+ this(new Ide(new JooSymbol(name)));
+ }
+
public IdeType(Ide ide) {
this.ide = ide;
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java b/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java
index ad3dcff08..9e9152fd7 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java
@@ -39,11 +39,12 @@ public IfStatement(JooSymbol symIf, Expr cond, Statement ifTrue, JooSymbol symEl
this.ifFalse = ifFalse;
}
- public void analyze(AnalyzeContext context) {
- cond.analyze(context);
- ifTrue.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ cond.analyze(this, context);
+ ifTrue.analyze(this, context);
if (ifFalse != null)
- ifFalse.analyze(context);
+ ifFalse.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java
index d804e6216..8c6643104 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java
@@ -24,10 +24,23 @@ public class ImportDirective extends NodeImplBase {
JooSymbol importKeyword;
Type type;
+ JooSymbol semicolon;
- public ImportDirective(JooSymbol importKeyword, Type type) {
+ public ImportDirective(JooSymbol importKeyword, Type type, JooSymbol semicolon) {
this.importKeyword = importKeyword;
this.type = type;
+ this.semicolon = semicolon;
+ }
+
+ @Override
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (type instanceof IdeType) {
+ Ide ide = ((IdeType)type).ide;
+ context.getScope().declareIde(ide.getName(), this);
+ // also add first package path arc (might be the same string for top level imports):
+ context.getScope().declareIde(ide.getQualifiedName()[0], this);
+ }
}
public void generateCode(JsWriter out) throws IOException {
@@ -36,7 +49,9 @@ public void generateCode(JsWriter out) throws IOException {
out.write("\"");
out.writeSymbolToken(importKeyword);
type.generateCode(out);
- out.write("\",");
+ out.write("\"");
+ out.writeSymbolWhitespace(semicolon);
+ out.write(",");
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Initializer.java b/jooc/src/main/java/net/jangaroo/jooc/Initializer.java
index 774e25d01..ef3d2d9be 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Initializer.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Initializer.java
@@ -30,8 +30,9 @@ public Initializer(JooSymbol symEq, Expr value) {
this.value = value;
}
- public void analyze(AnalyzeContext context) {
- value.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ value.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java b/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java
index 9fb99c493..ded3f6ce5 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java
@@ -26,6 +26,10 @@ public class JooSymbol extends java_cup.runtime.Symbol {
protected Object jooValue;
protected String fileName;
+ public JooSymbol(String text) {
+ this(net.jangaroo.jooc.sym.IDE, "", -1, -1, "", text);
+ }
+
public JooSymbol(int type, String fileName, int line, int column, String whitespace, String text) {
this(type, fileName, line, column, whitespace, text, null);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Jooc.java b/jooc/src/main/java/net/jangaroo/jooc/Jooc.java
index e7c014135..bf3a37157 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Jooc.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Jooc.java
@@ -51,7 +51,7 @@ public class Jooc {
public static final String CLASS_FULLY_QUALIFIED_NAME = CLASS_PACKAGE_NAME + "." + CLASS_CLASS_NAME;
private JoocConfiguration config;
- private CompileLog log = new CompileLog();
+ private static CompileLog log = new CompileLog();
private ArrayList<CompilationUnit> compilationUnits = new ArrayList<CompilationUnit>();
@@ -64,7 +64,7 @@ public int run(JoocConfiguration config) {
CompilationUnitSinkFactory codeSinkFactory = createSinkFactory(config);
for (CompilationUnit unit : compilationUnits) {
- unit.analyze(new AnalyzeContext());
+ unit.analyze(null, new AnalyzeContext());
unit.writeOutput(codeSinkFactory, config.isVerbose());
}
return log.hasErrors() ? 1 : 0;
@@ -129,6 +129,10 @@ public static void error(String msg, Throwable t) {
throw new CompilerError(msg, t);
}
+ static void warning(JooSymbol symbol, String msg) {
+ log.warning(symbol, msg);
+ }
+
protected void processSource(String fileName) {
processSource(new File(fileName));
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java b/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java
index b257199a8..7a3f8be9f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java
@@ -31,8 +31,8 @@ class LabelRefStatement extends KeywordExprStatement {
protected LabeledStatement labelDeclaration = null;
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
Scope scope = context.getScope();
if (optLabel == null) {
Statement loopOrSwitchStatement = scope.getCurrentLoopOrSwitch();
diff --git a/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java b/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java
index da3a29fa1..3297f2217 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java
@@ -32,8 +32,9 @@ public LabeledStatement(Ide ide, JooSymbol symColon, Statement statement) {
this.statement = statement;
}
- public void analyze(AnalyzeContext context) {
- statement.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ statement.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java b/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java
index 7d7f892ab..7d00606f0 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java
@@ -41,10 +41,11 @@ public void generateCode(JsWriter out) throws IOException {
protected void generateLoopFooterCode(JsWriter out) throws IOException {
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
context.getScope().enterLoop(this);
analyzeLoopHeader(context);
- body.analyze(context);
+ body.analyze(this, context);
analyzeLoopFooter(context);
context.getScope().exitLoop(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java
index bbbc204e5..bfb59d875 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java
@@ -46,8 +46,8 @@ public boolean isConstructor() {
return false;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (isField() || isMethod()) {
getClassDeclaration().registerMember(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java
index 14c34608a..11ecafe4a 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java
@@ -76,7 +76,7 @@ public boolean isAbstract() {
return getClassDeclaration().isInterface() || super.isAbstract();
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
parentDeclaration = context.getCurrentClass();
ClassDeclaration classDeclaration = getClassDeclaration();
if (ide.getName().equals(classDeclaration.getName())) {
@@ -84,7 +84,7 @@ public void analyze(AnalyzeContext context) {
classDeclaration.setConstructor(this);
allowedModifiers = MODIFIERS_SCOPE;
}
- super.analyze(context); // computes modifiers
+ super.analyze(parentNode, context); // computes modifiers
if (overrides() && isAbstract())
Jooc.error(this, "overriding methods are not allowed to be declared abstract");
if (isAbstract()) {
@@ -100,10 +100,13 @@ public void analyze(AnalyzeContext context) {
context.enterScope(this);
if (params != null)
- params.analyze(context);
+ params.analyze(this, context);
+ if (context.getScope().getIdeDeclaration("arguments")==null) {
+ context.getScope().declareIde("arguments", this); // is always defined inside a function!
+ }
if (optTypeRelation != null)
- optTypeRelation.analyze(context);
- optBody.analyze(context);
+ optTypeRelation.analyze(this, context);
+ optBody.analyze(this, context);
context.leaveScope(this);
if (containsSuperConstructorCall()) {
@@ -130,17 +133,20 @@ public void generateCode(JsWriter out) throws IOException {
out.write(methodName);
out.write("\",");
out.writeSymbol(symFunction);
+ out.writeSymbolWhitespace(ide.ide);
if (out.getKeepSource()) {
out.write(" ");
if (isConstructor) {
// do not name the constructor initializer function like the class, or it will be called
// instead of the constructor function generated by the runtime! So we prefix it with a "$".
// The name is for debugging purposes only, anyway.
- out.write("$");
+ out.write("$"+methodName);
+ } else if (ide instanceof AccessorIde) {
+ out.write(((AccessorIde)ide).getFunctionName());
+ } else {
+ out.write(methodName);
}
- out.write(methodName);
}
- out.writeSymbolWhitespace(ide.ide);
}
out.writeSymbol(lParen);
if (params != null) {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java b/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java
index 0ee7c0319..42234e501 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java
@@ -36,9 +36,10 @@ public NewExpr(JooSymbol symNew, Type type, JooSymbol lParen, Arguments args, Jo
this.rParen = rParen;
}
- public void analyze(AnalyzeContext context) {
- if (args != null)
- args.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (args != null)
+ args.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Node.java b/jooc/src/main/java/net/jangaroo/jooc/Node.java
index 49019759e..2f37ef722 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Node.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Node.java
@@ -24,6 +24,6 @@ interface Node {
JooSymbol getSymbol();
void generateCode(JsWriter out) throws IOException;
- void analyze(AnalyzeContext context);
+ void analyze(Node parentNode, AnalyzeContext context);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java b/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java
index 0665c9aa0..06bd1c1cc 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java
@@ -24,21 +24,23 @@
*/
public abstract class NodeImplBase implements Node {
+ Node parentNode;
+
void generateCode(Collection<Node> nodes, JsWriter out) throws IOException {
for (Node node : nodes) {
node.generateCode(out);
}
}
- public void analyze(AnalyzeContext context) {
- // default is to do nothing
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ this.parentNode = parentNode;
}
- public void analyze(Collection/*<Node>*/ nodes, AnalyzeContext context) {
+ public void analyze(Node parent, Collection/*<Node>*/ nodes, AnalyzeContext context) {
Iterator iter = nodes.iterator();
while (iter.hasNext()) {
NodeImplBase node = (NodeImplBase) iter.next();
- node.analyze(context);
+ node.analyze(parent, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java
index 8ed5d8cbb..3831976b5 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java
@@ -32,9 +32,10 @@ public ObjectField(Expr nameExpr, JooSymbol symColon, Expr value) {
this.value = value;
}
- public void analyze(AnalyzeContext context) {
- nameExpr.analyze(context);
- value.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ nameExpr.analyze(this, context);
+ value.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java
index 441fce247..725bcda4e 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java
@@ -36,10 +36,11 @@ public ObjectFields(ObjectField field, JooSymbol symComma, ObjectFields tail) {
this.tail = tail;
}
- public void analyze(AnalyzeContext context) {
- field.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ field.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java
index 2aa38fc04..d5fee4cdd 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java
@@ -39,9 +39,10 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(rParen);
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (fields != null)
- fields.analyze(context);
+ fields.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java
index bf9eeb085..f82eaaf8d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java
@@ -39,8 +39,11 @@ public void generateCode(JsWriter out) throws IOException {
out.write(",");
}
- public void analyze(AnalyzeContext context) {
- context.enterScope(this);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ // do *not* call super!
+ this.parentNode = parentNode;
+ // add first package path arc (might be the same string for top level imports):
+ context.getScope().declareIde(ide.getQualifiedName()[0], this);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Parameters.java b/jooc/src/main/java/net/jangaroo/jooc/Parameters.java
index 617dbba61..d57b3aeae 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Parameters.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Parameters.java
@@ -45,11 +45,11 @@ public Parameters(Parameter param) {
this(param, null, null);
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- param.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ param.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java
index ae7759e6a..f293af14c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java
@@ -32,8 +32,9 @@ public ParenthesizedExpr(JooSymbol lParen, Expr expr, JooSymbol rParen) {
this.rParen = rParen;
}
- public void analyze(AnalyzeContext context) {
- expr.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ expr.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Scope.java b/jooc/src/main/java/net/jangaroo/jooc/Scope.java
index 33016de50..5df7adb0c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Scope.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Scope.java
@@ -41,17 +41,13 @@ public Scope getParentScope() {
return parent;
}
- protected Map<String,IdeDeclaration> ides = new HashMap<String,IdeDeclaration>();
+ protected Map<String,Node> ides = new HashMap<String,Node>();
protected List<LabeledStatement> labels = new ArrayList<LabeledStatement>();
protected List<LoopStatement> loopStatementStack = new ArrayList<LoopStatement>();
protected List<KeywordStatement> loopOrSwitchStatementStack = new ArrayList<KeywordStatement>();
- public void declareIde(IdeDeclaration decl) {
- String name = decl.ide.getName();
- IdeDeclaration alreadyDeclared = ides.get(name);
- if (alreadyDeclared != null)
- Jooc.error(decl.ide.ide, "duplicate declaration of identifier '" + name + "'");
- ides.put(name, decl);
+ public Node declareIde(String name, Node decl) {
+ return ides.put(name, decl);
}
public void defineLabel(LabeledStatement labeledStatement) {
@@ -75,8 +71,12 @@ public LabeledStatement lookupLabel(Ide ide) {
return null; // not reached
}
- public IdeDeclaration getIdeDeclaration(Ide ide) {
- return ides.get(ide.getName());
+ public Node getIdeDeclaration(Ide ide) {
+ return getIdeDeclaration(ide.getName());
+ }
+
+ public Node getIdeDeclaration(String name) {
+ return ides.get(name);
}
public Scope findScopeThatDeclares(Ide ide) {
@@ -85,7 +85,7 @@ public Scope findScopeThatDeclares(Ide ide) {
: getParentScope().findScopeThatDeclares(ide);
}
- public IdeDeclaration lookupIde(Ide ide) {
+ public Node lookupIde(Ide ide) {
Scope scope = findScopeThatDeclares(ide);
if (scope == null)
Jooc.error(ide.ide, "undeclared identifier: '" + ide.getName() + "'");
diff --git a/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java b/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java
index 77ac16f46..2fc9722e3 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java
@@ -38,10 +38,10 @@ public void generateCode(JsWriter out) throws IOException {
out.write(",");
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
context.enterScope(this);
- block.analyze(context);
+ block.analyze(this, context);
context.leaveScope(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java b/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java
index bea260f41..c3abb32b4 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java
@@ -37,7 +37,8 @@ public SuperConstructorCallStatement(JooSymbol symSuper, JooSymbol lParen, Argum
this.fun = new SuperExpr(symSuper);
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
MethodDeclaration method = context.getCurrentMethod();
if (method == null || !method.isConstructor()) {
Jooc.error(symSuper, "must only call super constructor from constructor method");
@@ -48,7 +49,7 @@ public void analyze(AnalyzeContext context) {
method.setContainsSuperConstructorCall(true);
if (args != null)
- args.analyze(context);
+ args.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java b/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java
index 0fe499789..95bc57af3 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java
@@ -16,7 +16,6 @@
package net.jangaroo.jooc;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.List;
/**
@@ -34,10 +33,11 @@ public SwitchStatement(JooSymbol symSwitch, ParenthesizedExpr cond, JooSymbol lB
}
- public void analyze(AnalyzeContext context) {
- cond.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ cond.analyze(this, context);
context.getScope().enterSwitch(this);
- block.analyze(context);
+ block.analyze(this, context);
context.getScope().exitSwitch(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java
index be8c5442f..e4d27ae05 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java
@@ -22,6 +22,8 @@
*/
class TopLevelIdeExpr extends IdeExpr {
+ // TODO: add a compiler option for this:
+ public static final boolean ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS = true;
private Scope scope;
public TopLevelIdeExpr(Ide ide) {
@@ -29,8 +31,8 @@ public TopLevelIdeExpr(Ide ide) {
}
@Override
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
scope = context.getScope();
}
@@ -38,26 +40,27 @@ public void analyze(AnalyzeContext context) {
public void generateCode(JsWriter out) throws IOException {
if (scope!=null) {
Scope declaringScope = scope.findScopeThatDeclares(ide);
- if (declaringScope!=null) {
+ boolean addMissingThis = false;
+ if (declaringScope == null) {
+ addMissingThis = ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS && Character.isLowerCase(ide.getName().charAt(0));
+ Jooc.warning(ide.getSymbol(), "Undeclared identifier: "+ide.getName()
+ +(addMissingThis ? ", assuming it is an inherited member." : ""));
+ } else {
Node declaration = declaringScope.getDeclaration();
if (declaration instanceof ClassDeclaration) {
MemberDeclaration memberDeclaration = (MemberDeclaration)declaringScope.getIdeDeclaration(ide);
if (!memberDeclaration.isStatic() && !memberDeclaration.isConstructor()) {
- //System.out.println("WARNING: Adding probably missing 'this' to "+getSymbol());
- out.writeToken("this");
- if (memberDeclaration.isPrivate()) {
- out.write("[");
- // awkward, but we have to be careful if we add characters to tokens:
- out.writeSymbol(getSymbol(), "$", "");
- out.write("]");
- } else {
- out.write(".");
- out.writeSymbol(getSymbol());
- }
- return;
+ addMissingThis = true;
}
}
}
+ if (addMissingThis) {
+ DotExpr synthesizedDotExpr = new DotExpr(new ThisExpr(new JooSymbol("this")), new JooSymbol("."), this.ide);
+ synthesizedDotExpr.parentNode = parentNode;
+ synthesizedDotExpr.classDeclaration = scope.getClassDeclaration();
+ synthesizedDotExpr.generateCode(out);
+ return;
+ }
}
super.generateCode(out);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java b/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java
index 4302a3b67..160ed45ec 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java
@@ -40,11 +40,12 @@ public TryStatement(JooSymbol symTry, BlockStatement block, ArrayList catches, J
this.finallyBlock = finallyBlock;
}
- public void analyze(AnalyzeContext context) {
- block.analyze(context);
- analyze(catches, context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ block.analyze(this, context);
+ analyze(this, catches, context);
if (finallyBlock != null)
- finallyBlock.analyze(context);
+ finallyBlock.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TypeList.java b/jooc/src/main/java/net/jangaroo/jooc/TypeList.java
index 380796543..f58280459 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TypeList.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TypeList.java
@@ -36,10 +36,11 @@ public TypeList(Type type, JooSymbol optComma, TypeList tail) {
this.tail = tail;
}
- public void analyze(AnalyzeContext context) {
- type.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ type.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java b/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java
index 9f0091f85..9da96172a 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java
@@ -35,8 +35,9 @@ public TypeRelation(JooSymbol symRelation, Type type) {
this.type = type;
}
- public void analyze(AnalyzeContext context) {
- type.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ type.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java b/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java
index 650d1ccf2..0fbc6d27c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java
@@ -28,8 +28,9 @@ public UnaryOpExpr(JooSymbol op, Expr arg) {
this.arg = arg;
}
- public void analyze(AnalyzeContext context) {
- arg.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ arg.analyze(this, context);
}
boolean isCompileTimeConstant() {
diff --git a/jooc/src/main/js/joo/Class.js b/jooc/src/main/js/joo/Class.js
index 74c7d2751..a9c5a8638 100644
--- a/jooc/src/main/js/joo/Class.js
+++ b/jooc/src/main/js/joo/Class.js
@@ -13,6 +13,21 @@
// JangarooScript runtime support. Author: Frank Wienberg
+Class = function Class(casted) {
+ return casted;
+};
+Class.$class = {
+ isInstance: function(object) {
+ return typeof object=="function";
+ }
+};
+trace = function(msg) {
+ if (window.console) {
+ console.log("AS3: "+msg);
+ } else {
+ document.writeln("AS3: "+msg);
+ }
+};
Function.prototype.getName = typeof Function.prototype.name=="string"
? (function getName() { return this.name; })
: (function() {
@@ -30,10 +45,15 @@ Function.prototype.getName = typeof Function.prototype.name=="string"
}());
Function.prototype.bind = function(object) {
+ if (this.$boundTo===object) {
+ return this;
+ }
var fn = this;
- return function() {
+ var f = function $boundMethod() {
return fn.apply(object,arguments);
};
+ f.$boundTo = object;
+ return f;
};
(function(theGlobalObject) {
@@ -67,6 +87,19 @@ Function.prototype.bind = function(object) {
function isFunction(object) {
return typeof object=="function" && object.constructor!==RegExp;
}
+ function getMethod(object, methodType, methodName) {
+ return methodType=="get" ? object.__lookupGetter__(methodName)
+ : methodType=="set" ? object.__lookupSetter__(methodName)
+ : isFunction(object[methodName]) ? object[methodName]
+ : null;
+ }
+ function setMethod(object, methodType, methodName, method) {
+ switch(methodType) {
+ case "get": object.__defineGetter__(methodName, method); break;
+ case "set": object.__defineSetter__(methodName, method); break;
+ default: object[methodName] = method;
+ }
+ }
function createEmptyConstructor($constructor) {
var emptyConstructor = function(){ this.constructor = $constructor; };
emptyConstructor.prototype = $constructor.prototype;
@@ -111,13 +144,7 @@ Function.prototype.bind = function(object) {
if (typeof member!="function" || member.$boundTo===object) {
return member;
}
- var boundMethod = function $boundMethod() {
- return member.apply(object,arguments);
- };
- // remember the object I am bound to:
- boundMethod.$boundTo = object;
- object[methodName]=boundMethod;
- return boundMethod;
+ return object[methodName]=member.bind(object);
}
function assert(cond, file, line, column) {
if (!cond)
@@ -186,7 +213,8 @@ Function.prototype.bind = function(object) {
var cd = this.classDescriptions[fullClassName];
if (!cd) {
var constr = getNativeClass(fullClassName);
- if (typeof constr=="function") {
+ var constrType = typeof constr;
+ if (constrType=="function" || constrType=="object") {
if (joo.Class.debug && theGlobalObject.console) {
console.debug("found non-Jangaroo class "+fullClassName+"!");
}
@@ -455,6 +483,7 @@ Function.prototype.bind = function(object) {
continue;
}
var memberType = "function";
+ var methodType = "method";
var memberName = undefined;
var modifiers;
if (typeof members=="string") {
@@ -467,6 +496,8 @@ Function.prototype.bind = function(object) {
visibility = "$"+modifier;
} else if (modifier=="var" || modifier=="const") {
memberType = modifier;
+ } else if (modifier=="get" || modifier=="set") {
+ methodType = modifier;
} else if (modifier=="override") {
// so far: ignore. TODO: enable super-call!
} else if (j==modifiers.length-1) {
@@ -490,19 +521,26 @@ Function.prototype.bind = function(object) {
// found static code block; execute on initialization
targetMap.$static.fieldsWithInitializer.push(members);
} else {
- setFunctionName(members, memberName);
+ if (methodType!="method") {
+ setFunctionName(members, methodType+"$"+memberName);
+ } else {
+ setFunctionName(members, memberName);
+ }
if (memberName==this.$class) {
this.$constructor = members;
} else {
if (memberKey=="$this") {
if (visibility=="$private") {
memberName = registerPrivateMember(privateStatic, classPrefix, memberName);
- } else if (isFunction(target[memberName])) {
- // Found overriding! Store super method as private method delegate for super access:
- this.Public.prototype[registerPrivateMember(privateStatic, classPrefix, memberName)] = target[memberName];
+ } else {
+ var overriddenMethod = getMethod(target, methodType, memberName);
+ if (overriddenMethod) {
+ // Found overriding! Store super method as private method delegate for super access:
+ setMethod(this.Public.prototype, methodType, registerPrivateMember(privateStatic, classPrefix, memberName), overriddenMethod);
+ }
}
}
- target[memberName] = members;
+ setMethod(target, methodType, memberName, members);
}
}
} else {
diff --git a/jooc/src/test/joo/example/Person.as b/jooc/src/test/joo/example/Person.as
index 97c1d0f0f..6d16def9a 100644
--- a/jooc/src/test/joo/example/Person.as
+++ b/jooc/src/test/joo/example/Person.as
@@ -49,14 +49,14 @@ public class Person {
* Render this person as HTML into the current document.
*/
public function render(): void {
- document.write("<div>"+this.renderInner()+"</div>");
+ window.document.write("<div>"+this.renderInner()+"</div>");
}
/**
* Get the inner HTML presenting this person.
* Subclasses should add a presentation of their additional properties.
*/
- protected function renderInner(): void {
+ protected function renderInner(): String {
this.privateTest("foo");
return "<p>name: "+this.getName()+"</p>";
}
diff --git a/jooc/src/test/joo/package1/TestBind.as b/jooc/src/test/joo/package1/TestBind.as
new file mode 100644
index 000000000..c295fa1d5
--- /dev/null
+++ b/jooc/src/test/joo/package1/TestBind.as
@@ -0,0 +1,69 @@
+/*
+ * 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 {
+
+[Event]
+public class TestBind {
+
+ public function TestBind(state : String) {
+ this.state = state;
+ //joo.bind(this,"getState");
+ }
+
+ //[Bound]
+ public function getState() : String {
+ return this.state;
+ }
+
+ //[Bound]
+ private function getStatePrivate() : String {
+ return this.state;
+ }
+
+ public function testInvokeLocalVar() : * {
+ var f : Function = this.getState;
+ return f();
+ }
+
+ public function testInvokeLocalVarUnqualified() : * {
+ var f : Function = getState;
+ return f();
+ }
+
+ public function testInvokeParameter() : String {
+ return this.invoke(this.getState);
+ }
+
+ public function testInvokeParameterUnqualified() : String {
+ return invoke(getState);
+ }
+
+ public function testInvokeParameterUnqualifiedPrivate() : String {
+ return invoke(getStatePrivate);
+ }
+
+ public function testDelete() : Boolean {
+ delete this.testDelete;
+ return "testDelete" in this;
+ }
+
+ private function invoke(f : Function) : * {
+ return f();
+ }
+
+ private var state : String;
+}
+}
\ No newline at end of file
|
a2507a8f1c4e9b3c8d727653aaed2c4beaefc13d
|
elasticsearch
|
test: fix and simplify logic--
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/core/src/test/java/org/elasticsearch/common/network/NetworkAddressTests.java b/core/src/test/java/org/elasticsearch/common/network/NetworkAddressTests.java
index 4ccc9f716609e..5847bb75eeb5a 100644
--- a/core/src/test/java/org/elasticsearch/common/network/NetworkAddressTests.java
+++ b/core/src/test/java/org/elasticsearch/common/network/NetworkAddressTests.java
@@ -87,21 +87,13 @@ public void testNoScopeID() throws Exception {
/** creates address without any lookups. hostname can be null, for missing */
private InetAddress forge(String hostname, String address) throws IOException {
- if (hostname == null) {
- return InetAddress.getByName(address);
- } else {
- byte bytes[] = InetAddress.getByName(address).getAddress();
- return InetAddress.getByAddress(hostname, bytes);
- }
+ byte bytes[] = InetAddress.getByName(address).getAddress();
+ return InetAddress.getByAddress(hostname, bytes);
}
/** creates scoped ipv6 address without any lookups. hostname can be null, for missing */
private InetAddress forgeScoped(String hostname, String address, int scopeid) throws IOException {
byte bytes[] = InetAddress.getByName(address).getAddress();
- if (hostname == null) {
- return Inet6Address.getByAddress(hostname, bytes);
- } else {
- return Inet6Address.getByAddress(hostname, bytes, scopeid);
- }
+ return Inet6Address.getByAddress(hostname, bytes, scopeid);
}
}
|
73282a316e9b28a3854ff93b6fd95789d9cd40ef
|
restlet-framework-java
|
JAX-RS-Extension: - encoding of UriBuilder- parameters implemented--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java
index 3d36bc397d..8158f6639f 100644
--- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java
+++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java
@@ -74,6 +74,7 @@ public String resolve(String variableName) {
"The given array contains null value at position ("
+ i + ")");
varValue = value.toString();
+ varValue = EncodeOrCheck.all(varValue, encode);
i++;
retrievedValues.put(variableName, varValue);
}
@@ -178,7 +179,7 @@ private void addValidPathSegments(List<CharSequence> newPathSegments) {
*/
@Override
public URI build() throws UriBuilderException {
- Template template = new Template(toStringWithCheck(true));
+ Template template = new Template(toStringWithCheck(false));
return buildUri(template.format(NO_VAR_RESOLVER));
}
@@ -204,7 +205,6 @@ public URI build() throws UriBuilderException {
@SuppressWarnings("unchecked")
public URI build(final Map<String, Object> values)
throws IllegalArgumentException, UriBuilderException {
- // TODO encode values
Template template = new Template(toStringWithCheck(false));
return buildUri(template.format(new Resolver<String>() {
public String resolve(String variableName) {
@@ -213,7 +213,7 @@ public String resolve(String variableName) {
throw new IllegalArgumentException(
"The value Map must contain a value for all given Templet variables. The value for variable "
+ variableName + " is missing");
- return varValue.toString();
+ return EncodeOrCheck.all(varValue.toString(), encode);
}
}));
}
@@ -252,7 +252,6 @@ public URI build(Object... values) throws IllegalArgumentException,
}
Template template = new Template(toStringWithCheck(false));
return buildUri(template.format(new IteratorVariableResolver(values)));
- // TODO encode values
}
/**
diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java
index c7c9d0f357..06091beec4 100644
--- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java
+++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java
@@ -532,4 +532,29 @@ else if (c == '%') {
return stb;
// LATER userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
}
+
+ /**
+ * @param string
+ * @param encode
+ * @return
+ */
+ public static String all(CharSequence string, boolean encode) {
+ int length = string.length();
+ StringBuilder stb = new StringBuilder(length);
+ for (int i = 0; i < length; i++) {
+ char c = string.charAt(i);
+ if (Reference.isValid(c))
+ stb.append(c);
+ else if (c == '%') {
+ if (encode)
+ toHex(c, stb);
+ else {
+ checkForHexDigitAndAppend(string, i, stb);
+ i += 2;
+ }
+ } else
+ toHexOrReject(c, stb, encode);
+ }
+ return stb.toString();
+ }
}
\ No newline at end of file
|
3d1b29b41b22677fcdc47ec9631e15b973ca3d62
|
tapiji
|
Defines a team working set for "TapiJI Tool Suite"
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/team_project_sets.psf b/team_project_sets.psf
new file mode 100644
index 00000000..20cd9304
--- /dev/null
+++ b/team_project_sets.psf
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<psf version="2.0">
+<provider id="org.eclipse.egit.core.GitProvider">
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.core"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.core.pdeutils"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.editor"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.editor.nls"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.editor.rcp"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.editor.rcp.compat"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.core"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.core.ui"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.java"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.feature"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.java.ui"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.rbmanager"/>
+<project reference="1.0,https://code.google.com/a/eclipselabs.org/p/tapiji/,master,org.eclipse.babel.tapiji.tools.target"/>
+</provider>
+<workingSets editPageId="org.eclipse.jdt.ui.JavaWorkingSetPage" id="1354519122612_4" label="TapiJI Tool Suite" name="tapiji_tool_suite">
+<item elementID="=org.eclipse.babel.core" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.core.pdeutils" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.tapiji.tools.core.ui" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.tapiji.tools.java.ui" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/org.eclipse.babel.tapiji.tools.target" type="4"/>
+<item factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/org.eclipse.babel.tapiji.tools.java.feature" type="4"/>
+<item elementID="=org.eclipse.babel.tapiji.tools.core" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.tapiji.tools.rbmanager" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.tapiji.tools.java" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.editor.rcp" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item elementID="=org.eclipse.babel.editor" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+<item factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/org.eclipse.babel.editor.nls" type="4"/>
+<item elementID="=org.eclipse.babel.editor.rcp.compat" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/>
+</workingSets>
+</psf>
|
9ad12d9f43bfde5e0dbe836cac76a3d00fefc82d
|
Valadoc
|
docbook-parser: Accept symbols with trailing 's'
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index f102934e50..bb2d50005a 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -1395,7 +1395,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
- private Inline create_type_link (string name) {
+ private Inline create_type_link (string name, bool c_accept_plural = false) {
if (name == "TRUE" || name == "FALSE" || name == "NULL" || is_numeric (name)) {
var monospaced = factory.create_run (Run.Style.MONOSPACED);
monospaced.content.add (factory.create_text (name.down ()));
@@ -1403,6 +1403,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
} else {
Taglets.Link? taglet = factory.create_taglet ("link") as Taglets.Link;
assert (taglet != null);
+ taglet.c_accept_plural = c_accept_plural;
taglet.symbol_name = "c::"+name;
return taglet;
}
@@ -1625,16 +1626,16 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
next ();
} else if (current.type == TokenType.GTKDOC_SIGNAL) {
- run.content.add (this.create_type_link ("::"+current.content));
+ run.content.add (this.create_type_link ("::" + current.content, true));
next ();
} else if (current.type == TokenType.GTKDOC_PROPERTY) {
- run.content.add (this.create_type_link (":"+current.content));
+ run.content.add (this.create_type_link (":" + current.content, true));
next ();
} else if (current.type == TokenType.GTKDOC_CONST) {
- run.content.add (this.create_type_link (current.content));
+ run.content.add (this.create_type_link (current.content, true));
next ();
} else if (current.type == TokenType.GTKDOC_TYPE) {
- run.content.add (this.create_type_link (current.content));
+ run.content.add (this.create_type_link (current.content, true));
next ();
} else if (current.type == TokenType.NEWLINE || current.type == TokenType.SPACE) {
append_inline_content_string (run, " ");
|
3ff28bc8dc5d849263f9205cbe8ee8323dfbc318
|
Vala
|
Remove gedit from all-bindings as it will be shipped upstream
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/Makefile.am b/vapi/Makefile.am
index 12506367ad..30604b2735 100644
--- a/vapi/Makefile.am
+++ b/vapi/Makefile.am
@@ -388,7 +388,6 @@ GIR_BINDINGS = \
gdk-3.0 \
gdk-pixbuf-2.0 \
gdl-3.0 \
- gedit \
geocode-glib-1.0 \
gio-2.0 \
gobject-introspection-1.0 \
|
03351581d05f135185ba6e487986f14667b25cbe
|
hbase
|
HBASE-4606 Remove spam in HCM and fix a- list.size == 0--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1185326 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 0645ae1adc7e..22fafea1dab9 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -623,6 +623,7 @@ Release 0.92.0 - Unreleased
HBASE-4558 Refactor TestOpenedRegionHandler and TestOpenRegionHandler.(Ram)
HBASE-4558 Addendum for TestMasterFailover (Ram) - Breaks the build
HBASE-4568 Make zk dump jsp response faster
+ HBASE-4606 Remove spam in HCM and fix a list.size == 0
TASKS
diff --git a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
index 406e5e345493..f7fac44e8752 100644
--- a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
@@ -1400,12 +1400,9 @@ public <R> void processBatchCallback(
throw new IllegalArgumentException(
"argument results must be the same size as argument list");
}
- if (list.size() == 0) {
+ if (list.isEmpty()) {
return;
}
- if (LOG.isDebugEnabled()) {
- LOG.debug("expecting "+results.length+" results");
- }
// Keep track of the most recent servers for any given item for better
// exceptional reporting. We keep HRegionLocation to save on parsing.
|
b497f6ccad3eebcc6d475071bb7dd2741557d5e0
|
spring-framework
|
fixed JSR-303 Validator delegation code- (SPR-6557)--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java b/org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java
index d6a28c36365e..3b286bde07a9 100644
--- a/org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java
+++ b/org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java
@@ -121,7 +121,7 @@ public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propert
public <T> Set<ConstraintViolation<T>> validateValue(
Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
- return this.targetValidator.validateValue(beanType, propertyName, groups);
+ return this.targetValidator.validateValue(beanType, propertyName, value, groups);
}
public BeanDescriptor getConstraintsForClass(Class<?> clazz) {
|
3a424782b8663270000716b5dcc1b22a576c6467
|
Vala
|
Update gio vapi after vala-girs update
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi
index fbc4b3624d..01c2efcf8a 100644
--- a/vapi/gio-2.0.vapi
+++ b/vapi/gio-2.0.vapi
@@ -3637,7 +3637,7 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h", instance_pos = 6.9)]
public delegate GLib.Variant DBusInterfaceGetPropertyFunc (GLib.DBusConnection connection, string sender, string object_path, string interface_name, string property_name) throws GLib.Error;
[CCode (cheader_filename = "gio/gio.h", instance_pos = 7.9)]
- public delegate void DBusInterfaceMethodCallFunc (GLib.DBusConnection connection, string sender, string object_path, string interface_name, string method_name, GLib.Variant parameters, GLib.DBusMethodInvocation invocation);
+ public delegate void DBusInterfaceMethodCallFunc (GLib.DBusConnection connection, string sender, string object_path, string interface_name, string method_name, GLib.Variant parameters, owned GLib.DBusMethodInvocation invocation);
[CCode (cheader_filename = "gio/gio.h", instance_pos = 7.9)]
public delegate bool DBusInterfaceSetPropertyFunc (GLib.DBusConnection connection, string sender, string object_path, string interface_name, string property_name, GLib.Variant value) throws GLib.Error;
[CCode (cheader_filename = "gio/gio.h", instance_pos = 3.9)]
|
f6d8ce0ddb06773f1b9a269bdb94ac8840673d82
|
tapiji
|
Prepares maven pom files for building tapiji translator (RCP)
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF
index ac6e3ae8..c1fcc5b9 100644
--- a/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: RCP Compatibiltiy for TapiJI Translator
Bundle-SymbolicName: org.eclipselabs.tapiji.translator.swt.compat
-Bundle-Version: 0.0.2.qualifier
+Bundle-Version: 0.9.0.B1
Bundle-Activator: org.eclipselabs.tapiji.translator.compat.Activator
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.eclipselabs.tapiji.translator.swt.compat/pom.xml b/org.eclipselabs.tapiji.translator.swt.compat/pom.xml
new file mode 100644
index 00000000..dc9aaae2
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.swt.compat/pom.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+
+Copyright (c) 2012 Martin Reiterer
+
+All rights reserved. This program and the accompanying materials
+are made available under the terms of the Eclipse Public License
+v1.0 which accompanies this distribution, and is available at
+http://www.eclipse.org/legal/epl-v10.html
+
+Contributors: Martin Reiterer - setup of tycho build for tapiji translator
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>org.eclipselabs.tapiji.translator.swt.compat</artifactId>
+ <packaging>eclipse-plugin</packaging>
+
+ <parent>
+ <groupId>org.eclipselabs.tapiji</groupId>
+ <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId>
+ <version>0.9.0.B1</version>
+ <relativePath>..</relativePath>
+ </parent>
+
+ <version>0.9.0.B1</version>
+</project>
diff --git a/org.eclipselabs.tapiji.translator.swt.product/.classpath b/org.eclipselabs.tapiji.translator.swt.product/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.swt.product/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipselabs.tapiji.translator.swt.product/.project b/org.eclipselabs.tapiji.translator.swt.product/.project
new file mode 100644
index 00000000..650df245
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.swt.product/.project
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipselabs.tapiji.translator.swt.parent</name>
+ <comment></comment>
+ <projects>
+ </projects>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png
new file mode 100644
index 00000000..98514e0e
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png differ
diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png
new file mode 100644
index 00000000..73b82c2f
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png differ
diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png
new file mode 100644
index 00000000..3984eba6
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png differ
diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png
new file mode 100644
index 00000000..190a92e4
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png differ
diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png
new file mode 100644
index 00000000..89988073
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png differ
diff --git a/org.eclipselabs.tapiji.translator.swt/org.eclipselabs.tapiji.translator.product b/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product
similarity index 94%
rename from org.eclipselabs.tapiji.translator.swt/org.eclipselabs.tapiji.translator.product
rename to org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product
index ff6c0744..6b53d02a 100644
--- a/org.eclipselabs.tapiji.translator.swt/org.eclipselabs.tapiji.translator.product
+++ b/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<?pde version="3.5"?>
-<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.0.1" useFeatures="false" includeLaunchers="true">
+<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.rcp.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.9.0.B1" useFeatures="false" includeLaunchers="true">
<aboutInfo>
<image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/>
@@ -239,9 +239,7 @@ litigation.
<plugin id="org.eclipse.babel.core"/>
<plugin id="org.eclipse.babel.editor"/>
<plugin id="org.eclipse.babel.editor.nls" fragment="true"/>
- <plugin id="org.eclipse.babel.editor.rcp" fragment="true"/>
- <plugin id="org.eclipse.babel.editor.rcp.compat"/>
- <plugin id="org.eclipse.babel.tapiji.translator.rbe"/>
+ <plugin id="org.eclipse.babel.editor.swt" fragment="true"/>
<plugin id="org.eclipse.compare"/>
<plugin id="org.eclipse.compare.core"/>
<plugin id="org.eclipse.core.commands"/>
@@ -252,7 +250,6 @@ litigation.
<plugin id="org.eclipse.core.expressions"/>
<plugin id="org.eclipse.core.filebuffers"/>
<plugin id="org.eclipse.core.filesystem"/>
- <plugin id="org.eclipse.core.filesystem.linux.x86_64" fragment="true"/>
<plugin id="org.eclipse.core.jobs"/>
<plugin id="org.eclipse.core.resources"/>
<plugin id="org.eclipse.core.runtime"/>
@@ -288,11 +285,6 @@ litigation.
<plugin id="org.eclipse.equinox.simpleconfigurator"/>
<plugin id="org.eclipse.equinox.simpleconfigurator.manipulator"/>
<plugin id="org.eclipse.help"/>
- <plugin id="org.eclipse.jdt.compiler.apt" fragment="true"/>
- <plugin id="org.eclipse.jdt.compiler.tool" fragment="true"/>
- <plugin id="org.eclipse.jdt.core"/>
- <plugin id="org.eclipse.jdt.debug"/>
- <plugin id="org.eclipse.jdt.launching"/>
<plugin id="org.eclipse.jface"/>
<plugin id="org.eclipse.jface.databinding"/>
<plugin id="org.eclipse.jface.text"/>
@@ -300,10 +292,7 @@ litigation.
<plugin id="org.eclipse.ltk.ui.refactoring"/>
<plugin id="org.eclipse.osgi"/>
<plugin id="org.eclipse.osgi.services"/>
- <plugin id="org.eclipse.pde.build"/>
- <plugin id="org.eclipse.pde.core"/>
<plugin id="org.eclipse.swt"/>
- <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true"/>
<plugin id="org.eclipse.team.core"/>
<plugin id="org.eclipse.team.ui"/>
<plugin id="org.eclipse.text"/>
@@ -317,8 +306,7 @@ litigation.
<plugin id="org.eclipse.ui.workbench.texteditor"/>
<plugin id="org.eclipse.update.configurator"/>
<plugin id="org.eclipselabs.tapiji.translator"/>
- <plugin id="org.eclipselabs.tapiji.translator.rcp" fragment="true"/>
- <plugin id="org.eclipselabs.tapiji.translator.rcp.compat"/>
+ <plugin id="org.eclipselabs.tapiji.translator.swt.compat"/>
<plugin id="org.hamcrest.core"/>
<plugin id="org.junit"/>
<plugin id="org.sat4j.core"/>
diff --git a/org.eclipselabs.tapiji.translator.swt.product/pom.xml b/org.eclipselabs.tapiji.translator.swt.product/pom.xml
new file mode 100644
index 00000000..67d70438
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.swt.product/pom.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!-- Copyright (c) 2012 Martin Reiterer All rights reserved. This program
+ and the accompanying materials are made available under the terms of the
+ Eclipse Public License v1.0 which accompanies this distribution, and is available
+ at http://www.eclipse.org/legal/epl-v10.html Contributors: Martin Reiterer
+ - setup of tycho build for tapiji translator -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>org.eclipselabs.tapiji.translator.swt.product</artifactId>
+ <packaging>eclipse-application</packaging>
+
+ <parent>
+ <groupId>org.eclipselabs.tapiji</groupId>
+ <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId>
+ <version>0.9.0.B1</version>
+ <relativePath>..</relativePath>
+ </parent>
+
+<!-- <build>
+ <plugins>
+ <plugin>
+ <groupId>org.eclipse.tycho</groupId>
+ <artifactId>target-platform-configuration</artifactId>
+ <version>${tycho-version}</version>
+ <configuration>
+ <dependency-resolution>
+ <optionalDependencies>ignore</optionalDependencies>
+ <extraRequirements combine.children="append">
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipselabs.tapiji.translator.swt</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ </extraRequirements>
+ </dependency-resolution>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ -->
+</project>
diff --git a/org.eclipselabs.tapiji.translator.swt.product/splash.bmp b/org.eclipselabs.tapiji.translator.swt.product/splash.bmp
new file mode 100644
index 00000000..9283331e
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/splash.bmp differ
diff --git a/org.eclipselabs.tapiji.translator.swt/fragment.xml b/org.eclipselabs.tapiji.translator.swt/fragment.xml
index c5df4ff8..d7f1d28d 100644
--- a/org.eclipselabs.tapiji.translator.swt/fragment.xml
+++ b/org.eclipselabs.tapiji.translator.swt/fragment.xml
@@ -6,11 +6,11 @@
id="product"
point="org.eclipse.core.runtime.products">
<product
- application="org.eclipselabs.tapiji.application"
+ application="org.eclipse.ant.core.antRunner"
name="TapiJI Translator">
<property
name="windowImages"
- value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
+ value="platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png">
</property>
<property
name="appName"
@@ -18,7 +18,7 @@
</property>
<property
name="aboutImage"
- value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
+ value="platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png">
</property>
<property
name="aboutText"
diff --git a/org.eclipselabs.tapiji.translator.swt/pom.xml b/org.eclipselabs.tapiji.translator.swt/pom.xml
new file mode 100644
index 00000000..bf84602f
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.swt/pom.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+
+Copyright (c) 2012 Martin Reiterer
+
+All rights reserved. This program and the accompanying materials
+are made available under the terms of the Eclipse Public License
+v1.0 which accompanies this distribution, and is available at
+http://www.eclipse.org/legal/epl-v10.html
+
+Contributors: Martin Reiterer - setup of tycho build for tapiji translator
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>org.eclipselabs.tapiji.translator.swt</artifactId>
+ <packaging>eclipse-plugin</packaging>
+
+ <parent>
+ <groupId>org.eclipselabs.tapiji</groupId>
+ <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId>
+ <version>0.9.0.B1</version>
+ <relativePath>..</relativePath>
+ </parent>
+
+</project>
diff --git a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF
index 2eeeb311..8432e599 100644
--- a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: TapiJI Translator
Bundle-SymbolicName: org.eclipselabs.tapiji.translator;singleton:=true
-Bundle-Version: 0.0.2.qualifier
+Bundle-Version: 0.9.0.B1
Bundle-Activator: org.eclipselabs.tapiji.translator.Activator
Require-Bundle: org.eclipse.ui;resolution:=optional,
org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)",
diff --git a/org.eclipselabs.tapiji.translator/plugin.xml b/org.eclipselabs.tapiji.translator/plugin.xml
index 4e251edb..077db6a4 100644
--- a/org.eclipselabs.tapiji.translator/plugin.xml
+++ b/org.eclipselabs.tapiji.translator/plugin.xml
@@ -80,4 +80,48 @@
</property>
</product>
</extension>
+ <extension
+ id="product"
+ point="org.eclipse.core.runtime.products">
+ <product
+ application="org.eclipselabs.tapiji.translator.application"
+ name="TapiJI Translator">
+ <property
+ name="windowImages"
+ value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png">
+ </property>
+ <property
+ name="aboutText"
+ value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
+ </property>
+ <property
+ name="aboutImage"
+ value="icons/TapiJI_128.png">
+ </property>
+ </product>
+ </extension>
+ <extension
+ id="translator"
+ point="org.eclipse.core.runtime.products">
+ <product
+ application="org.eclipselabs.tapiji.translator.application"
+ name="TapiJI Translator">
+ <property
+ name="windowImages"
+ value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png">
+ </property>
+ <property
+ name="aboutText"
+ value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
+ </property>
+ <property
+ name="aboutImage"
+ value="icons/TapiJI_128.png">
+ </property>
+ <property
+ name="appName"
+ value="TapiJI Translator">
+ </property>
+ </product>
+ </extension>
</plugin>
diff --git a/org.eclipselabs.tapiji.translator/pom.xml b/org.eclipselabs.tapiji.translator/pom.xml
new file mode 100644
index 00000000..84cbce9f
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/pom.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!-- Copyright (c) 2012 Martin Reiterer All rights reserved. This program
+ and the accompanying materials are made available under the terms of the
+ Eclipse Public License v1.0 which accompanies this distribution, and is available
+ at http://www.eclipse.org/legal/epl-v10.html Contributors: Martin Reiterer
+ - setup of tycho build for tapiji translator -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>org.eclipselabs.tapiji.translator</artifactId>
+ <packaging>eclipse-plugin</packaging>
+
+ <parent>
+ <groupId>org.eclipselabs.tapiji</groupId>
+ <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId>
+ <version>0.9.0.B1</version>
+ <relativePath>..</relativePath>
+ </parent>
+
+</project>
diff --git a/pom.xml b/pom.xml
index dfa7fd1a..d4ce706f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,129 +1,194 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-Copyright (c) 2012 Martin Reiterer, Stefan Strobl
-
-All rights reserved. This program and the accompanying materials
-are made available under the terms of the Eclipse Public License
-v1.0 which accompanies this distribution, and is available at
-http://www.eclipse.org/legal/epl-v10.html
-
-Contributors:
- Martin Reiterer - setup of tycho build for babel tools
- Stefan Strobl - add eclipse signing plugin, babel p2 repository
-
--->
+<!-- Copyright (c) 2012 Martin Reiterer, Stefan Strobl All rights reserved.
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html Contributors:
+ Martin Reiterer - setup of tycho build for babel tools Stefan Strobl - add
+ eclipse signing plugin, babel p2 repository -->
<project
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
- xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.eclipse.babel.plugins</groupId>
- <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId>
- <version>0.0.2-SNAPSHOT</version>
- <packaging>pom</packaging>
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.eclipselabs.tapiji</groupId>
+ <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId>
+ <version>0.9.0.B1</version>
+ <packaging>pom</packaging>
-<!-- tycho requires maven >= 3.0 -->
- <prerequisites>
- <maven>3.0</maven>
- </prerequisites>
+ <modules>
+ <module>org.eclipselabs.tapiji.translator.swt.compat</module>
+ <module>org.eclipselabs.tapiji.translator</module>
+ <module>org.eclipselabs.tapiji.translator.swt.product</module>
+ </modules>
- <properties>
- <tycho-version>0.16.0</tycho-version>
- </properties>
- <repositories>
- <!-- configure p2 repository to resolve against -->
- <repository>
- <id>indigo</id>
- <layout>p2</layout>
- <url>http://download.eclipse.org/releases/indigo</url>
- </repository>
- </repositories>
+ <properties>
+ <tycho-version>0.16.0</tycho-version>
+ <eclipse-repository-url>http://download.eclipse.org/eclipse/updates/3.6</eclipse-repository-url>
+ <babel-plugins-url>http://build.eclipse.org/technology/babel/tools-updates-nightly</babel-plugins-url>
+ </properties>
- <pluginRepositories>
- <pluginRepository>
- <id>maven.eclipse.org</id>
- <url>http://maven.eclipse.org/nexus/content/repositories/milestone-indigo/</url>
- </pluginRepository>
- </pluginRepositories>
+ <profiles>
+ <profile>
+ <id>indigo rcp</id>
+ <properties>
+ <eclipse-repository-url>http://download.eclipse.org/releases/indigo</eclipse-repository-url>
+ <babel-plugins-url>http://build.eclipse.org/technology/babel/tools-updates-nightly</babel-plugins-url>
+ </properties>
+ <activation>
+ <activeByDefault>true</activeByDefault>
+ <property>
+ <name>maven.profile</name>
+ <value>swt-editor</value>
+ </property>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.eclipse.tycho</groupId>
+ <artifactId>target-platform-configuration</artifactId>
+ <version>${tycho-version}</version>
+ <configuration>
+ <!-- disable resolving of optional dependencies, but define the extra
+ dependencies -->
+ <dependency-resolution>
+ <optionalDependencies>ignore</optionalDependencies>
+ <extraRequirements>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipselabs.tapiji.translator.swt.compat</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.babel.editor.swt.compat</id>
+ <versionRange>0.9.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ui</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.jface.text</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ui.editors</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ui.ide</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ui.workbench.texteditor</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ui.forms</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ltk.core.refactoring</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ltk.ui.refactoring</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.junit</id>
+ <versionRange>0.0.0</versionRange>
+ </requirement>
+ <requirement>
+ <type>eclipse-plugin</type>
+ <id>org.eclipse.ui.forms</id>
+ <versionRange>3.5.101</versionRange>
+ </requirement>
+ </extraRequirements>
+ </dependency-resolution>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
- <build>
- <plugins>
- <plugin>
- <!-- enable tycho build extension -->
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>tycho-maven-plugin</artifactId>
- <version>${tycho-version}</version>
- <extensions>true</extensions>
- </plugin>
+ <repositories>
+ <repository>
+ <id>eclipse-repository</id>
+ <url>${eclipse-repository-url}</url>
+ <layout>p2</layout>
+ </repository>
+ <repository>
+ <id>babel-extension-plugins</id>
+ <url>${babel-plugins-url}</url>
+ <layout>p2</layout>
+ </repository>
+ </repositories>
- <!-- enable source bundle generation -->
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>tycho-source-plugin</artifactId>
- <version>${tycho-version}</version>
- <executions>
- <execution>
- <id>plugin-source</id>
- <goals>
- <goal>plugin-source</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.eclipse.tycho</groupId>
+ <artifactId>tycho-maven-plugin</artifactId>
+ <version>${tycho-version}</version>
+ <extensions>true</extensions>
+ </plugin>
+ <plugin>
+ <groupId>org.eclipse.tycho</groupId>
+ <artifactId>target-platform-configuration</artifactId>
+ <version>${tycho-version}</version>
+ <configuration>
+ <environments>
+ <environment>
+ <os>linux</os>
+ <ws>gtk</ws>
+ <arch>x86_64</arch>
+ </environment>
+ <environment>
+ <os>linux</os>
+ <ws>gtk</ws>
+ <arch>x86</arch>
+ </environment>
+ <environment>
+ <os>macosx</os>
+ <ws>carbon</ws>
+ <arch>x86</arch>
+ </environment>
+ <environment>
+ <os>macosx</os>
+ <ws>cocoa</ws>
+ <arch>x86</arch>
+ </environment>
+ <environment>
+ <os>macosx</os>
+ <ws>cocoa</ws>
+ <arch>x86_64</arch>
+ </environment>
+ <environment>
+ <os>win32</os>
+ <ws>win32</ws>
+ <arch>x86</arch>
+ </environment>
+ <environment>
+ <os>win32</os>
+ <ws>win32</ws>
+ <arch>x86_64</arch>
+ </environment>
+ </environments>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>target-platform-configuration</artifactId>
- <version>${tycho-version}</version>
- <configuration>
- <target>
- <artifact>
- <groupId>org.eclipse.babel.plugins</groupId>
- <artifactId>org.eclipse.babel.tapiji.tools.target</artifactId>
- <version>0.0.2-SNAPSHOT</version>
- </artifact>
- </target>
- <!-- configure the p2 target environments for multi-platform build -->
- <environments>
- <environment>
- <os>linux</os>
- <ws>gtk</ws>
- <arch>x86_64</arch>
- </environment>
- <environment>
- <os>win32</os>
- <ws>win32</ws>
- <arch>x86_64</arch>
- </environment>
- </environments>
- </configuration>
- </plugin>
- </plugins>
- <pluginManagement>
- <plugins>
- <!-- provide maven singing plugin for babel.repository pom -->
- <plugin>
- <groupId>org.eclipse.dash.maven</groupId>
- <artifactId>eclipse-signing-maven-plugin</artifactId>
- <version>1.0.5</version>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- <modules>
- <module>org.eclipse.babel.core</module>
- <module>org.eclipse.babel.editor</module>
- <module>org.eclipse.babel.tapiji.tools.core</module>
- <module>org.eclipse.babel.tapiji.tools.core.ui</module>
- <module>org.eclipse.babel.tapiji.tools.java</module>
- <module>org.eclipse.babel.tapiji.tools.java.feature</module>
- <module>org.eclipse.babel.tapiji.tools.java.ui</module>
- <module>org.eclipse.babel.tapiji.tools.rbmanager</module>
- <module>org.eclipse.babel.editor.nls</module>
- <module>org.eclipse.babel.tapiji.tools.target</module>
- <module>org.eclipse.babel.core.pdeutils</module>
- <module>org.eclipse.babel.repository</module>
- </modules>
</project>
|
db14c09d6257c537ce0b77f004410ce1606db73f
|
ReactiveX-RxJava
|
1.x: Expose Single.lift()--
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java
index 3489f1a55c..b7e99671d2 100644
--- a/src/main/java/rx/Single.java
+++ b/src/main/java/rx/Single.java
@@ -163,9 +163,8 @@ public interface OnSubscribe<T> extends Action1<SingleSubscriber<? super T>> {
* @return a Single that is the result of applying the lifted Operator to the source Single
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators">RxJava wiki: Implementing Your Own Operators</a>
*/
- private <R> Single<R> lift(final Operator<? extends R, ? super T> lift) {
- // This method is private because not sure if we want to expose the Observable.Operator in this public API rather than a Single.Operator
-
+ @Experimental
+ public final <R> Single<R> lift(final Operator<? extends R, ? super T> lift) {
return new Single<R>(new Observable.OnSubscribe<R>() {
@Override
public void call(Subscriber<? super R> o) {
|
1eebb3a020b0a91f153cf313bd90b0600b94a56f
|
Valadoc
|
gir-importer: Process implicit parameters
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/Makefile.am b/src/libvaladoc/Makefile.am
index b54bbdef18..7ec0b656ff 100644
--- a/src/libvaladoc/Makefile.am
+++ b/src/libvaladoc/Makefile.am
@@ -55,6 +55,7 @@ libvaladoc_la_VALASOURCES = \
api/attributeargument.vala \
api/attribute.vala \
api/array.vala \
+ api/callable.vala \
api/childsymbolregistrar.vala \
api/class.vala \
api/constant.vala \
diff --git a/src/libvaladoc/api/callable.vala b/src/libvaladoc/api/callable.vala
new file mode 100644
index 0000000000..60515ee1b5
--- /dev/null
+++ b/src/libvaladoc/api/callable.vala
@@ -0,0 +1,51 @@
+/* callable.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:
+ * Florian Brosch <[email protected]>
+ */
+
+
+using Valadoc;
+using GLib;
+using Gee;
+
+
+/**
+ * Used to translate imported C-documentation
+ */
+public interface Valadoc.Api.Callable : Symbol {
+ /**
+ * The return type of this symbol.
+ *
+ * @return The return type of this symbol or null for void
+ */
+ public abstract TypeReference? return_type {
+ set;
+ get;
+ }
+
+ /**
+ * Used to avoid warnings for implicit parameters
+ */
+ internal abstract string? implicit_array_length_cparameter_name {
+ get;
+ set;
+ }
+}
+
diff --git a/src/libvaladoc/api/delegate.vala b/src/libvaladoc/api/delegate.vala
index 2e4379163b..d57c80d602 100644
--- a/src/libvaladoc/api/delegate.vala
+++ b/src/libvaladoc/api/delegate.vala
@@ -27,9 +27,18 @@ using Valadoc.Content;
/**
* Represents a Delegate.
*/
-public class Valadoc.Api.Delegate : TypeSymbol {
+public class Valadoc.Api.Delegate : TypeSymbol, Callable {
private string? cname;
+ /**
+ * {@inheritDoc}
+ */
+ internal string? implicit_array_length_cparameter_name {
+ get;
+ set;
+ }
+
+
public Delegate (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, bool is_static, void* data) {
base (parent, file, name, accessibility, comment, false, data);
@@ -45,9 +54,7 @@ public class Valadoc.Api.Delegate : TypeSymbol {
}
/**
- * The return type of this callback.
- *
- * @return The return type of this callback or null for void
+ * {@inheritDoc}
*/
public TypeReference? return_type {
set;
diff --git a/src/libvaladoc/api/formalparameter.vala b/src/libvaladoc/api/formalparameter.vala
index 0a781e31f3..82ed872a22 100644
--- a/src/libvaladoc/api/formalparameter.vala
+++ b/src/libvaladoc/api/formalparameter.vala
@@ -32,6 +32,30 @@ public class Valadoc.Api.FormalParameter : Symbol {
set;
}
+ /**
+ * Used to translate imported C-documentation
+ */
+ internal string? implicit_array_length_cparameter_name {
+ get;
+ set;
+ }
+
+ /**
+ * Used to translate imported C-documentation
+ */
+ internal string? implicit_closure_cparameter_name {
+ get;
+ set;
+ }
+
+ /**
+ * Used to translate imported C-documentation
+ */
+ internal string? implicit_destroy_cparameter_name {
+ get;
+ set;
+ }
+
private FormalParameterType type;
public FormalParameter (Node parent, SourceFile file, string? name, SymbolAccessibility accessibility, FormalParameterType type, bool ellipsis, void* data) {
diff --git a/src/libvaladoc/api/method.vala b/src/libvaladoc/api/method.vala
index 0a142e3d20..d222bf0cc0 100644
--- a/src/libvaladoc/api/method.vala
+++ b/src/libvaladoc/api/method.vala
@@ -20,14 +20,14 @@
* Florian Brosch <[email protected]>
*/
-using Gee;
using Valadoc.Content;
+using Gee;
/**
* Represents a function or a method.
*/
-public class Valadoc.Api.Method : Member {
+public class Valadoc.Api.Method : Member, Callable {
private string? finish_function_cname;
private string? dbus_result_name;
private string? dbus_name;
@@ -35,6 +35,15 @@ public class Valadoc.Api.Method : Member {
private MethodBindingType binding_type;
+ /**
+ * {@inheritDoc}
+ */
+ internal string? implicit_array_length_cparameter_name {
+ get;
+ set;
+ }
+
+
public Method (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? dbus_name, string? dbus_result_name, string? finish_function_cname, MethodBindingType binding_type, bool is_yields, bool is_dbus_visible, bool is_constructor, void* data) {
base (parent, file, name, accessibility, comment, data);
@@ -83,9 +92,7 @@ public class Valadoc.Api.Method : Member {
}
/**
- * The return type of this method.
- *
- * @return The return type of this method or null for void
+ * {@inheritDoc}
*/
public TypeReference? return_type {
set;
diff --git a/src/libvaladoc/api/signal.vala b/src/libvaladoc/api/signal.vala
index 87a380cdb2..0e21dfb812 100644
--- a/src/libvaladoc/api/signal.vala
+++ b/src/libvaladoc/api/signal.vala
@@ -27,10 +27,20 @@ using Valadoc.Content;
/**
* Represents an signal.
*/
-public class Valadoc.Api.Signal : Member {
+public class Valadoc.Api.Signal : Member, Callable {
private string? dbus_name;
private string? cname;
+
+ /**
+ * {@inheritDoc}
+ */
+ internal string? implicit_array_length_cparameter_name {
+ get;
+ set;
+ }
+
+
public Signal (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? dbus_name, bool is_dbus_visible, bool is_virtual, void* data) {
base (parent, file, name, accessibility, comment, data);
@@ -56,9 +66,7 @@ public class Valadoc.Api.Signal : Member {
}
/**
- * The return type of this signal.
- *
- * @return The return type of this signal or null for void
+ * {@inheritDoc}
*/
public TypeReference? return_type {
set;
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index 79392168a5..eb154ad2f1 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -1537,15 +1537,13 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
- return null;
+ return {id};
}
- private string? resolve_parameter_ctype (string parameter_name, out string? param_name) {
- string[]? parts = split_type_name (current.content);
- param_name = null;
- if (parts == null) {
- return null;
- }
+ private string? resolve_parameter_ctype (string parameter_name, out string? param_name, out string? param_array_name, out bool is_return_type_len) {
+ string[]? parts = split_type_name (parameter_name);
+ is_return_type_len = false;
+ param_array_name = null;
Api.FormalParameter? param = null; // type parameter or formal parameter
foreach (Api.Node node in this.element.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false)) {
@@ -1553,10 +1551,31 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
param = node as Api.FormalParameter;
break;
}
+
+ if (((Api.FormalParameter) node).implicit_array_length_cparameter_name == parts[0]) {
+ param_array_name = ((Api.FormalParameter) node).name;
+ break;
+ }
}
+ if (this.element is Api.Callable && ((Api.Callable) this.element).implicit_array_length_cparameter_name == parts[0]) {
+ is_return_type_len = true;
+ }
+
+ if (parts.length == 1) {
+ param_name = parameter_name;
+ return null;
+ }
+
+
+ Api.Item? inner = null;
+
+ if (param_array_name != null || is_return_type_len) {
+ inner = tree.search_symbol_str (null, "int");
+ } else if (param != null) {
+ inner = param.parameter_type;
+ }
- Api.Item? inner = param.parameter_type;
while (inner != null) {
if (inner is Api.TypeReference) {
inner = ((Api.TypeReference) inner).data_type;
@@ -1571,6 +1590,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
if (inner == null) {
+ param_name = parameter_name;
return null;
}
@@ -1671,17 +1691,27 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
run.content.add (this.create_type_link (current.content));
next ();
} else if (current.type == TokenType.GTKDOC_PARAM) {
+ string? param_array_name;
+ bool is_return_type_len;
string? param_name;
- string? cname = resolve_parameter_ctype (current.content, out param_name);
+
+ string? cname = resolve_parameter_ctype (current.content, out param_name, out param_array_name, out is_return_type_len);
Run current_run = factory.create_run (Run.Style.MONOSPACED);
+ run.content.add (current_run);
- if (cname == null) {
- current_run.content.add (factory.create_text (current.content));
- run.content.add (current_run);
+ if (is_return_type_len) {
+ Run keyword_run = factory.create_run (Run.Style.LANG_KEYWORD);
+ keyword_run.content.add (factory.create_text ("return"));
+ current_run.content.add (keyword_run);
+
+ current_run.content.add (factory.create_text (".length"));
+ } else if (param_array_name != null) {
+ current_run.content.add (factory.create_text (param_array_name + ".length"));
} else {
current_run.content.add (factory.create_text (param_name));
- run.content.add (current_run);
+ }
+ if (cname != null) {
run.content.add (factory.create_text ("."));
Taglets.Link link = factory.create_taglet ("link") as Taglets.Link;
diff --git a/src/libvaladoc/errorreporter.vala b/src/libvaladoc/errorreporter.vala
index 073eb4b3d1..b7359820d5 100644
--- a/src/libvaladoc/errorreporter.vala
+++ b/src/libvaladoc/errorreporter.vala
@@ -42,8 +42,9 @@ public class Valadoc.ErrorReporter : Object {
set;
}
- public ErrorReporter () {
- this.stream = GLib.stderr;
+ public Settings? settings {
+ get;
+ set;
}
public int errors {
@@ -58,6 +59,12 @@ public class Valadoc.ErrorReporter : Object {
}
}
+
+ public ErrorReporter (Settings? settings = null) {
+ this.stream = GLib.stderr;
+ this.settings = settings;
+ }
+
private inline void msg (string type, string file, long line, long startpos, long endpos, string errline, string msg_format, va_list args) {
this.stream.printf ("%s:%lu.%lu-%lu.%lu: %s: ", file, line, startpos, line, endpos, type);
this.stream.vprintf (msg_format, args);
@@ -92,6 +99,15 @@ public class Valadoc.ErrorReporter : Object {
this._errors++;
}
+ public void simple_note (string msg_format, ...) {
+ if (_settings == null || _settings.verbose) {
+ var args = va_list();
+ this.stream.vprintf (msg_format, args);
+ this.stream.putc ('\n');
+ this._warnings++;
+ }
+ }
+
public void error (string file, long line, long startpos, long endpos, string errline, string msg_format, ...) {
var args = va_list();
this.msg ("error", file, line, startpos, endpos, errline, msg_format, args);
diff --git a/src/libvaladoc/importer/girdocumentationimporter.vala b/src/libvaladoc/importer/girdocumentationimporter.vala
index 789409b2ed..d097e26fda 100644
--- a/src/libvaladoc/importer/girdocumentationimporter.vala
+++ b/src/libvaladoc/importer/girdocumentationimporter.vala
@@ -1,8 +1,8 @@
/* girdocumentationimporter.vala
*
* Copyright (C) 2008-2010 Jürg Billeter
- * Copyright (C) 2011 Luca Bruno
- * Copyright (C) 2011 Florian Brosch
+ * Copyright (C) 2011 Luca Bruno
+ * Copyright (C) 2011-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
@@ -27,7 +27,7 @@
using Valadoc;
using GLib;
-
+using Gee;
public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
@@ -44,6 +44,16 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
private string parent_c_identifier;
+ private struct ImplicitParameterPos {
+ public int parameter;
+ public int position;
+
+ public ImplicitParameterPos (int parameter, int position) {
+ this.parameter = parameter;
+ this.position = position;
+ }
+ }
+
public GirDocumentationImporter (Api.Tree tree, DocumentationParser parser, ModuleLoader modules, Settings settings, ErrorReporter reporter) {
base (tree, modules, settings);
this.reporter = reporter;
@@ -65,7 +75,26 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
file = null;
}
- private void attach_comment (string cname, Api.GirSourceComment? comment) {
+ private Api.FormalParameter? find_parameter (Api.Node node, string name) {
+ Gee.List<Api.Node> parameters = node.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false);
+ foreach (Api.Node param in parameters) {
+ if (((Api.FormalParameter) param).name == name) {
+ return (Api.FormalParameter) param;
+ }
+ }
+
+ return null;
+ }
+
+ private inline string? get_cparameter_name (string[] param_names, int length_pos) {
+ if (length_pos < 0 || param_names.length < length_pos) {
+ return null;
+ }
+
+ return param_names[length_pos];
+ }
+
+ private void attach_comment (string cname, Api.GirSourceComment? comment, string[]? param_names = null, ImplicitParameterPos[]? destroy_notifies = null, ImplicitParameterPos[]? closures = null, ImplicitParameterPos[]? array_lengths = null, int array_length_ret = -1) {
if (comment == null) {
return ;
}
@@ -75,6 +104,39 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
return;
}
+ if (param_names != null) {
+ foreach (ImplicitParameterPos pos in destroy_notifies) {
+ Api.FormalParameter? param = find_parameter (node, param_names[pos.parameter]);
+ if (param == null) {
+ continue ;
+ }
+
+ param.implicit_destroy_cparameter_name = get_cparameter_name (param_names, pos.position);
+ }
+
+ foreach (ImplicitParameterPos pos in closures) {
+ Api.FormalParameter? param = find_parameter (node, param_names[pos.parameter]);
+ if (param == null) {
+ continue ;
+ }
+
+ param.implicit_closure_cparameter_name = get_cparameter_name (param_names, pos.position);
+ }
+
+ foreach (ImplicitParameterPos pos in array_lengths) {
+ Api.FormalParameter? param = find_parameter (node, param_names[pos.parameter]);
+ if (param == null) {
+ continue ;
+ }
+
+ param.implicit_array_length_cparameter_name = get_cparameter_name (param_names, pos.position);
+ }
+
+ if (node is Api.Callable) {
+ ((Api.Callable) node).implicit_array_length_cparameter_name = get_cparameter_name (param_names, array_length_ret);
+ }
+ }
+
Content.Comment? content = this.parser.parse (node, comment);
if (content == null) {
return;
@@ -83,6 +145,10 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
node.documentation = content;
}
+ private void warning (string message) {
+ reporter.warning (this.file.relative_path, this.begin.line, this.begin.column, this.end.column, this.reader.get_line_content (this.begin.line), message);
+ }
+
private void error (string message) {
reporter.error (this.file.relative_path, this.begin.line, this.begin.column, this.end.column, this.reader.get_line_content (this.begin.line), message);
}
@@ -299,20 +365,39 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
end_element ("member");
}
- private void parse_return_value (out Api.SourceComment? comment = null) {
+ private void parse_return_value (out Api.SourceComment? comment, out int array_length_ret) {
start_element ("return-value");
next ();
comment = parse_doc ();
- parse_type ();
+ parse_type (out array_length_ret);
end_element ("return-value");
}
- private void parse_parameter (out Api.SourceComment? comment, out string param_name) {
+ private void parse_parameter (out Api.SourceComment? comment, out string param_name, out int destroy_pos, out int closure_pos, out int array_length_pos) {
start_element ("parameter");
param_name = reader.get_attribute ("name");
+ array_length_pos = -1;
+ destroy_pos = -1;
+ closure_pos = -1;
+
+ string? closure = reader.get_attribute ("closure");
+ if (closure != null) {
+ closure_pos = int.parse (closure);
+ if (closure_pos < 0) {
+ warning ("invalid closure position");
+ }
+ }
+
+ string? destroy = reader.get_attribute ("destroy");
+ if (destroy != null) {
+ destroy_pos = int.parse (destroy);
+ if (destroy_pos < 0) {
+ warning ("invalid destroy position");
+ }
+ }
next ();
comment = parse_doc ();
@@ -324,14 +409,28 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
end_element ("varargs");
} else {
- parse_type ();
+ parse_type (out array_length_pos);
}
end_element ("parameter");
}
- private void parse_type () {
- skip_element ();
+ private void parse_type (out int array_length_pos = null) {
+ array_length_pos = -1;
+
+ if (reader.name == "array") {
+ string? length = reader.get_attribute ("length");
+ if (length != null) {
+ array_length_pos = int.parse (length);
+ if (array_length_pos < 0) {
+ warning ("invalid array lenght position");
+ }
+ }
+
+ skip_element ();
+ } else {
+ skip_element ();
+ }
}
private void parse_record () {
@@ -508,9 +607,15 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
Api.GirSourceComment? comment = parse_symbol_doc ();
+ ImplicitParameterPos[] destroy_notifies = new ImplicitParameterPos[0];
+ ImplicitParameterPos[] array_lengths = new ImplicitParameterPos[0];
+ ImplicitParameterPos[] closures = new ImplicitParameterPos[0];
+ string[] param_names = new string[0];
+ int array_length_ret = -1;
+
if (current_token == MarkupTokenType.START_ELEMENT && reader.name == "return-value") {
Api.SourceComment? return_comment;
- parse_return_value (out return_comment);
+ parse_return_value (out return_comment, out array_length_ret);
if (return_comment != null) {
if (comment == null) {
comment = new Api.GirSourceComment ("", file, begin.line, begin.column, end.line, end.column);
@@ -524,11 +629,27 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
start_element ("parameters");
next ();
- while (current_token == MarkupTokenType.START_ELEMENT) {
+ for (int pcount = 0; current_token == MarkupTokenType.START_ELEMENT; pcount++) {
Api.SourceComment? param_comment;
+ int array_length_pos;
+ int destroy_pos;
+ int closure_pos;
string? param_name;
- parse_parameter (out param_comment, out param_name);
+ parse_parameter (out param_comment, out param_name, out destroy_pos, out closure_pos, out array_length_pos);
+ param_names += param_name;
+
+ if (destroy_pos >= 0 && pcount != destroy_pos) {
+ destroy_notifies += ImplicitParameterPos (pcount, destroy_pos);
+ }
+
+ if (closure_pos >= 0 && pcount != closure_pos) {
+ closures += ImplicitParameterPos (pcount, closure_pos);
+ }
+
+ if (array_length_pos >= 0 && pcount != destroy_pos) {
+ array_lengths += ImplicitParameterPos (pcount, array_length_pos);
+ }
if (param_comment != null) {
if (comment == null) {
@@ -541,7 +662,7 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
end_element ("parameters");
}
- attach_comment (c_identifier, comment);
+ attach_comment (c_identifier, comment, param_names, destroy_notifies, closures, array_lengths, array_length_ret);
end_element (element_name);
}
diff --git a/src/libvaladoc/taglets/tagletlink.vala b/src/libvaladoc/taglets/tagletlink.vala
index 49699a5c7f..d49aa4b84e 100644
--- a/src/libvaladoc/taglets/tagletlink.vala
+++ b/src/libvaladoc/taglets/tagletlink.vala
@@ -84,6 +84,7 @@ public class Valadoc.Taglets.Link : InlineTaglet {
link.symbol = _symbol;
link.label = symbol_name;
+ // TODO: move typeof () to gtkdoc-importer
switch (_context) {
case SymbolContext.TYPE:
Content.Run content = new Content.Run (Run.Style.MONOSPACED);
diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala
index 36a21eb6bc..78e9d163d3 100644
--- a/src/libvaladoc/taglets/tagletparam.vala
+++ b/src/libvaladoc/taglets/tagletparam.vala
@@ -21,8 +21,8 @@
* Didier 'Ptitjes Villevalois <[email protected]>
*/
-using Gee;
using Valadoc.Content;
+using Gee;
public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
@@ -40,11 +40,21 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
});
}
-
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
// Check for the existence of such a parameter
+ unowned string? implicit_return_array_length = null;
+ bool is_implicit = false;
this.parameter = null;
+ if (container is Api.Callable) {
+ implicit_return_array_length = ((Api.Callable) container).implicit_array_length_cparameter_name;
+ } else {
+ reporter.simple_warning ("%s: %s: @param: warning: @param used outside method/delegate/signal context", file_path, container.get_full_name ());
+ base.check (api_root, container, file_path, reporter, settings);
+ return ;
+ }
+
+
if (parameter_name == "...") {
Gee.List<Api.Node> params = container.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false);
foreach (Api.Node param in params) {
@@ -65,12 +75,27 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
break;
}
+ Api.FormalParameter formalparam = param as Api.FormalParameter;
+ if (formalparam != null && (formalparam.implicit_array_length_cparameter_name == parameter_name || formalparam.implicit_closure_cparameter_name == parameter_name || formalparam.implicit_destroy_cparameter_name == parameter_name)) {
+ is_implicit = true;
+ break;
+ }
+
pos++;
}
+
+ if (this.parameter == null && (parameter_name == "error" && container.has_children ({Api.NodeType.ERROR_DOMAIN, Api.NodeType.CLASS})
+ || parameter_name == implicit_return_array_length)) {
+ is_implicit = true;
+ }
}
if (this.parameter == null) {
- reporter.simple_warning ("%s: %s: @param: warning: Unknown parameter `%s'", file_path, container.get_full_name (), parameter_name);
+ if (is_implicit) {
+ reporter.simple_note ("%s: %s: @param: warning: Implicit parameter `%s' exposed in documentation", file_path, container.get_full_name (), parameter_name);
+ } else {
+ reporter.simple_warning ("%s: %s: @param: warning: Unknown parameter `%s'", file_path, container.get_full_name (), parameter_name);
+ }
}
base.check (api_root, container, file_path, reporter, settings);
diff --git a/src/libvaladoc/taglets/tagletreturn.vala b/src/libvaladoc/taglets/tagletreturn.vala
index 655fb7ace9..e616791f64 100644
--- a/src/libvaladoc/taglets/tagletreturn.vala
+++ b/src/libvaladoc/taglets/tagletreturn.vala
@@ -37,10 +37,8 @@ public class Valadoc.Taglets.Return : InlineContent, Taglet, Block {
if (container is Api.Method) {
creation_method = ((Api.Method) container).is_constructor;
type_ref = ((Api.Method) container).return_type;
- } else if (container is Api.Delegate) {
- type_ref = ((Api.Delegate) container).return_type;
- } else if (container is Api.Signal) {
- type_ref = ((Api.Signal) container).return_type;
+ } else if (container is Api.Callable) {
+ type_ref = ((Api.Callable) container).return_type;
} else {
reporter.simple_warning ("%s: %s: @return: warning: @return used outside method/delegate/signal context", file_path, container.get_full_name ());
}
diff --git a/src/valadoc/valadoc.vala b/src/valadoc/valadoc.vala
index 7c6bdba5a8..cca16b167c 100644
--- a/src/valadoc/valadoc.vala
+++ b/src/valadoc/valadoc.vala
@@ -198,6 +198,8 @@ public class ValaDoc : Object {
private int run (ErrorReporter reporter) {
// settings:
var settings = new Valadoc.Settings ();
+ reporter.settings = settings;
+
settings.pkg_name = this.get_pkg_name ();
settings.gir_namespace = this.gir_namespace;
settings.gir_version = this.gir_version;
|
a1bf55c5541b45552708fa76b04e24419604825b
|
camel
|
Minor cleanup--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@712728 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java
index f88b5bd99ee8c..120a7d63eba3e 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java
@@ -38,7 +38,6 @@ public class DefaultUnitOfWork implements UnitOfWork, Service {
private String id;
private List<Synchronization> synchronizations;
private List<AsyncCallback> asyncCallbacks;
- private CountDownLatch latch;
public DefaultUnitOfWork() {
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java b/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java
index db5319995fc07..2d8d5760579af 100644
--- a/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java
+++ b/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java
@@ -150,8 +150,15 @@ public ObjectName getObjectName(ManagedRoute mbean) throws MalformedObjectNameEx
public ObjectName getObjectName(RouteContext routeContext, ProcessorType processor)
throws MalformedObjectNameException {
Endpoint<? extends Exchange> ep = routeContext.getEndpoint();
- String ctxid = ep != null ? getContextId(ep.getCamelContext()) : VALUE_UNKNOWN;
- String cid = ObjectName.quote(ep.getEndpointUri());
+ String ctxid;
+ String cid;
+ if (ep != null) {
+ ctxid = getContextId(ep.getCamelContext());
+ cid = ObjectName.quote(ep.getEndpointUri());
+ } else {
+ ctxid = VALUE_UNKNOWN;
+ cid = null;
+ }
//String id = VALUE_UNKNOWN.equals(cid) ? ObjectName.quote(getEndpointId(ep) : "[" + cid + "]" + ObjectName.quote(getEndpointId(ep);
String nodeId = processor.idOrCreate();
diff --git a/camel-core/src/main/java/org/apache/camel/model/RouteType.java b/camel-core/src/main/java/org/apache/camel/model/RouteType.java
index 04307bb4712a1..ec3901c1e1469 100644
--- a/camel-core/src/main/java/org/apache/camel/model/RouteType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/RouteType.java
@@ -78,11 +78,9 @@ public String toString() {
public void addRoutes(CamelContext context, Collection<Route> routes) throws Exception {
setCamelContext(context);
- if (context instanceof CamelContext) {
- ErrorHandlerBuilder handler = context.getErrorHandlerBuilder();
- if (handler != null) {
- setErrorHandlerBuilderIfNull(handler);
- }
+ ErrorHandlerBuilder handler = context.getErrorHandlerBuilder();
+ if (handler != null) {
+ setErrorHandlerBuilderIfNull(handler);
}
for (FromType fromType : inputs) {
diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java
index 83342f78bfe44..a076b572596e8 100644
--- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java
+++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java
@@ -120,8 +120,7 @@ protected void logException(Exchange exchange, Throwable throwable) {
* Returns true if the given exchange should be logged in the trace list
*/
protected boolean shouldLogExchange(Exchange exchange) {
- return (tracer == null || tracer.isEnabled())
- && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange));
+ return tracer.isEnabled() && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange));
}
/**
|
fa9c04520d88cce7068ce84ddc539ad4b93ba045
|
Vala
|
gio-2.0: Add lots of default values, mostly for Cancellable parameters
Fixes bug 613471.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi
index 311400d493..8eaa34db59 100644
--- a/vapi/gio-2.0.vapi
+++ b/vapi/gio-2.0.vapi
@@ -77,13 +77,13 @@ namespace GLib {
public class BufferedInputStream : GLib.FilterInputStream {
[CCode (type = "GInputStream*", has_construct_function = false)]
public BufferedInputStream (GLib.InputStream base_stream);
- public virtual ssize_t fill (ssize_t count, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async ssize_t fill_async (ssize_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual ssize_t fill (ssize_t count, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async ssize_t fill_async (ssize_t count, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public size_t get_available ();
public size_t get_buffer_size ();
public size_t peek (void* buffer, size_t offset, size_t count);
public void* peek_buffer (out size_t count);
- public int read_byte (GLib.Cancellable? cancellable) throws GLib.Error;
+ public int read_byte (GLib.Cancellable? cancellable = null) throws GLib.Error;
public void set_buffer_size (size_t size);
[CCode (type = "GInputStream*", has_construct_function = false)]
public BufferedInputStream.sized (GLib.InputStream base_stream, size_t size);
@@ -185,16 +185,16 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class DBusConnection : GLib.Object, GLib.Initable, GLib.AsyncInitable {
[CCode (type = "void", has_construct_function = false)]
- public async DBusConnection (GLib.IOStream stream, string guid, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async DBusConnection (GLib.IOStream stream, string guid, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable = null) throws GLib.Error;
public uint add_filter (GLib.DBusMessageFilterFunction filter_function, GLib.DestroyNotify user_data_free_func);
- public async GLib.Variant call (string bus_name, string object_path, string interface_name, string method_name, GLib.Variant parameters, GLib.VariantType reply_type, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable) throws GLib.Error;
- public GLib.Variant call_sync (string bus_name, string object_path, string interface_name, string method_name, GLib.Variant parameters, GLib.VariantType reply_type, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async GLib.Variant call (string bus_name, string object_path, string interface_name, string method_name, GLib.Variant parameters, GLib.VariantType reply_type, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public GLib.Variant call_sync (string bus_name, string object_path, string interface_name, string method_name, GLib.Variant parameters, GLib.VariantType reply_type, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void close ();
public bool emit_signal (string destination_bus_name, string object_path, string interface_name, string signal_name, GLib.Variant parameters) throws GLib.Error;
[CCode (type = "void", has_construct_function = false)]
- public async DBusConnection.for_address (string address, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async DBusConnection.for_address (string address, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable = null) throws GLib.Error;
[CCode (has_construct_function = false)]
- public DBusConnection.for_address_sync (string address, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable) throws GLib.Error;
+ public DBusConnection.for_address_sync (string address, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable = null) throws GLib.Error;
public GLib.DBusCapabilityFlags get_capabilities ();
public bool get_exit_on_close ();
public unowned string get_guid ();
@@ -206,13 +206,13 @@ namespace GLib {
public uint register_subtree (string object_path, GLib.DBusSubtreeVTable vtable, GLib.DBusSubtreeFlags flags, GLib.DestroyNotify user_data_free_func) throws GLib.Error;
public void remove_filter (uint filter_id);
public bool send_message (GLib.DBusMessage message, uint32 out_serial) throws GLib.Error;
- public async GLib.DBusMessage send_message_with_reply (GLib.DBusMessage message, int timeout_msec, uint32 out_serial, GLib.Cancellable? cancellable) throws GLib.Error;
- public GLib.DBusMessage send_message_with_reply_sync (GLib.DBusMessage message, int timeout_msec, uint32 out_serial, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async GLib.DBusMessage send_message_with_reply (GLib.DBusMessage message, int timeout_msec, uint32 out_serial, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public GLib.DBusMessage send_message_with_reply_sync (GLib.DBusMessage message, int timeout_msec, uint32 out_serial, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void set_exit_on_close (bool exit_on_close);
public uint signal_subscribe (string sender, string interface_name, string member, string object_path, string arg0, GLib.DBusSignalCallback callback, GLib.DestroyNotify user_data_free_func);
public void signal_unsubscribe (uint subscription_id);
[CCode (has_construct_function = false)]
- public DBusConnection.sync (GLib.IOStream stream, string guid, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable) throws GLib.Error;
+ public DBusConnection.sync (GLib.IOStream stream, string guid, GLib.DBusConnectionFlags flags, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool unregister_object (uint registration_id);
public bool unregister_subtree (uint registration_id);
public string address { construct; }
@@ -361,13 +361,13 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class DBusProxy : GLib.Object, GLib.Initable, GLib.AsyncInitable {
[CCode (type = "void", has_construct_function = false)]
- public async DBusProxy (GLib.DBusConnection connection, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable) throws GLib.Error;
- public async GLib.Variant call (string method_name, GLib.Variant parameters, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable) throws GLib.Error;
- public GLib.Variant call_sync (string method_name, GLib.Variant parameters, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async DBusProxy (GLib.DBusConnection connection, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async GLib.Variant call (string method_name, GLib.Variant parameters, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public GLib.Variant call_sync (string method_name, GLib.Variant parameters, GLib.DBusCallFlags flags, int timeout_msec, GLib.Cancellable? cancellable = null) throws GLib.Error;
[CCode (type = "void", has_construct_function = false)]
- public async DBusProxy.for_bus (GLib.BusType bus_type, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async DBusProxy.for_bus (GLib.BusType bus_type, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable = null) throws GLib.Error;
[CCode (has_construct_function = false)]
- public DBusProxy.for_bus_sync (GLib.BusType bus_type, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable) throws GLib.Error;
+ public DBusProxy.for_bus_sync (GLib.BusType bus_type, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable = null) throws GLib.Error;
public unowned GLib.Variant get_cached_property (string property_name);
public unowned string get_cached_property_names ();
public unowned GLib.DBusConnection get_connection ();
@@ -382,7 +382,7 @@ namespace GLib {
public void set_default_timeout (int timeout_msec);
public void set_interface_info (GLib.DBusInterfaceInfo info);
[CCode (has_construct_function = false)]
- public DBusProxy.sync (GLib.DBusConnection connection, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable) throws GLib.Error;
+ public DBusProxy.sync (GLib.DBusConnection connection, GLib.DBusProxyFlags flags, GLib.DBusInterfaceInfo info, string name, string object_path, string interface_name, GLib.Cancellable? cancellable = null) throws GLib.Error;
public GLib.BusType g_bus_type { construct; }
[NoAccessorMethod]
public GLib.DBusConnection g_connection { owned get; construct; }
@@ -412,7 +412,7 @@ namespace GLib {
public void start ();
public void stop ();
[CCode (has_construct_function = false)]
- public DBusServer.sync (string address, GLib.DBusServerFlags flags, string guid, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable) throws GLib.Error;
+ public DBusServer.sync (string address, GLib.DBusServerFlags flags, string guid, GLib.DBusAuthObserver observer, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoAccessorMethod]
public string active { owned get; }
[NoAccessorMethod]
@@ -445,17 +445,17 @@ namespace GLib {
public DataInputStream (GLib.InputStream base_stream);
public GLib.DataStreamByteOrder get_byte_order ();
public GLib.DataStreamNewlineType get_newline_type ();
- public uchar read_byte (GLib.Cancellable? cancellable) throws GLib.Error;
- public int16 read_int16 (GLib.Cancellable? cancellable) throws GLib.Error;
- public int32 read_int32 (GLib.Cancellable? cancellable) throws GLib.Error;
- public int64 read_int64 (GLib.Cancellable? cancellable) throws GLib.Error;
- public string? read_line (out size_t length, GLib.Cancellable? cancellable) throws GLib.Error;
- public async string? read_line_async (int io_priority, GLib.Cancellable? cancellable, out size_t length) throws GLib.Error;
- public uint16 read_uint16 (GLib.Cancellable? cancellable) throws GLib.Error;
- public uint32 read_uint32 (GLib.Cancellable? cancellable) throws GLib.Error;
- public uint64 read_uint64 (GLib.Cancellable? cancellable) throws GLib.Error;
- public string? read_until (string stop_chars, out size_t length, GLib.Cancellable? cancellable) throws GLib.Error;
- public async string? read_until_async (string stop_chars, int io_priority, GLib.Cancellable? cancellable, out size_t length) throws GLib.Error;
+ public uchar read_byte (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public int16 read_int16 (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public int32 read_int32 (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public int64 read_int64 (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public string? read_line (out size_t length, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async string? read_line_async (int io_priority, GLib.Cancellable? cancellable = null, out size_t? length = null) throws GLib.Error;
+ public uint16 read_uint16 (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public uint32 read_uint32 (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public uint64 read_uint64 (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public string? read_until (string stop_chars, out size_t length, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async string? read_until_async (string stop_chars, int io_priority, GLib.Cancellable? cancellable = null, out size_t? length = null) throws GLib.Error;
public void set_byte_order (GLib.DataStreamByteOrder order);
public void set_newline_type (GLib.DataStreamNewlineType type);
public GLib.DataStreamByteOrder byte_order { get; set; }
@@ -466,14 +466,14 @@ namespace GLib {
[CCode (has_construct_function = false)]
public DataOutputStream (GLib.OutputStream base_stream);
public GLib.DataStreamByteOrder get_byte_order ();
- public bool put_byte (uchar data, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_int16 (int16 data, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_int32 (int32 data, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_int64 (int64 data, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_string (string str, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_uint16 (uint16 data, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_uint32 (uint32 data, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool put_uint64 (uint64 data, GLib.Cancellable? cancellable) throws GLib.Error;
+ public bool put_byte (uchar data, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_int16 (int16 data, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_int32 (int32 data, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_int64 (int64 data, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_string (string str, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_uint16 (uint16 data, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_uint32 (uint32 data, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool put_uint64 (uint64 data, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void set_byte_order (GLib.DataStreamByteOrder order);
public GLib.DataStreamByteOrder byte_order { get; set; }
}
@@ -534,15 +534,15 @@ namespace GLib {
}
[CCode (cheader_filename = "gio/gio.h")]
public class FileEnumerator : GLib.Object {
- public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public bool close (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool close_fn (GLib.Cancellable? cancellable = null) throws GLib.Error;
public unowned GLib.File get_container ();
public bool has_pending ();
public bool is_closed ();
- public virtual GLib.FileInfo next_file (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async GLib.List<GLib.FileInfo> next_files_async (int num_files, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual GLib.FileInfo next_file (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async GLib.List<GLib.FileInfo> next_files_async (int num_files, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void set_pending (bool pending);
public GLib.File container { construct; }
}
@@ -553,14 +553,14 @@ namespace GLib {
[NoWrapper]
public virtual bool can_truncate ();
public virtual unowned string get_etag ();
- public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
public virtual int64 tell ();
[NoWrapper]
- public virtual bool truncate_fn (int64 size, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool truncate_fn (int64 size, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public class FileIcon : GLib.Object, GLib.Icon, GLib.LoadableIcon {
@@ -645,10 +645,10 @@ namespace GLib {
public class FileInputStream : GLib.InputStream, GLib.Seekable {
[NoWrapper]
public virtual bool can_seek ();
- public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
public virtual int64 tell ();
}
@@ -671,14 +671,14 @@ namespace GLib {
[NoWrapper]
public virtual bool can_truncate ();
public virtual unowned string get_etag ();
- public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual unowned GLib.FileInfo query_info (string attributes, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async unowned GLib.FileInfo query_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
public virtual int64 tell ();
[NoWrapper]
- public virtual bool truncate_fn (int64 size, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool truncate_fn (int64 size, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public class FilenameCompleter : GLib.Object {
@@ -745,10 +745,10 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class IOStream : GLib.Object {
public void clear_pending ();
- public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public bool close (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool close_fn (GLib.Cancellable? cancellable = null) throws GLib.Error;
public virtual unowned GLib.InputStream get_input_stream ();
public virtual unowned GLib.OutputStream get_output_stream ();
public bool has_pending ();
@@ -810,20 +810,20 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class InputStream : GLib.Object {
public void clear_pending ();
- public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public bool close (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool close_fn (GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool has_pending ();
public bool is_closed ();
- public ssize_t read (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool read_all (void* buffer, size_t count, out size_t bytes_read, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async ssize_t read_async (void* buffer, size_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public ssize_t read (void* buffer, size_t count, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool read_all (void* buffer, size_t count, out size_t bytes_read, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async ssize_t read_async (void* buffer, size_t count, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual ssize_t read_fn (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual ssize_t read_fn (void* buffer, size_t count, GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool set_pending () throws GLib.Error;
- public virtual ssize_t skip (size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async ssize_t skip_async (size_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual ssize_t skip (size_t count, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async ssize_t skip_async (size_t count, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[Compact]
[CCode (cheader_filename = "gio/gio.h")]
@@ -886,7 +886,7 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class NativeVolumeMonitor : GLib.VolumeMonitor {
[NoWrapper]
- public virtual unowned GLib.Mount get_mount_for_mount_path (string mount_path, GLib.Cancellable? cancellable);
+ public virtual unowned GLib.Mount get_mount_for_mount_path (string mount_path, GLib.Cancellable? cancellable = null);
}
[CCode (cheader_filename = "gio/gio.h")]
public class NetworkAddress : GLib.Object, GLib.SocketConnectable {
@@ -912,23 +912,23 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class OutputStream : GLib.Object {
public void clear_pending ();
- public bool close (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public bool close (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool close_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual bool close_fn (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual bool flush (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool flush_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool close_fn (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual bool flush (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool flush_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool has_pending ();
public bool is_closed ();
public bool is_closing ();
public bool set_pending () throws GLib.Error;
- public virtual ssize_t splice (GLib.InputStream source, GLib.OutputStreamSpliceFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async ssize_t splice_async (GLib.InputStream source, GLib.OutputStreamSpliceFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public ssize_t write (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool write_all (void* buffer, size_t count, out size_t bytes_written, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async ssize_t write_async (void* buffer, size_t count, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual ssize_t splice (GLib.InputStream source, GLib.OutputStreamSpliceFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async ssize_t splice_async (GLib.InputStream source, GLib.OutputStreamSpliceFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public ssize_t write (void* buffer, size_t count, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool write_all (void* buffer, size_t count, out size_t bytes_written, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async ssize_t write_async (void* buffer, size_t count, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public virtual ssize_t write_fn (void* buffer, size_t count, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual ssize_t write_fn (void* buffer, size_t count, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[Compact]
[CCode (cheader_filename = "gio/gio.h")]
@@ -938,14 +938,14 @@ namespace GLib {
}
[CCode (cheader_filename = "gio/gio.h")]
public class Permission : GLib.Object {
- public virtual bool acquire (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool acquire_async (GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool acquire (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool acquire_async (GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool get_allowed ();
public bool get_can_acquire ();
public bool get_can_release ();
public void impl_update (bool allowed, bool can_acquire, bool can_release);
- public virtual bool release (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async bool release_async (GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool release (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async bool release_async (GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool allowed { get; }
public bool can_acquire { get; }
public bool can_release { get; }
@@ -954,12 +954,12 @@ namespace GLib {
public class Resolver : GLib.Object {
public static GLib.Quark error_quark ();
public static unowned GLib.Resolver get_default ();
- public virtual unowned string lookup_by_address (GLib.InetAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async unowned string lookup_by_address_async (GLib.InetAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual GLib.List<GLib.InetAddress> lookup_by_name (string hostname, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async GLib.List<GLib.InetAddress> lookup_by_name_async (string hostname, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual GLib.List<GLib.SrvTarget> lookup_service (string service, string protocol, string domain, GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async GLib.List<GLib.SrvTarget> lookup_service_async (string service, string protocol, string domain, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual unowned string lookup_by_address (GLib.InetAddress address, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async unowned string lookup_by_address_async (GLib.InetAddress address, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual GLib.List<GLib.InetAddress> lookup_by_name (string hostname, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async GLib.List<GLib.InetAddress> lookup_by_name_async (string hostname, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual GLib.List<GLib.SrvTarget> lookup_service (string service, string protocol, string domain, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async GLib.List<GLib.SrvTarget> lookup_service_async (string service, string protocol, string domain, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void set_default ();
public virtual signal void reload ();
}
@@ -1059,7 +1059,7 @@ namespace GLib {
public void* get_source_tag ();
public static bool is_valid (GLib.AsyncResult _result, GLib.Object source, void* source_tag);
public bool propagate_error () throws GLib.Error;
- public void run_in_thread (GLib.SimpleAsyncThreadFunc func, int io_priority, GLib.Cancellable? cancellable);
+ public void run_in_thread (GLib.SimpleAsyncThreadFunc func, int io_priority, GLib.Cancellable? cancellable = null);
public void set_error (GLib.Quark domain, int code, string format);
public void set_error_va (GLib.Quark domain, int code, string format, void* args);
public void set_from_error (GLib.Error error);
@@ -1081,14 +1081,14 @@ namespace GLib {
public class Socket : GLib.Object, GLib.Initable {
[CCode (has_construct_function = false)]
public Socket (GLib.SocketFamily family, GLib.SocketType type, GLib.SocketProtocol protocol) throws GLib.Error;
- public unowned GLib.Socket accept (GLib.Cancellable? cancellable) throws GLib.Error;
+ public unowned GLib.Socket accept (GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool bind (GLib.SocketAddress address, bool allow_reuse) throws GLib.Error;
public bool check_connect_result () throws GLib.Error;
public bool close () throws GLib.Error;
public GLib.IOCondition condition_check (GLib.IOCondition condition);
- public bool condition_wait (GLib.IOCondition condition, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool connect (GLib.SocketAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
- public GLib.SocketSource create_source (GLib.IOCondition condition, GLib.Cancellable? cancellable);
+ public bool condition_wait (GLib.IOCondition condition, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool connect (GLib.SocketAddress address, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public GLib.SocketSource create_source (GLib.IOCondition condition, GLib.Cancellable? cancellable = null);
[CCode (has_construct_function = false)]
public Socket.from_fd (int fd) throws GLib.Error;
public bool get_blocking ();
@@ -1104,12 +1104,12 @@ namespace GLib {
public bool is_closed ();
public bool is_connected ();
public bool listen () throws GLib.Error;
- public ssize_t receive (string buffer, size_t size, GLib.Cancellable? cancellable) throws GLib.Error;
- public ssize_t receive_from (out unowned GLib.SocketAddress address, string buffer, size_t size, GLib.Cancellable? cancellable) throws GLib.Error;
- public ssize_t receive_message (out unowned GLib.SocketAddress address, GLib.InputVector vectors, int num_vectors, out unowned GLib.SocketControlMessage messages, int num_messages, int flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public ssize_t send (string buffer, size_t size, GLib.Cancellable? cancellable) throws GLib.Error;
- public ssize_t send_message (GLib.SocketAddress address, GLib.OutputVector vectors, int num_vectors, out unowned GLib.SocketControlMessage messages, int num_messages, int flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public ssize_t send_to (GLib.SocketAddress address, string buffer, size_t size, GLib.Cancellable? cancellable) throws GLib.Error;
+ public ssize_t receive (string buffer, size_t size, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public ssize_t receive_from (out unowned GLib.SocketAddress address, string buffer, size_t size, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public ssize_t receive_message (out unowned GLib.SocketAddress address, GLib.InputVector vectors, int num_vectors, out unowned GLib.SocketControlMessage messages, int num_messages, int flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public ssize_t send (string buffer, size_t size, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public ssize_t send_message (GLib.SocketAddress address, GLib.OutputVector vectors, int num_vectors, out unowned GLib.SocketControlMessage messages, int num_messages, int flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public ssize_t send_to (GLib.SocketAddress address, string buffer, size_t size, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void set_blocking (bool blocking);
public void set_keepalive (bool keepalive);
public void set_listen_backlog (int backlog);
@@ -1139,19 +1139,19 @@ namespace GLib {
}
[CCode (cheader_filename = "gio/gio.h")]
public class SocketAddressEnumerator : GLib.Object {
- public virtual unowned GLib.SocketAddress next (GLib.Cancellable? cancellable) throws GLib.Error;
- public virtual async unowned GLib.SocketAddress next_async (GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual unowned GLib.SocketAddress next (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public virtual async unowned GLib.SocketAddress next_async (GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public class SocketClient : GLib.Object {
[CCode (has_construct_function = false)]
public SocketClient ();
- public unowned GLib.SocketConnection connect (GLib.SocketConnectable connectable, GLib.Cancellable? cancellable) throws GLib.Error;
- public async unowned GLib.SocketConnection connect_async (GLib.SocketConnectable connectable, GLib.Cancellable? cancellable) throws GLib.Error;
- public unowned GLib.SocketConnection connect_to_host (string host_and_port, uint16 default_port, GLib.Cancellable? cancellable) throws GLib.Error;
- public async unowned GLib.SocketConnection connect_to_host_async (string host_and_port, uint16 default_port, GLib.Cancellable? cancellable) throws GLib.Error;
- public unowned GLib.SocketConnection connect_to_service (string domain, string service, GLib.Cancellable? cancellable) throws GLib.Error;
- public async unowned GLib.SocketConnection connect_to_service_async (string domain, string service, GLib.Cancellable? cancellable) throws GLib.Error;
+ public unowned GLib.SocketConnection connect (GLib.SocketConnectable connectable, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async unowned GLib.SocketConnection connect_async (GLib.SocketConnectable connectable, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public unowned GLib.SocketConnection connect_to_host (string host_and_port, uint16 default_port, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async unowned GLib.SocketConnection connect_to_host_async (string host_and_port, uint16 default_port, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public unowned GLib.SocketConnection connect_to_service (string domain, string service, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async unowned GLib.SocketConnection connect_to_service_async (string domain, string service, GLib.Cancellable? cancellable = null) throws GLib.Error;
public GLib.SocketFamily get_family ();
public unowned GLib.SocketAddress get_local_address ();
public GLib.SocketProtocol get_protocol ();
@@ -1190,10 +1190,10 @@ namespace GLib {
public class SocketListener : GLib.Object {
[CCode (has_construct_function = false)]
public SocketListener ();
- public unowned GLib.SocketConnection accept (out unowned GLib.Object source_object, GLib.Cancellable? cancellable) throws GLib.Error;
- public async unowned GLib.SocketConnection accept_async (GLib.Cancellable? cancellable, out unowned GLib.Object source_object) throws GLib.Error;
- public unowned GLib.Socket accept_socket (out unowned GLib.Object source_object, GLib.Cancellable? cancellable) throws GLib.Error;
- public async unowned GLib.Socket accept_socket_async (GLib.Cancellable? cancellable, out unowned GLib.Object source_object) throws GLib.Error;
+ public unowned GLib.SocketConnection accept (out unowned GLib.Object source_object, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async unowned GLib.SocketConnection accept_async (GLib.Cancellable? cancellable = null, out GLib.Object? source_object = null) throws GLib.Error;
+ public unowned GLib.Socket accept_socket (out unowned GLib.Object source_object, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async unowned GLib.Socket accept_socket_async (GLib.Cancellable? cancellable = null, out GLib.Object? source_object = null) throws GLib.Error;
public bool add_address (GLib.SocketAddress address, GLib.SocketType type, GLib.SocketProtocol protocol, GLib.Object? source_object, out unowned GLib.SocketAddress effective_address) throws GLib.Error;
public uint16 add_any_inet_port (GLib.Object source_object) throws GLib.Error;
public bool add_inet_port (uint16 port, GLib.Object? source_object) throws GLib.Error;
@@ -1287,13 +1287,13 @@ namespace GLib {
public virtual unowned string[] get_supported_uri_schemes ();
public virtual bool is_active ();
[NoWrapper]
- public virtual void local_file_add_info (string filename, uint64 device, GLib.FileAttributeMatcher attribute_matcher, GLib.FileInfo info, GLib.Cancellable? cancellable, void* extra_data, GLib.DestroyNotify free_extra_data);
+ public virtual void local_file_add_info (string filename, uint64 device, GLib.FileAttributeMatcher attribute_matcher, GLib.FileInfo info, GLib.Cancellable? cancellable = null, void* extra_data = null, GLib.DestroyNotify? free_extra_data = null);
[NoWrapper]
public virtual void local_file_moved (string source, string dest);
[NoWrapper]
public virtual void local_file_removed (string filename);
[NoWrapper]
- public virtual bool local_file_set_attributes (string filename, GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
+ public virtual bool local_file_set_attributes (string filename, GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
public virtual unowned GLib.File parse_name (string parse_name);
}
[CCode (cheader_filename = "gio/gio.h")]
@@ -1371,10 +1371,10 @@ namespace GLib {
}
[CCode (cheader_filename = "gio/gio.h")]
public interface AsyncInitable : GLib.Object {
- public abstract async bool init_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool init_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public static async unowned GLib.Object new_async (GLib.Type object_type, int io_priority, GLib.Cancellable? cancellable, ...) throws GLib.Error;
- public static async void new_valist_async (GLib.Type object_type, string first_property_name, void* var_args, int io_priority, GLib.Cancellable? cancellable);
- public static async void newv_async (GLib.Type object_type, uint n_parameters, GLib.Parameter parameters, int io_priority, GLib.Cancellable? cancellable);
+ public static async void new_valist_async (GLib.Type object_type, string first_property_name, void* var_args, int io_priority, GLib.Cancellable? cancellable = null);
+ public static async void newv_async (GLib.Type object_type, uint n_parameters, GLib.Parameter parameters, int io_priority, GLib.Cancellable? cancellable = null);
}
[CCode (cheader_filename = "gio/gio.h")]
public interface AsyncResult : GLib.Object {
@@ -1393,8 +1393,8 @@ namespace GLib {
public abstract bool can_start ();
public abstract bool can_start_degraded ();
public abstract bool can_stop ();
- public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract unowned string enumerate_identifiers ();
public abstract unowned GLib.Icon get_icon ();
public abstract unowned string get_identifier (string kind);
@@ -1405,9 +1405,9 @@ namespace GLib {
public abstract bool has_volumes ();
public abstract bool is_media_check_automatic ();
public abstract bool is_media_removable ();
- public abstract async bool poll_for_media (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool start (GLib.DriveStartFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool stop (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool poll_for_media (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool start (GLib.DriveStartFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool stop (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public signal void changed ();
public signal void disconnected ();
public signal void eject_button ();
@@ -1415,26 +1415,26 @@ namespace GLib {
}
[CCode (cheader_filename = "gio/gio.h")]
public interface File : GLib.Object {
- public abstract GLib.FileOutputStream append_to (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.FileOutputStream append_to_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool copy (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable, GLib.FileProgressCallback? progress_callback) throws GLib.Error;
- public abstract async bool copy_async (GLib.File destination, GLib.FileCopyFlags flags, int io_priority, GLib.Cancellable? cancellable, GLib.FileProgressCallback? progress_callback) throws GLib.Error;
- public bool copy_attributes (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileOutputStream create (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.FileOutputStream create_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileIOStream create_readwrite (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async unowned GLib.FileIOStream create_readwrite_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool @delete (GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract GLib.FileOutputStream append_to (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.FileOutputStream append_to_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract bool copy (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable = null, GLib.FileProgressCallback? progress_callback = null) throws GLib.Error;
+ public abstract async bool copy_async (GLib.File destination, GLib.FileCopyFlags flags, int io_priority, GLib.Cancellable? cancellable = null, GLib.FileProgressCallback? progress_callback = null) throws GLib.Error;
+ public bool copy_attributes (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract GLib.FileOutputStream create (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.FileOutputStream create_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract unowned GLib.FileIOStream create_readwrite (GLib.FileCreateFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async unowned GLib.FileIOStream create_readwrite_async (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool @delete (GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public abstract bool delete_file (GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool delete_file (GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract unowned GLib.File dup ();
- public abstract async bool eject_mountable (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool eject_mountable_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileEnumerator enumerate_children (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.FileEnumerator enumerate_children_async (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool eject_mountable (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool eject_mountable_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract GLib.FileEnumerator enumerate_children (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.FileEnumerator enumerate_children_async (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract bool equal (GLib.File file2);
- public abstract GLib.Mount find_enclosing_mount (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.Mount find_enclosing_mount_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract GLib.Mount find_enclosing_mount (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.Mount find_enclosing_mount_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract string? get_basename ();
public GLib.File get_child (string name);
public abstract GLib.File get_child_for_display_name (string display_name) throws GLib.Error;
@@ -1449,65 +1449,65 @@ namespace GLib {
public abstract bool has_uri_scheme (string uri_scheme);
public abstract uint hash ();
public abstract bool is_native ();
- public bool load_contents (GLib.Cancellable? cancellable, out string contents, out size_t length, out string etag_out) throws GLib.Error;
- public async bool load_contents_async (GLib.Cancellable? cancellable, out string contents, out size_t length, out string etag_out) throws GLib.Error;
- public async bool load_partial_contents_async (GLib.Cancellable? cancellable, GLib.FileReadMoreCallback read_more_callback, out string contents, out size_t length, out string etag_out) throws GLib.Error;
- public abstract bool make_directory (GLib.Cancellable? cancellable) throws GLib.Error;
- public bool make_directory_with_parents (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool make_symbolic_link (string symlink_value, GLib.Cancellable? cancellable) throws GLib.Error;
- public unowned GLib.FileMonitor monitor (GLib.FileMonitorFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
+ public bool load_contents (GLib.Cancellable? cancellable = null, out string contents, out unowned size_t? length = null, out string? etag_out = null) throws GLib.Error;
+ public async bool load_contents_async (GLib.Cancellable? cancellable = null, out string contents, out unowned size_t? length = null, out string? etag_out = null) throws GLib.Error;
+ public async bool load_partial_contents_async (GLib.Cancellable? cancellable, GLib.FileReadMoreCallback read_more_callback, out string contents, out unowned size_t? length = null, out string? etag_out = null) throws GLib.Error;
+ public abstract bool make_directory (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool make_directory_with_parents (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract bool make_symbolic_link (string symlink_value, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public unowned GLib.FileMonitor monitor (GLib.FileMonitorFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
[CCode (vfunc_name = "monitor_dir")]
public abstract GLib.FileMonitor monitor_directory (GLib.FileMonitorFlags flags, GLib.Cancellable? cancellable = null) throws GLib.IOError;
public abstract GLib.FileMonitor monitor_file (GLib.FileMonitorFlags flags, GLib.Cancellable? cancellable = null) throws GLib.IOError;
- public abstract async bool mount_enclosing_volume (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async unowned GLib.File mount_mountable (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract bool move (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable, GLib.FileProgressCallback? progress_callback) throws GLib.Error;
+ public abstract async bool mount_enclosing_volume (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async unowned GLib.File mount_mountable (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract bool move (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable? cancellable = null, GLib.FileProgressCallback? progress_callback = null) throws GLib.Error;
public static GLib.File new_for_commandline_arg (string arg);
public static GLib.File new_for_path (string path);
public static GLib.File new_for_uri (string uri);
- public abstract unowned GLib.FileIOStream open_readwrite (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async unowned GLib.FileIOStream open_readwrite_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract unowned GLib.FileIOStream open_readwrite (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async unowned GLib.FileIOStream open_readwrite_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public static unowned GLib.File parse_name (string parse_name);
- public abstract async bool poll_mountable (GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool poll_mountable (GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
public abstract bool prefix_matches (GLib.File file);
- public GLib.AppInfo query_default_handler (GLib.Cancellable? cancellable) throws GLib.Error;
- public bool query_exists (GLib.Cancellable? cancellable);
- public GLib.FileType query_file_type (GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable);
- public abstract unowned GLib.FileInfo query_filesystem_info (string attributes, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async unowned GLib.FileInfo query_filesystem_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileInfo query_info (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.FileInfo query_info_async (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileAttributeInfoList query_settable_attributes (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.FileAttributeInfoList query_writable_namespaces (GLib.Cancellable? cancellable) throws GLib.Error;
- public GLib.FileInputStream read (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.FileInputStream read_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public GLib.AppInfo query_default_handler (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool query_exists (GLib.Cancellable? cancellable = null);
+ public GLib.FileType query_file_type (GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null);
+ public abstract unowned GLib.FileInfo query_filesystem_info (string attributes, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async unowned GLib.FileInfo query_filesystem_info_async (string attributes, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract GLib.FileInfo query_info (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.FileInfo query_info_async (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract unowned GLib.FileAttributeInfoList query_settable_attributes (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract unowned GLib.FileAttributeInfoList query_writable_namespaces (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public GLib.FileInputStream read (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.FileInputStream read_async (int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
- public abstract unowned GLib.FileInputStream read_fn (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract GLib.FileOutputStream replace (string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async GLib.FileOutputStream replace_async (string? etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool replace_contents (string contents, size_t length, string? etag, bool make_backup, GLib.FileCreateFlags flags, out string? new_etag, GLib.Cancellable? cancellable) throws GLib.Error;
- public async bool replace_contents_async (string contents, size_t length, string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable, out string? new_etag) throws GLib.Error;
- public abstract unowned GLib.FileIOStream replace_readwrite (string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async unowned GLib.FileIOStream replace_readwrite_async (string? etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract unowned GLib.FileInputStream read_fn (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract GLib.FileOutputStream replace (string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async GLib.FileOutputStream replace_async (string? etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool replace_contents (string contents, size_t length, string? etag, bool make_backup, GLib.FileCreateFlags flags, out string? new_etag, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public async bool replace_contents_async (string contents, size_t length, string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable = null, out string? new_etag = null) throws GLib.Error;
+ public abstract unowned GLib.FileIOStream replace_readwrite (string? etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async unowned GLib.FileIOStream replace_readwrite_async (string? etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract GLib.File resolve_relative_path (string relative_path);
- public abstract bool set_attribute (string attribute, GLib.FileAttributeType type, void* value_p, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool set_attribute_byte_string (string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool set_attribute_int32 (string attribute, int32 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool set_attribute_int64 (string attribute, int64 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool set_attribute_string (string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool set_attribute_uint32 (string attribute, uint32 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public bool set_attribute_uint64 (string attribute, uint64 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool set_attribute (string attribute, GLib.FileAttributeType type, void* value_p, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool set_attribute_byte_string (string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool set_attribute_int32 (string attribute, int32 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool set_attribute_int64 (string attribute, int64 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool set_attribute_string (string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool set_attribute_uint32 (string attribute, uint32 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public bool set_attribute_uint64 (string attribute, uint64 value, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract async bool set_attributes_async (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable? cancellable, out unowned GLib.FileInfo info_out) throws GLib.Error;
- public abstract bool set_attributes_from_info (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned GLib.File set_display_name (string display_name, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async unowned GLib.File set_display_name_async (string display_name, int io_priority, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool start_mountable (GLib.DriveStartFlags flags, GLib.MountOperation start_operation, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool stop_mountable (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool set_attributes_from_info (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract unowned GLib.File set_display_name (string display_name, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async unowned GLib.File set_display_name_async (string display_name, int io_priority, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool start_mountable (GLib.DriveStartFlags flags, GLib.MountOperation start_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool stop_mountable (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool supports_thread_contexts ();
- public abstract bool trash (GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool unmount_mountable (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool unmount_mountable_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool trash (GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool unmount_mountable (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool unmount_mountable_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public interface Icon : GLib.Object {
@@ -1522,22 +1522,22 @@ namespace GLib {
}
[CCode (cheader_filename = "gio/gio.h")]
public interface Initable : GLib.Object {
- public abstract bool init (GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool init (GLib.Cancellable? cancellable = null) throws GLib.Error;
public static void* @new (GLib.Type object_type, GLib.Cancellable? cancellable, ...) throws GLib.Error;
- public static unowned GLib.Object new_valist (GLib.Type object_type, string first_property_name, void* var_args, GLib.Cancellable? cancellable) throws GLib.Error;
- public static void* newv (GLib.Type object_type, uint n_parameters, GLib.Parameter parameters, GLib.Cancellable? cancellable) throws GLib.Error;
+ public static unowned GLib.Object new_valist (GLib.Type object_type, string first_property_name, void* var_args, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public static void* newv (GLib.Type object_type, uint n_parameters, GLib.Parameter parameters, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public interface LoadableIcon : GLib.Icon, GLib.Object {
- public abstract unowned GLib.InputStream load (int size, out unowned string? type, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract unowned GLib.InputStream load (int size, out unowned string? type, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract async unowned GLib.InputStream load_async (int size, GLib.Cancellable? cancellable, out unowned string? type) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public interface Mount : GLib.Object {
public abstract bool can_eject ();
public abstract bool can_unmount ();
- public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract unowned GLib.File get_default_location ();
public abstract unowned GLib.Drive get_drive ();
public abstract unowned GLib.Icon get_icon ();
@@ -1545,13 +1545,13 @@ namespace GLib {
public abstract unowned GLib.File get_root ();
public abstract unowned string get_uuid ();
public abstract unowned GLib.Volume get_volume ();
- public abstract async unowned string guess_content_type (bool force_rescan, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract unowned string guess_content_type_sync (bool force_rescan, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async unowned string guess_content_type (bool force_rescan, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract unowned string guess_content_type_sync (bool force_rescan, GLib.Cancellable? cancellable = null) throws GLib.Error;
public bool is_shadowed ();
- public abstract async bool remount (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool remount (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void shadow ();
- public abstract async bool unmount (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool unmount_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool unmount (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool unmount_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public void unshadow ();
public signal void changed ();
public signal void pre_unmount ();
@@ -1561,10 +1561,10 @@ namespace GLib {
public interface Seekable : GLib.Object {
public abstract bool can_seek ();
public abstract bool can_truncate ();
- public abstract bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool seek (int64 offset, GLib.SeekType type, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract int64 tell ();
[CCode (vfunc_name = "truncate_fn")]
- public abstract bool truncate (int64 offset, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract bool truncate (int64 offset, GLib.Cancellable? cancellable = null) throws GLib.Error;
}
[CCode (cheader_filename = "gio/gio.h")]
public interface SocketConnectable : GLib.Object {
@@ -1574,8 +1574,8 @@ namespace GLib {
public interface Volume : GLib.Object {
public abstract bool can_eject ();
public abstract bool can_mount ();
- public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable) throws GLib.Error;
- public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public abstract async bool eject (GLib.MountUnmountFlags flags, GLib.Cancellable? cancellable = null) throws GLib.Error;
+ public abstract async bool eject_with_operation (GLib.MountUnmountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
public abstract unowned string enumerate_identifiers ();
public abstract unowned GLib.File get_activation_root ();
public abstract unowned GLib.Drive get_drive ();
@@ -1584,7 +1584,7 @@ namespace GLib {
public abstract unowned GLib.Mount get_mount ();
public abstract unowned string get_name ();
public abstract unowned string get_uuid ();
- public async bool mount (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable) throws GLib.Error;
+ public async bool mount (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable = null) throws GLib.Error;
[NoWrapper]
public abstract void mount_fn (GLib.MountMountFlags flags, GLib.MountOperation? mount_operation, GLib.Cancellable? cancellable, GLib.AsyncReadyCallback callback);
public abstract bool should_automount ();
@@ -2244,13 +2244,13 @@ namespace GLib {
[CCode (cname = "g_content_types_get_registered", cheader_filename = "gio/gio.h")]
public static GLib.List<string> g_content_types_get_registered ();
[CCode (cname = "g_dbus_address_get_for_bus_sync", cheader_filename = "gio/gio.h")]
- public static unowned string g_dbus_address_get_for_bus_sync (GLib.BusType bus_type, GLib.Cancellable? cancellable) throws GLib.Error;
+ public static unowned string g_dbus_address_get_for_bus_sync (GLib.BusType bus_type, GLib.Cancellable? cancellable = null) throws GLib.Error;
[CCode (cname = "g_dbus_address_get_stream", cheader_filename = "gio/gio.h")]
- public static async void g_dbus_address_get_stream (string address, GLib.Cancellable? cancellable);
+ public static async void g_dbus_address_get_stream (string address, GLib.Cancellable? cancellable = null);
[CCode (cname = "g_dbus_address_get_stream_finish", cheader_filename = "gio/gio.h")]
public static unowned GLib.IOStream g_dbus_address_get_stream_finish (GLib.AsyncResult res, string out_guid) throws GLib.Error;
[CCode (cname = "g_dbus_address_get_stream_sync", cheader_filename = "gio/gio.h")]
- public static unowned GLib.IOStream g_dbus_address_get_stream_sync (string address, string out_guid, GLib.Cancellable? cancellable) throws GLib.Error;
+ public static unowned GLib.IOStream g_dbus_address_get_stream_sync (string address, string out_guid, GLib.Cancellable? cancellable = null) throws GLib.Error;
[CCode (cname = "g_dbus_error_encode_gerror", cheader_filename = "gio/gio.h")]
public static unowned string g_dbus_error_encode_gerror (GLib.Error error);
[CCode (cname = "g_dbus_error_get_remote_error", cheader_filename = "gio/gio.h")]
@@ -2300,7 +2300,7 @@ namespace GLib {
[CCode (cname = "g_io_scheduler_cancel_all_jobs", cheader_filename = "gio/gio.h")]
public static void g_io_scheduler_cancel_all_jobs ();
[CCode (cname = "g_io_scheduler_push_job", cheader_filename = "gio/gio.h")]
- public static void g_io_scheduler_push_job (GLib.IOSchedulerJobFunc job_func, GLib.DestroyNotify? notify, int io_priority, GLib.Cancellable? cancellable);
+ public static void g_io_scheduler_push_job (GLib.IOSchedulerJobFunc job_func, GLib.DestroyNotify? notify, int io_priority, GLib.Cancellable? cancellable = null);
[CCode (cname = "g_keyfile_settings_backend_new", cheader_filename = "gio/gio.h")]
public static unowned GLib.SettingsBackend g_keyfile_settings_backend_new (string filename);
[CCode (cname = "g_simple_async_report_error_in_idle", cheader_filename = "gio/gio.h")]
diff --git a/vapi/packages/gio-2.0/gio-2.0.metadata b/vapi/packages/gio-2.0/gio-2.0.metadata
index 59f3b6f739..9a572c4275 100644
--- a/vapi/packages/gio-2.0/gio-2.0.metadata
+++ b/vapi/packages/gio-2.0/gio-2.0.metadata
@@ -8,6 +8,8 @@ g_app_info_launch_uris.envp is_array="1"
g_app_launch_context_get_display.files type_arguments="File"
g_app_launch_context_get_startup_notify_id.files type_arguments="File"
GAsyncReadyCallback.source_object nullable="1"
+g_async_initable_new_async transfer_ownership="1"
+g_async_initable_new_async.cancellable nullable="1"
g_buffered_input_stream_peek_buffer.count is_out="1"
g_content_type_guess.data_size hidden="1"
g_content_type_guess.result_uncertain is_out="1"
@@ -17,11 +19,12 @@ g_converter_convert.bytes_written is_out="1"
g_data_input_stream_read_line nullable="1" transfer_ownership="1"
g_data_input_stream_read_line.length is_out="1"
g_data_input_stream_read_line_finish nullable="1" transfer_ownership="1"
-g_data_input_stream_read_line_finish.length is_out="1"
+g_data_input_stream_read_line_finish.length nullable="1" transfer_ownership="1" default_value="null" is_out="1"
+g_data_input_stream_read_line_async.length default_value="null"
g_data_input_stream_read_until nullable="1" transfer_ownership="1"
g_data_input_stream_read_until.length is_out="1"
g_data_input_stream_read_until_finish nullable="1" transfer_ownership="1"
-g_data_input_stream_read_until_finish.length is_out="1"
+g_data_input_stream_read_until_finish.length nullable="1" transfer_ownership="1" default_value="null" is_out="1"
g_dbus_address_get_stream async="1"
g_dbus_connection_call async="1"
g_dbus_connection_call_finish transfer_ownership="1"
@@ -45,7 +48,9 @@ g_drive_stop async="1"
g_emblemed_icon_get_emblems type_arguments="Emblem"
g_file_append_to transfer_ownership="1"
g_file_append_to_finish transfer_ownership="1"
+g_file_copy.progress_callback nullable="1" default_value="null"
g_file_copy.progress_callback_data hidden="1"
+g_file_copy_async.progress_callback nullable="1" default_value="null"
g_file_copy_async.progress_callback_data hidden="1"
g_file_create transfer_ownership="1"
g_file_create_finish transfer_ownership="1"
@@ -69,15 +74,10 @@ g_file_get_uri transfer_ownership="1"
g_file_get_uri_scheme transfer_ownership="1"
g_file_hash.file hidden="1"
g_file_info_get_modification_time.result is_out="1"
-g_file_load_contents.contents transfer_ownership="1"
-g_file_load_contents.length is_out="1"
-g_file_load_contents.etag_out transfer_ownership="1"
-g_file_load_contents_finish.contents transfer_ownership="1"
-g_file_load_contents_finish.length is_out="1"
-g_file_load_contents_finish.etag_out transfer_ownership="1"
-g_file_load_partial_contents_finish.contents transfer_ownership="1"
-g_file_load_partial_contents_finish.length is_out="1"
-g_file_load_partial_contents_finish.etag_out transfer_ownership="1"
+g_file_load_*.contents transfer_ownership="1"
+g_file_load_*.length nullable="1" is_out="1" default_value="null"
+g_file_load_*.etag_out nullable="1" transfer_ownership="1" default_value="null"
+g_file_load_partial_contents_async.cancellable nullable="1"
GFileMonitor::changed.other_file nullable="1"
g_file_monitor_directory hidden="1"
g_file_monitor_dir hidden="1"
@@ -98,19 +98,22 @@ g_file_replace transfer_ownership="1"
g_file_replace.etag nullable="1"
g_file_replace_async.etag nullable="1"
g_file_replace_contents.new_etag transfer_ownership="1" nullable="1"
-g_file_replace_contents_finish.new_etag transfer_ownership="1" nullable="1"
+g_file_replace_contents_finish.new_etag transfer_ownership="1" nullable="1" default_value="null"
g_file_replace_finish transfer_ownership="1"
g_file_resolve_relative_path transfer_ownership="1"
+g_file_set_attributes_async.cancellable nullable="1"
g_file_start_mountable async="1"
g_file_stop_mountable async="1"
g_file_unmount_mountable async="1"
g_file_unmount_mountable_with_operation async="1"
g_inet_address_to_string transfer_ownership="1"
g_inet_address_to_bytes type_name="uint8" is_array="1" no_array_length="1"
+g_initable_new.cancellable nullable="1"
g_input_stream_read_all.bytes_read is_out="1"
GIOErrorEnum rename_to="IOError" errordomain="1"
g_io_extension_point_get_extensions type_arguments="IOExtension"
g_io_modules_load_all_in_directory type_arguments="unowned TypeModule" transfer_ownership="1"
+g_loadable_icon_load_async.cancellable nullable="1"
g_memory_input_stream_add_data.destroy nullable="1"
g_memory_input_stream_new_from_data.destroy nullable="1"
g_mount_eject async="1"
@@ -144,11 +147,12 @@ g_vfs_get_supported_uri_schemes is_array="1"
g_volume_eject async="1"
g_volume_eject_with_operation async="1"
g_volume_mount async="1"
+g_volume_mount_fn.cancellable nullable="1"
-g_*.cancellable nullable="1"
+g_*.cancellable nullable="1" default_value="null"
g_*.mount_operation nullable="1"
g_file_*.etag nullable="1"
-g_file_*.progress_callback nullable="1"
+g_file_*.progress_callback nullable="1" default_value="null"
g_io_scheduler_*.notify nullable="1"
g_memory_input_stream_*.destroy nullable="1"
g_memory_output_stream_*.destroy_function nullable="1"
@@ -202,6 +206,11 @@ g_settings_list_list.n_items hidden="1"
g_simple_async_result_new.source_object nullable="1"
+g_socket_listener_accept_finish.source_object transfer_ownership="1" nullable="1" default_value="null"
+g_socket_listener_accept_socket_finish.source_object transfer_ownership="1" nullable="1" default_value="null"
+g_vfs_local_file_add_info.extra_data default_value="null"
+g_vfs_local_file_add_info.free_extra_data nullable="1" default_value="null"
+
GSocketService::incoming.source_object nullable="1"
g_volume_monitor_get transfer_ownership="1"
|
3beef9a92e78ca6da4f41dbb0c3c858ac85b10cb
|
spring-framework
|
SPR-8883 - RestTemplate.headForHeaders throws- "IllegalArgumentException: No InputStream specified" on server resource which- status code are 4xx--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java b/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java
index 2aea01f187b2..0615f7a823a9 100644
--- a/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java
+++ b/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java
@@ -17,6 +17,7 @@
package org.springframework.web.client;
import java.io.IOException;
+import java.io.InputStream;
import java.nio.charset.Charset;
import org.springframework.http.HttpStatus;
@@ -82,11 +83,15 @@ public void handleError(ClientHttpResponse response) throws IOException {
private byte[] getResponseBody(ClientHttpResponse response) {
try {
- return FileCopyUtils.copyToByteArray(response.getBody());
+ InputStream responseBody = response.getBody();
+ if (responseBody != null) {
+ return FileCopyUtils.copyToByteArray(responseBody);
+ }
}
catch (IOException ex) {
- return new byte[0];
+ // ignore
}
+ return new byte[0];
}
}
diff --git a/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java b/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java
index 67a11a7c8de3..0c9866c19bee 100644
--- a/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java
+++ b/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java
@@ -19,16 +19,17 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
-import org.junit.Before;
-import org.junit.Test;
-
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
+import org.junit.Before;
+import org.junit.Test;
+
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/** @author Arjen Poutsma */
public class DefaultResponseErrorHandlerTests {
@@ -96,4 +97,21 @@ public void handleErrorIOException() throws Exception {
verify(response);
}
+
+ @Test(expected = HttpClientErrorException.class)
+ public void handleErrorNullResponse() throws Exception {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.TEXT_PLAIN);
+
+ expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND);
+ expect(response.getStatusText()).andReturn("Not Found");
+ expect(response.getHeaders()).andReturn(headers);
+ expect(response.getBody()).andReturn(null);
+
+ replay(response);
+
+ handler.handleError(response);
+
+ verify(response);
+ }
}
|
5d29c390bf81bd1c5ec171751d6da9c0f862063c
|
drools
|
refactoring--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@2301 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
index 7be511bebf3..d4b69d473f5 100644
--- a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
+++ b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
@@ -1,6 +1,5 @@
package org.drools.leaps;
-import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -9,141 +8,125 @@
import java.util.Set;
import java.util.WeakHashMap;
+import org.drools.FactException;
import org.drools.RuleBase;
+import org.drools.RuleIntegrationException;
+import org.drools.RuleSetIntegrationException;
import org.drools.WorkingMemory;
-import org.drools.leaps.conflict.DefaultConflictResolver;
-import org.drools.reteoo.DefaultFactHandleFactory;
-import org.drools.rule.DuplicateRuleNameException;
+import org.drools.spi.FactHandleFactory;
import org.drools.rule.InvalidPatternException;
-import org.drools.rule.InvalidRuleException;
import org.drools.rule.Rule;
import org.drools.rule.RuleSet;
-import org.drools.spi.FactHandleFactory;
+import org.drools.spi.ClassObjectTypeResolver;
+import org.drools.spi.ObjectTypeResolver;
import org.drools.spi.RuleBaseContext;
/**
* This base class for the engine and analogous to Drool's RuleBase class. It
* has a similar interface adapted to the Leaps algorithm
- *
+ *
* @author Alexander Bagerman
*
*/
-public class RuleBaseImpl implements RuleBase, Serializable {
- private static final long serialVersionUID = 0L;
-
- // to store rules added just as addRule rather than as a part of ruleSet
- private final static String defaultRuleSet = "___default___rule___set___";
-
- private HashMap ruleSets;
-
- private Map applicationData;
-
- private RuleBaseContext ruleBaseContext;
-
- private ConflictResolver conflictResolver;
-
- private Builder builder;
+public class RuleBaseImpl implements RuleBase {
private HashMap leapsRules = new HashMap();
+ private final Builder builder;
+
/**
* TODO we do not need it here. and it references RETEoo class
*
* The fact handle factory.
*/
+ /** The fact handle factory. */
private final FactHandleFactory factHandleFactory;
- /* @todo: replace this with a weak HashSet */
+ private Set ruleSets;
+
+ private Map applicationData;
+
+ private RuleBaseContext ruleBaseContext;
+
+ // @todo: replace this with a weak HashSet
+ /**
+ * WeakHashMap to keep references of WorkingMemories but allow them to be
+ * garbage collected
+ */
private final transient Map workingMemories;
/** Special value when adding to the underlying map. */
private static final Object PRESENT = new Object();
+ // ------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------
+
/**
- * constractor that supplies default conflict resolution
+ * Construct.
*
- * @see LeapsDefaultConflictResolver
+ * @param rete
+ * The rete network.
*/
- public RuleBaseImpl() throws DuplicateRuleNameException,
- InvalidPatternException, InvalidRuleException {
- this(DefaultConflictResolver.getInstance(),
- new DefaultFactHandleFactory(), new HashSet(), new HashMap(),
+ public RuleBaseImpl() throws RuleIntegrationException,
+ RuleSetIntegrationException, FactException, InvalidPatternException {
+ this(new HandleFactory(), new HashSet(), new HashMap(),
new RuleBaseContext());
-
}
- public RuleBaseImpl(ConflictResolver conflictResolver,
- FactHandleFactory factHandleFactory, Set ruleSets,
+ /**
+ * Construct.
+ *
+ * @param rete
+ * The rete network.
+ * @param conflictResolver
+ * The conflict resolver.
+ * @param factHandleFactory
+ * The fact handle factory.
+ * @param ruleSets
+ * @param applicationData
+ */
+ public RuleBaseImpl(FactHandleFactory factHandleFactory, Set ruleSets,
Map applicationData, RuleBaseContext ruleBaseContext)
- throws DuplicateRuleNameException, InvalidPatternException,
- InvalidRuleException {
+ throws RuleIntegrationException, RuleSetIntegrationException,
+ FactException, InvalidPatternException {
+ ObjectTypeResolver resolver = new ClassObjectTypeResolver();
+ this.builder = new Builder(this, resolver);
this.factHandleFactory = factHandleFactory;
- this.conflictResolver = conflictResolver;
+ this.ruleSets = ruleSets;
this.applicationData = applicationData;
this.ruleBaseContext = ruleBaseContext;
this.workingMemories = new WeakHashMap();
- this.builder = new Builder();
-
- this.ruleSets = new HashMap();
- if (ruleSets != null) {
- int i = 0;
- RuleSet ruleSet;
- for (Iterator it = ruleSets.iterator(); it.hasNext(); i++) {
- ruleSet = (RuleSet) it.next();
- this.ruleSets.put(new Integer(i), ruleSet);
- Rule[] rules = ruleSet.getRules();
- for (int k = 0; k < rules.length; k++) {
- this.addRule(rules[k]);
- }
- }
+
+ this.ruleSets = new HashSet();
+ for (Iterator it = ruleSets.iterator(); it.hasNext();) {
+ this.addRuleSet((RuleSet) it.next());
}
- // default one to collect standalone rules
- this.ruleSets.put(defaultRuleSet, new RuleSet(defaultRuleSet,
- this.ruleBaseContext));
}
- /**
- * constractor. Takes conflict resolution class that for each fact and rule
- * sides must not return 0 if o1 != 02
- */
-
- public RuleBaseImpl(ConflictResolver conflictResolver)
- throws DuplicateRuleNameException, InvalidPatternException,
- InvalidRuleException {
- this(conflictResolver, new DefaultFactHandleFactory(), new HashSet(),
- new HashMap(), new RuleBaseContext());
-
- }
+ // ------------------------------------------------------------
+ // Instance methods
+ // ------------------------------------------------------------
/**
- * factory method for new working memory. will keep reference by default.
- * <b>Note:</b> references kept in a week hashmap.
- *
- * @return new working memory instance
- *
- * @see LeapsWorkingMemory
+ * @see RuleBase
*/
public WorkingMemory newWorkingMemory() {
- return this.newWorkingMemory(true);
+ return newWorkingMemory(true);
}
/**
- * factory method for new working memory. will keep reference by default.
- * <b>Note:</b> references kept in a week hashmap.
- *
- * @param keepReference
- * @return new working memory instance
- *
- * @see LeapsWorkingMemory
+ * @see RuleBase
*/
public WorkingMemory newWorkingMemory(boolean keepReference) {
- WorkingMemory workingMemory = new WorkingMemoryImpl(this);
- // process existing rules
+ WorkingMemoryImpl workingMemory = new WorkingMemoryImpl(this);
+ // add all rules added so far
for (Iterator it = this.leapsRules.values().iterator(); it.hasNext();) {
((WorkingMemoryImpl) workingMemory).addLeapsRules((List) it.next());
}
+ //
if (keepReference) {
- this.workingMemories.put(workingMemory, PRESENT);
+ this.workingMemories.put(workingMemory, RuleBaseImpl.PRESENT);
}
return workingMemory;
}
@@ -152,70 +135,127 @@ void disposeWorkingMemory(WorkingMemory workingMemory) {
this.workingMemories.remove(workingMemory);
}
- public Set getWorkingMemories() {
- return this.workingMemories.keySet();
- }
-
/**
- * TODO clash with leaps conflict resolver
+ * TODO do not understand its location here
*
* @see RuleBase
*/
- public org.drools.spi.ConflictResolver getConflictResolver() {
- return (org.drools.spi.ConflictResolver) null;
+ public FactHandleFactory getFactHandleFactory() {
+ return this.factHandleFactory;
}
- public ConflictResolver getLeapsConflictResolver() {
- return this.conflictResolver;
+ public FactHandleFactory newFactHandleFactory() {
+ return this.factHandleFactory.newInstance();
}
/**
- * @see RuleBase
+ * Assert a fact object.
+ *
+ * @param handle
+ * The handle.
+ * @param object
+ * The fact.
+ * @param workingMemory
+ * The working-memory.
+ *
+ * @throws FactException
+ * If an error occurs while performing the assertion.
*/
- public RuleSet[] getRuleSets() {
- return (RuleSet[]) this.ruleSets.values().toArray(
- new RuleSet[this.ruleSets.size()]);
- }
+// void assertObject(FactHandle handle, Object object,
+// PropagationContext context, WorkingMemoryImpl workingMemory)
+// throws FactException {
+// workingMemory.assertObject(object);
+// }
/**
- * Creates leaps rule wrappers and propagate rule to the working memories
+ * Retract a fact object.
*
- * @param rule
- * @throws DuplicateRuleNameException
- * @throws InvalidRuleException
- * @throws InvalidPatternException
+ * @param handle
+ * The handle.
+ * @param workingMemory
+ * The working-memory.
+ *
+ * @throws FactException
+ * If an error occurs while performing the retraction.
*/
- public void addRule(Rule rule) throws DuplicateRuleNameException,
- InvalidRuleException, InvalidPatternException {
- List rules = this.builder.processRule(rule);
-
- this.leapsRules.put(rule, rules);
-
- for(Iterator it = this.workingMemories.keySet().iterator(); it.hasNext();) {
- ((WorkingMemoryImpl)it.next()).addLeapsRules(rules);
- }
+// void retractObject(FactHandle handle, PropagationContext context,
+// WorkingMemoryImpl workingMemory) throws FactException {
+// workingMemory.retractObject(handle);
+// }
+//
+ public RuleSet[] getRuleSets() {
+ return (RuleSet[]) this.ruleSets.toArray(new RuleSet[this.ruleSets
+ .size()]);
}
- /**
- * @see RuleBase
- */
public Map getApplicationData() {
return this.applicationData;
}
- /**
- * @see RuleBase
- */
public RuleBaseContext getRuleBaseContext() {
return this.ruleBaseContext;
}
/**
- * TODO do not understand its location here
+ * Add a <code>RuleSet</code> to the network. Iterates through the
+ * <code>RuleSet</code> adding Each individual <code>Rule</code> to the
+ * network.
*
- * @see RuleBase
+ * @param ruleSet
+ * The rule-set to add.
+ *
+ * @throws RuleIntegrationException
+ * if an error prevents complete construction of the network for
+ * the <code>Rule</code>.
+ * @throws FactException
+ * @throws InvalidPatternException
*/
- public FactHandleFactory getFactHandleFactory() {
- return this.factHandleFactory;
+ public void addRuleSet(RuleSet ruleSet) throws RuleIntegrationException,
+ RuleSetIntegrationException, FactException, InvalidPatternException {
+ Map newApplicationData = ruleSet.getApplicationData();
+
+ // Check that the application data is valid, we cannot change the type
+ // of an already declared application data variable
+ for (Iterator it = newApplicationData.keySet().iterator(); it.hasNext();) {
+ String identifier = (String) it.next();
+ Class type = (Class) newApplicationData.get(identifier);
+ if (this.applicationData.containsKey(identifier)
+ && !this.applicationData.get(identifier).equals(type)) {
+ throw new RuleSetIntegrationException(ruleSet);
+ }
+ }
+ this.applicationData.putAll(newApplicationData);
+
+ this.ruleSets.add(ruleSet);
+
+ Rule[] rules = ruleSet.getRules();
+
+ for (int i = 0; i < rules.length; ++i) {
+ addRule(rules[i]);
+ }
+ }
+
+ /**
+ * Creates leaps rule wrappers and propagate rule to the working memories
+ *
+ * @param rule
+ * @throws FactException
+ * @throws RuleIntegrationException
+ * @throws InvalidPatternException
+ */
+ public void addRule(Rule rule) throws FactException,
+ RuleIntegrationException, InvalidPatternException {
+ List rules = this.builder.processRule(rule);
+
+ this.leapsRules.put(rule, rules);
+
+ for (Iterator it = this.workingMemories.keySet().iterator(); it
+ .hasNext();) {
+ ((WorkingMemoryImpl) it.next()).addLeapsRules(rules);
+ }
+ }
+
+ public Set getWorkingMemories() {
+ return this.workingMemories.keySet();
}
}
|
5b4e584e455a1d4713119308c846d66fcfd52d9a
|
drools
|
JBRULES-2439--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@31842 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialectConfiguration.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialectConfiguration.java
index 88603d2b226..394a3502c7d 100644
--- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialectConfiguration.java
+++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialectConfiguration.java
@@ -150,6 +150,8 @@ private String getDefaultLanguageLevel() {
level = "1.5";
} else if ( version.startsWith( "1.6" ) ) {
level = "1.6";
+ } else if ( version.startsWith( "1.7" ) ) {
+ level = "1.7";
} else {
level = "1.5";
}
|
4804e610fca59b7e81b9e7a31ab7441fd47465e0
|
Delta Spike
|
DELTASPIKE-289 add WindowScoped and initial Context handling
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/scope/WindowScoped.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/scope/WindowScoped.java
new file mode 100644
index 000000000..692faac5d
--- /dev/null
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/scope/WindowScoped.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.deltaspike.core.api.scope;
+
+import javax.enterprise.context.NormalScope;
+import java.lang.annotation.Documented;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Beans which use this scope are bound to a application window (or browser tab).
+ */
+@Target( { METHOD,TYPE,FIELD } )
+@Retention(RUNTIME)
+@Inherited
+@Documented
+@NormalScope(passivating = true)
+public @interface WindowScoped
+{
+}
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java
index 0638c6969..ff84d3eb5 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java
@@ -32,9 +32,9 @@ public interface AttributeAware extends Serializable
* Sets an attribute
* @param name name of the attribute
* @param value value of the attribute (null values aren't allowed)
- * @return true if it was possible to set the value
+ * @return the old value or <code>null</code> if no previous value did exist
*/
- boolean setAttribute(String name, Object value);
+ Object setAttribute(String name, Object value);
/**
* Returns true if there is a value for the given name
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java
index d42e7cc1b..b08ede1e8 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java
@@ -61,7 +61,7 @@ public interface WindowContext
* This is necessary when the session gets closed down.
* @return
*/
- void closeAllWindowContexts();
+ void destroy();
}
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java
index 522af4287..1337b29cc 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java
@@ -151,6 +151,15 @@ public void destroyAllActive()
return;
}
+ destroyAllActive(storage);
+ }
+
+ /**
+ * destroys all the Contextual Instances in the Storage returned by
+ * {@link #getContextualStorage(boolean)}.
+ */
+ public void destroyAllActive(ContextualStorage storage)
+ {
Map<Object, ContextualInstanceInfo<?>> contextMap = storage.getStorage();
for (Map.Entry<Object, ContextualInstanceInfo<?>> entry : contextMap.entrySet())
{
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/DefaultWindowContext.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/DefaultWindowContext.java
new file mode 100644
index 000000000..ac27fea1f
--- /dev/null
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/DefaultWindowContext.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.deltaspike.core.impl.scope.window;
+
+import javax.enterprise.context.ContextNotActiveException;
+import javax.enterprise.context.SessionScoped;
+import javax.enterprise.inject.spi.BeanManager;
+import javax.inject.Inject;
+
+import java.lang.annotation.Annotation;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.deltaspike.core.api.scope.WindowScoped;
+import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+import org.apache.deltaspike.core.util.context.AbstractContext;
+import org.apache.deltaspike.core.util.context.ContextualStorage;
+
+/**
+ *
+ */
+@SessionScoped
+public class DefaultWindowContext extends AbstractContext implements WindowContext
+{
+ /**
+ * all the {@link WindowContext}s which are active in this very Session.
+ */
+ private Map<String, WindowContext> windowContexts = new ConcurrentHashMap<String, WindowContext>();
+
+ @Inject
+ private WindowIdHolder windowIdHolder;
+
+ @Inject
+ private WindowBeanHolder windowBeanHolder;
+
+ private BeanManager beanManager;
+
+
+ public DefaultWindowContext(BeanManager beanManager)
+ {
+ super(beanManager);
+
+ this.beanManager = beanManager;
+ }
+
+ @Override
+ public void activateWindowContext(String windowId)
+ {
+ windowIdHolder.setWindowId(windowId);
+ }
+
+ @Override
+ public String getCurrentWindowId()
+ {
+ return windowIdHolder.getWindowId();
+ }
+
+ @Override
+ public boolean closeCurrentWindowContext()
+ {
+ String windowId = windowIdHolder.getWindowId();
+ if (windowId == null)
+ {
+ return false;
+ }
+
+ WindowContext windowContext = windowContexts.get(windowId);
+ if (windowContext == null)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public synchronized void destroy()
+ {
+ Map<String, ContextualStorage> windowContexts = windowBeanHolder.newStorageMap();
+
+ for (ContextualStorage contextualStorage : windowContexts.values())
+ {
+ destroyAllActive(contextualStorage);
+ }
+ }
+
+ @Override
+ protected ContextualStorage getContextualStorage(boolean createIfNotExist)
+ {
+ String windowId = getCurrentWindowId();
+ if (windowId == null)
+ {
+ throw new ContextNotActiveException("WindowContext: no windowId set for the current Thread yet!");
+ }
+
+ return windowBeanHolder.getContextualStorage(beanManager, windowId);
+ }
+
+ @Override
+ public Class<? extends Annotation> getScope()
+ {
+ return WindowScoped.class;
+ }
+
+ /**
+ * The WindowContext is active once a current windowId is set for the current Thread.
+ * @return
+ */
+ @Override
+ public boolean isActive()
+ {
+ String windowId = getCurrentWindowId();
+ return windowId != null;
+ }
+}
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
new file mode 100644
index 000000000..791b1c352
--- /dev/null
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.deltaspike.core.impl.scope.window;
+
+import javax.enterprise.context.SessionScoped;
+import javax.enterprise.inject.spi.BeanManager;
+import java.io.Serializable;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.deltaspike.core.util.context.ContextualStorage;
+
+/**
+ * This holder will store the window Ids for the current
+ * Session. We use standard SessionScoped bean to not need
+ * to treat async-supported and similar headache.
+ */
+@SessionScoped
+public class WindowBeanHolder implements Serializable
+{
+ private volatile Map<String, ContextualStorage> storageMap = new ConcurrentHashMap<String, ContextualStorage>();
+
+ public Map<String, ContextualStorage> getStorageMap()
+ {
+ return storageMap;
+ }
+
+ /**
+ * This method will return the ContextualStorage or create a new one
+ * if no one is yet assigned to the current windowId.
+ */
+ public ContextualStorage getContextualStorage(BeanManager beanManager, String windowId)
+ {
+ ContextualStorage contextualStorage = storageMap.get(windowId);
+ if (contextualStorage == null)
+ {
+ synchronized (this)
+ {
+ contextualStorage = storageMap.get(windowId);
+ if (contextualStorage == null)
+ {
+ storageMap.put(windowId, new ContextualStorage(beanManager, true, true));
+ }
+ }
+ }
+
+ return contextualStorage;
+ }
+
+ public Map<String, ContextualStorage> newStorageMap()
+ {
+ Map<String, ContextualStorage> oldStorageMap = storageMap;
+ storageMap = new ConcurrentHashMap<String, ContextualStorage>();
+ return oldStorageMap;
+ }
+}
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowIdHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowIdHolder.java
new file mode 100644
index 000000000..dc611844e
--- /dev/null
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowIdHolder.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.deltaspike.core.impl.scope.window;
+
+/**
+ * Simple class which just provides a @RequestScoped windowId.
+ */
+public class WindowIdHolder
+{
+ private String windowId;
+
+ /**
+ * @return the detected windowId or <code>null</code> if not yet set.
+ */
+ public String getWindowId()
+ {
+ return windowId;
+ }
+
+ /**
+ * Set the windowId for the current thread.
+ * @param windowId
+ */
+ public void setWindowId(String windowId)
+ {
+ this.windowId = windowId;
+ }
+}
|
7fff3ab5f629e07a7b6d8ff56fc32dd68c9766f3
|
hbase
|
HADOOP-2308 null regioninfo breaks meta scanner--git-svn-id: https://svn.apache.org/repos/asf/lucene/hadoop/trunk/src/contrib/hbase@599875 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 91a4b672d962..5a21198ebed6 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -41,6 +41,7 @@ Trunk (unreleased changes)
(Bryan Duxbury via Stack)
HADOOP-2295 Fix assigning a region to multiple servers
HADOOP-2234 TableInputFormat erroneously aggregates map values
+ HADOOP-2308 null regioninfo breaks meta scanner
IMPROVEMENTS
HADOOP-2401 Add convenience put method that takes writable
diff --git a/src/java/org/apache/hadoop/hbase/HMaster.java b/src/java/org/apache/hadoop/hbase/HMaster.java
index d5424d36a54b..08b8cd3989e1 100644
--- a/src/java/org/apache/hadoop/hbase/HMaster.java
+++ b/src/java/org/apache/hadoop/hbase/HMaster.java
@@ -229,14 +229,19 @@ protected void scanRegion(final MetaRegion region) throws IOException {
if (values == null || values.size() == 0) {
break;
}
-
for (Map.Entry<Writable, Writable> e: values.entrySet()) {
HStoreKey key = (HStoreKey) e.getKey();
results.put(key.getColumn(),
((ImmutableBytesWritable) e.getValue()).get());
}
- HRegionInfo info = (HRegionInfo) Writables.getWritable(
- results.get(COL_REGIONINFO), new HRegionInfo());
+ byte [] bytes = results.get(COL_REGIONINFO);
+ if (bytes == null) {
+ LOG.warn(COL_REGIONINFO.toString() + " is empty; has keys: " +
+ values.keySet().toString());
+ continue;
+ }
+ HRegionInfo info = (HRegionInfo) Writables.getWritable(bytes,
+ new HRegionInfo());
String serverName = Writables.bytesToString(results.get(COL_SERVER));
long startCode = Writables.bytesToLong(results.get(COL_STARTCODE));
if (LOG.isDebugEnabled()) {
|
4cbe2ae00aaec2ca4074b06f389f5e50ca235da3
|
spring-framework
|
[SPR-8387] Introduced- supports(MergedContextConfiguration) method in the SmartContextLoader SPI;- updated existing loaders accordingly; and fleshed out implementation of and- tests for the new DelegatingSmartContextLoader.--
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.test/src/main/java/org/springframework/test/context/SmartContextLoader.java b/org.springframework.test/src/main/java/org/springframework/test/context/SmartContextLoader.java
index 683a200d54b8..16f8655e0a86 100644
--- a/org.springframework.test/src/main/java/org/springframework/test/context/SmartContextLoader.java
+++ b/org.springframework.test/src/main/java/org/springframework/test/context/SmartContextLoader.java
@@ -95,6 +95,14 @@ public interface SmartContextLoader extends ContextLoader {
*/
void processContextConfiguration(ContextConfigurationAttributes configAttributes);
+ /**
+ * TODO Document supports(MergedContextConfiguration).
+ *
+ * @param mergedConfig
+ * @return
+ */
+ boolean supports(MergedContextConfiguration mergedConfig);
+
/**
* Loads a new {@link ApplicationContext context} based on the supplied
* {@link MergedContextConfiguration merged context configuration},
diff --git a/org.springframework.test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java b/org.springframework.test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java
index faf88f520e12..a8d3261115f7 100644
--- a/org.springframework.test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java
+++ b/org.springframework.test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java
@@ -23,6 +23,7 @@
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextLoader;
+import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -90,6 +91,13 @@ public void processContextConfiguration(ContextConfigurationAttributes configAtt
configAttributes.setLocations(processedLocations);
}
+ /**
+ * TODO Document default supports(MergedContextConfiguration) implementation.
+ */
+ public boolean supports(MergedContextConfiguration mergedConfig) {
+ return !ObjectUtils.isEmpty(mergedConfig.getLocations());
+ }
+
// --- ContextLoader -------------------------------------------------------
/**
diff --git a/org.springframework.test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoader.java b/org.springframework.test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoader.java
index bdb8adad6cdf..87599eb13b13 100644
--- a/org.springframework.test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoader.java
+++ b/org.springframework.test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoader.java
@@ -81,6 +81,14 @@ public void processContextConfiguration(ContextConfigurationAttributes configAtt
}
}
+ /**
+ * TODO Document overridden supports(MergedContextConfiguration) implementation.
+ */
+ @Override
+ public boolean supports(MergedContextConfiguration mergedConfig) {
+ return ObjectUtils.isEmpty(mergedConfig.getLocations()) && !ObjectUtils.isEmpty(mergedConfig.getClasses());
+ }
+
// --- AnnotationConfigContextLoader ---------------------------------------
private boolean isStaticNonPrivateAndNonFinal(Class<?> clazz) {
diff --git a/org.springframework.test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java b/org.springframework.test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java
index 8e4de5d39957..6aa828a1c968 100644
--- a/org.springframework.test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java
+++ b/org.springframework.test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java
@@ -26,6 +26,7 @@
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.SmartContextLoader;
+import org.springframework.util.ObjectUtils;
/**
* TODO Document DelegatingSmartContextLoader.
@@ -62,6 +63,11 @@ public boolean generatesDefaults() {
* TODO Document processContextConfiguration() implementation.
*/
public void processContextConfiguration(ContextConfigurationAttributes configAttributes) {
+
+ final String[] originalLocations = configAttributes.getLocations();
+ final Class<?>[] originalClasses = configAttributes.getClasses();
+ final boolean emptyResources = ObjectUtils.isEmpty(originalLocations) && ObjectUtils.isEmpty(originalClasses);
+
for (SmartContextLoader loader : candidates) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Delegating to loader [%s] to process context configuration [%s].",
@@ -73,7 +79,9 @@ public void processContextConfiguration(ContextConfigurationAttributes configAtt
// If the original locations and classes are not empty, there's no
// need to bother with default generation checks; just let each
// loader process the configuration.
- //
+ if (!emptyResources) {
+ loader.processContextConfiguration(configAttributes);
+ }
// Otherwise, if a loader claims to generate defaults, let it
// process the configuration, and then verify that it actually did
// generate defaults.
@@ -83,9 +91,26 @@ public void processContextConfiguration(ContextConfigurationAttributes configAtt
// 1) stop iterating
// 2) mark the current loader as the winning candidate (?)
// 3) log an info message.
+ else {
+ if (loader.generatesDefaults()) {
+ loader.processContextConfiguration(configAttributes);
+ }
+ }
+ }
+ // If any loader claims to generate defaults but none actually did,
+ // throw an exception.
+ }
- loader.processContextConfiguration(configAttributes);
+ /**
+ * TODO Document supports(MergedContextConfiguration) implementation.
+ */
+ public boolean supports(MergedContextConfiguration mergedConfig) {
+ for (SmartContextLoader loader : candidates) {
+ if (loader.supports(mergedConfig)) {
+ return true;
+ }
}
+ return false;
}
/**
@@ -99,21 +124,16 @@ public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) t
loader.getClass().getName(), mergedConfig));
}
- // TODO Implement loadContext(MergedContextConfiguration).
- //
- // Ask each loader if it _can_ load a context from the mergedConfig.
+ // Ask each loader if it can load a context from the mergedConfig.
// If a loader can, let it; otherwise, continue iterating over all
// remaining candidates.
- //
- // If no candidate can load a context from the mergedConfig, throw
- // an exception.
+ if (loader.supports(mergedConfig)) {
+ return loader.loadContext(mergedConfig);
+ }
}
- // TODO Implement delegation logic.
- //
- // Proof of concept: ensuring that hard-coded delegation to
- // GenericXmlContextLoader works "as is".
- return candidates.get(0).loadContext(mergedConfig);
+ throw new IllegalStateException(String.format("None of the candidate SmartContextLoaders [%s] "
+ + "was able to load an ApplicationContext from [%s].", candidates, mergedConfig));
}
// --- ContextLoader -------------------------------------------------------
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java
index 40a89205730e..f9096ab5f067 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java
@@ -26,6 +26,13 @@
import org.springframework.test.context.junit4.annotation.BeanOverridingExplicitConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.DefaultConfigClassesBaseTests;
import org.springframework.test.context.junit4.annotation.DefaultConfigClassesInheritedTests;
+import org.springframework.test.context.junit4.annotation.DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests;
+import org.springframework.test.context.junit4.annotation.DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests;
+import org.springframework.test.context.junit4.annotation.DefaultLoaderDefaultConfigClassesBaseTests;
+import org.springframework.test.context.junit4.annotation.DefaultLoaderDefaultConfigClassesInheritedTests;
+import org.springframework.test.context.junit4.annotation.DefaultLoaderExplicitConfigClassesBaseTests;
+import org.springframework.test.context.junit4.annotation.DefaultLoaderExplicitConfigClassesInheritedTests;
+import org.springframework.test.context.junit4.annotation.ExplicitConfigClassesBaseTests;
import org.springframework.test.context.junit4.annotation.ExplicitConfigClassesInheritedTests;
import org.springframework.test.context.junit4.orm.HibernateSessionFlushingTests;
import org.springframework.test.context.junit4.profile.annotation.DefaultProfileAnnotationConfigTests;
@@ -58,12 +65,19 @@
DefaultConfigClassesBaseTests.class,//
DefaultConfigClassesInheritedTests.class,//
BeanOverridingDefaultConfigClassesInheritedTests.class,//
+ ExplicitConfigClassesBaseTests.class,//
ExplicitConfigClassesInheritedTests.class,//
BeanOverridingExplicitConfigClassesInheritedTests.class,//
+ DefaultLoaderDefaultConfigClassesBaseTests.class,//
+ DefaultLoaderDefaultConfigClassesInheritedTests.class,//
+ DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.class,//
+ DefaultLoaderExplicitConfigClassesBaseTests.class,//
+ DefaultLoaderExplicitConfigClassesInheritedTests.class,//
+ DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.class,//
DefaultProfileAnnotationConfigTests.class,//
- DevProfileAnnotationConfigTests.class, //
+ DevProfileAnnotationConfigTests.class,//
DefaultProfileXmlConfigTests.class,//
- DevProfileXmlConfigTests.class, //
+ DevProfileXmlConfigTests.class,//
ExpectedExceptionSpringRunnerTests.class,//
TimedSpringRunnerTests.class,//
RepeatedSpringRunnerTests.class,//
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests.java
index 7c7cef5c5440..e83eaddd33d0 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests.java
@@ -18,7 +18,6 @@
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunnerAppCtxTests;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
/**
* Integration tests that verify support for configuration classes in
@@ -34,7 +33,7 @@
* @author Sam Brannen
* @since 3.1
*/
-@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = PojoAndStringConfig.class, inheritLocations = false)
+@ContextConfiguration(classes = PojoAndStringConfig.class, inheritLocations = false)
public class AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
/* all tests are in the parent class. */
}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigTestSuite.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigTestSuite.java
index e2ff34c6625e..f0dde3f7ea25 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigTestSuite.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/AnnotationConfigTestSuite.java
@@ -34,8 +34,15 @@
DefaultConfigClassesBaseTests.class,//
DefaultConfigClassesInheritedTests.class,//
BeanOverridingDefaultConfigClassesInheritedTests.class,//
+ ExplicitConfigClassesBaseTests.class,//
+ ExplicitConfigClassesInheritedTests.class,//
BeanOverridingExplicitConfigClassesInheritedTests.class,//
- ExplicitConfigClassesInheritedTests.class //
+ DefaultLoaderDefaultConfigClassesBaseTests.class,//
+ DefaultLoaderDefaultConfigClassesInheritedTests.class,//
+ DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.class,//
+ DefaultLoaderExplicitConfigClassesBaseTests.class,//
+ DefaultLoaderExplicitConfigClassesInheritedTests.class,//
+ DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.class //
})
public class AnnotationConfigTestSuite {
}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java
index 3bd2fea8ae18..61a033f3cb94 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java
@@ -29,8 +29,8 @@
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
- * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTestsConfig}
- * and {@link BeanOverridingDefaultConfigClassesInheritedTestsConfig}.
+ * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}
+ * and {@link BeanOverridingDefaultConfigClassesInheritedTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java
index c0cc2721d03f..537e46ead0e0 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java
@@ -26,8 +26,8 @@
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
- * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTestsConfig}
- * and {@link BeanOverridingDefaultConfigClassesInheritedTestsConfig}.
+ * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}
+ * and {@link BeanOverridingDefaultConfigClassesInheritedTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java
index 046d95954b56..05c586dcd3a0 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java
@@ -33,7 +33,7 @@
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
- * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTestsConfig}.
+ * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java
index 6351e0c71d0e..281c8f3f266b 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java
@@ -30,8 +30,8 @@
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
- * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTestsConfig}
- * and {@link DefaultConfigClassesInheritedTestsConfig}.
+ * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}
+ * and {@link DefaultConfigClassesInheritedTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java
new file mode 100644
index 000000000000..c61562127f50
--- /dev/null
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.test.context.junit4.annotation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.springframework.beans.Employee;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.support.DelegatingSmartContextLoader;
+
+/**
+ * Integration tests that verify support for configuration classes in
+ * the Spring TestContext Framework in conjunction with the
+ * {@link DelegatingSmartContextLoader}.
+ *
+ * @author Sam Brannen
+ * @since 3.1
+ */
+@ContextConfiguration
+public class DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests extends
+ DefaultLoaderDefaultConfigClassesBaseTests {
+
+ @Configuration
+ static class Config {
+
+ @Bean
+ public Employee employee() {
+ Employee employee = new Employee();
+ employee.setName("Yoda");
+ employee.setAge(900);
+ employee.setCompany("The Force");
+ return employee;
+ }
+ }
+
+
+ @Test
+ @Override
+ public void verifyEmployeeSetFromBaseContextConfig() {
+ assertNotNull("The employee should have been autowired.", this.employee);
+ assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName());
+ }
+
+}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java
new file mode 100644
index 000000000000..cdf4207a0161
--- /dev/null
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.test.context.junit4.annotation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.support.DelegatingSmartContextLoader;
+
+/**
+ * Integration tests that verify support for configuration classes in
+ * the Spring TestContext Framework in conjunction with the
+ * {@link DelegatingSmartContextLoader}.
+ *
+ * @author Sam Brannen
+ * @since 3.1
+ */
+@ContextConfiguration(classes = DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.Config.class)
+public class DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests extends
+ DefaultLoaderExplicitConfigClassesBaseTests {
+
+ @Test
+ @Override
+ public void verifyEmployeeSetFromBaseContextConfig() {
+ assertNotNull("The employee should have been autowired.", this.employee);
+ assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName());
+ }
+
+}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java
new file mode 100644
index 000000000000..dcc5249163c6
--- /dev/null
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.test.context.junit4.annotation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.Employee;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DelegatingSmartContextLoader;
+
+/**
+ * Integration tests that verify support for configuration classes in
+ * the Spring TestContext Framework in conjunction with the
+ * {@link DelegatingSmartContextLoader}.
+ *
+ * @author Sam Brannen
+ * @since 3.1
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration
+public class DefaultLoaderDefaultConfigClassesBaseTests {
+
+ @Configuration
+ static class Config {
+
+ @Bean
+ public Employee employee() {
+ Employee employee = new Employee();
+ employee.setName("John Smith");
+ employee.setAge(42);
+ employee.setCompany("Acme Widgets, Inc.");
+ return employee;
+ }
+ }
+
+
+ @Autowired
+ protected Employee employee;
+
+
+ @Test
+ public void verifyEmployeeSetFromBaseContextConfig() {
+ assertNotNull("The employee field should have been autowired.", this.employee);
+ assertEquals("John Smith", this.employee.getName());
+ }
+
+}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java
new file mode 100644
index 000000000000..a5706a1517d6
--- /dev/null
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.test.context.junit4.annotation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.springframework.beans.Pet;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.support.DelegatingSmartContextLoader;
+
+/**
+ * Integration tests that verify support for configuration classes in
+ * the Spring TestContext Framework in conjunction with the
+ * {@link DelegatingSmartContextLoader}.
+ *
+ * @author Sam Brannen
+ * @since 3.1
+ */
+@ContextConfiguration
+public class DefaultLoaderDefaultConfigClassesInheritedTests extends DefaultLoaderDefaultConfigClassesBaseTests {
+
+ @Configuration
+ static class Config {
+
+ @Bean
+ public Pet pet() {
+ return new Pet("Fido");
+ }
+ }
+
+
+ @Autowired
+ private Pet pet;
+
+
+ @Test
+ public void verifyPetSetFromExtendedContextConfig() {
+ assertNotNull("The pet should have been autowired.", this.pet);
+ assertEquals("Fido", this.pet.getName());
+ }
+
+}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java
new file mode 100644
index 000000000000..46b72595814b
--- /dev/null
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.test.context.junit4.annotation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.Employee;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DelegatingSmartContextLoader;
+
+/**
+ * Integration tests that verify support for configuration classes in
+ * the Spring TestContext Framework in conjunction with the
+ * {@link DelegatingSmartContextLoader}.
+ *
+ * @author Sam Brannen
+ * @since 3.1
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = DefaultLoaderDefaultConfigClassesBaseTests.Config.class)
+public class DefaultLoaderExplicitConfigClassesBaseTests {
+
+ @Autowired
+ protected Employee employee;
+
+
+ @Test
+ public void verifyEmployeeSetFromBaseContextConfig() {
+ assertNotNull("The employee should have been autowired.", this.employee);
+ assertEquals("John Smith", this.employee.getName());
+ }
+
+}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java
new file mode 100644
index 000000000000..69a2c846b53d
--- /dev/null
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.test.context.junit4.annotation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.Pet;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DelegatingSmartContextLoader;
+
+/**
+ * Integration tests that verify support for configuration classes in
+ * the Spring TestContext Framework in conjunction with the
+ * {@link DelegatingSmartContextLoader}.
+ *
+ * @author Sam Brannen
+ * @since 3.1
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = DefaultLoaderDefaultConfigClassesInheritedTests.Config.class)
+public class DefaultLoaderExplicitConfigClassesInheritedTests extends DefaultLoaderExplicitConfigClassesBaseTests {
+
+ @Autowired
+ private Pet pet;
+
+
+ @Test
+ public void verifyPetSetFromExtendedContextConfig() {
+ assertNotNull("The pet should have been autowired.", this.pet);
+ assertEquals("Fido", this.pet.getName());
+ }
+
+}
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java
index e45bc3d03310..cd351bdfc01b 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java
@@ -31,7 +31,7 @@
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
- * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTestsConfig}.
+ * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java
index 21b19c31b266..642d2d67e75d 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java
@@ -31,8 +31,8 @@
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
- * <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTestsConfig}
- * and {@link DefaultConfigClassesInheritedTestsConfig}
+ * <p>Configuration will be loaded from {@link DefaultConfigClassesInheritedTests.ContextConfiguration}
+ * and {@link DefaultConfigClassesBaseTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
|
710ae3a9d2fbcb6767872656d82b2edaeb6e0656
|
spring-framework
|
SpringJUnit4ClassRunnerAppCtxTests now verifies- seamless support for using @Inject in addition to @Autowired
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.test/.classpath b/org.springframework.test/.classpath
index d35f01db07af..5e5a2e70be5f 100644
--- a/org.springframework.test/.classpath
+++ b/org.springframework.test/.classpath
@@ -15,6 +15,7 @@
<classpathentry combineaccessrules="false" kind="src" path="/org.springframework.web.portlet"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.springframework.web.servlet"/>
<classpathentry kind="var" path="IVY_CACHE/javax.activation/com.springsource.javax.activation/1.1.0/com.springsource.javax.activation-1.1.0.jar" sourcepath="/IVY_CACHE/javax.activation/com.springsource.javax.activation/1.1.0/com.springsource.javax.activation-sources-1.1.0.jar"/>
+ <classpathentry kind="var" path="IVY_CACHE/javax.inject/com.springsource.javax.inject/0.9.0.PFD/com.springsource.javax.inject-0.9.0.PFD.jar" sourcepath="/IVY_CACHE/javax.inject/com.springsource.javax.inject/0.9.0.PFD/com.springsource.javax.inject-sources-0.9.0.PFD.jar"/>
<classpathentry kind="var" path="IVY_CACHE/javax.persistence/com.springsource.javax.persistence/1.0.0/com.springsource.javax.persistence-1.0.0.jar" sourcepath="/IVY_CACHE/javax.persistence/com.springsource.javax.persistence/1.0.0/com.springsource.javax.persistence-sources-1.0.0.jar"/>
<classpathentry kind="var" path="IVY_CACHE/javax.portlet/com.springsource.javax.portlet/2.0.0/com.springsource.javax.portlet-2.0.0.jar"/>
<classpathentry kind="var" path="IVY_CACHE/javax.servlet/com.springsource.javax.servlet/2.5.0/com.springsource.javax.servlet-2.5.0.jar" sourcepath="/IVY_CACHE/javax.servlet/com.springsource.javax.servlet/2.5.0/com.springsource.javax.servlet-sources-2.5.0.jar"/>
diff --git a/org.springframework.test/ivy.xml b/org.springframework.test/ivy.xml
index e64c205bb575..b70e01038eed 100644
--- a/org.springframework.test/ivy.xml
+++ b/org.springframework.test/ivy.xml
@@ -21,6 +21,7 @@
<dependencies>
<dependency org="javax.activation" name="com.springsource.javax.activation" rev="1.1.0" conf="provided->compile"/>
<dependency org="javax.el" name="com.springsource.javax.el" rev="1.0.0" conf="provided->compile"/>
+ <dependency org="javax.inject" name="com.springsource.javax.inject" rev="0.9.0.PFD" conf="test->compile"/>
<dependency org="javax.persistence" name="com.springsource.javax.persistence" rev="1.0.0" conf="provided->compile"/>
<dependency org="javax.portlet" name="com.springsource.javax.portlet" rev="2.0.0" conf="provided->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet" rev="2.5.0" conf="provided->compile"/>
diff --git a/org.springframework.test/pom.xml b/org.springframework.test/pom.xml
index 3518579246f8..332939c8b645 100644
--- a/org.springframework.test/pom.xml
+++ b/org.springframework.test/pom.xml
@@ -25,6 +25,12 @@
<version>1.0</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>javax.inject</groupId>
+ <artifactId>com.springsource.javax.inject</artifactId>
+ <version>0.9.0.PFD</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java
index 91b51242bdfc..e23164bcf1f2 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java
@@ -19,9 +19,11 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import javax.annotation.Resource;
+import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,6 +50,7 @@
* <ul>
* <li>{@link ContextConfiguration @ContextConfiguration}</li>
* <li>{@link Autowired @Autowired}</li>
+ * <li>{@link Inject @Inject}</li>
* <li>{@link Qualifier @Qualifier}</li>
* <li>{@link Resource @Resource}</li>
* <li>{@link ApplicationContextAware}</li>
@@ -59,10 +62,12 @@
* {@link ContextConfiguration#locations() locations} are explicitly declared
* and since the {@link ContextConfiguration#loader() ContextLoader} is left set
* to the default value of {@link GenericXmlContextLoader}, this test class's
- * dependencies will be injected via {@link Autowired @Autowired} and
- * {@link Resource @Resource} from beans defined in the
- * {@link ApplicationContext} loaded from the default classpath resource:
- * <code>"/org/springframework/test/context/junit/SpringJUnit4ClassRunnerAppCtxTests-context.xml"</code>.
+ * dependencies will be injected via {@link Autowired @Autowired},
+ * {@link Inject @Inject}, and {@link Resource @Resource} from beans defined in
+ * the {@link ApplicationContext} loaded from the default classpath resource:
+ *
+ * <code>"/org/springframework/test/context/junit/SpringJUnit4ClassRunnerAppCtxTests-context.xml"</code>
+ * .
* </p>
*
* @author Sam Brannen
@@ -93,12 +98,15 @@ public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAwa
private Employee employee;
@Autowired
- private Pet pet;
+ private Pet autowiredPet;
+
+ @Inject
+ private Pet injectedPet;
@Autowired(required = false)
protected Long nonrequiredLong;
- @Resource()
+ @Resource
protected String foo;
protected String bar;
@@ -153,11 +161,14 @@ public final void verifyBeanNameSet() {
}
@Test
- public final void verifyAnnotationAutowiredFields() {
+ public final void verifyAnnotationAutowiredAndInjectedFields() {
assertNull("The nonrequiredLong field should NOT have been autowired.", this.nonrequiredLong);
assertEquals("The quux field should have been autowired via @Autowired and @Qualifier.", "Quux", this.quux);
- assertNotNull("The pet field should have been autowired.", this.pet);
- assertEquals("Fido", this.pet.getName());
+ assertNotNull("The pet field should have been autowired.", this.autowiredPet);
+ assertNotNull("The pet field should have been injected.", this.injectedPet);
+ assertEquals("Fido", this.autowiredPet.getName());
+ assertEquals("Fido", this.injectedPet.getName());
+ assertSame("@Autowired and @Inject pet should be the same object.", this.autowiredPet, this.injectedPet);
}
@Test
@@ -176,4 +187,4 @@ public final void verifyResourceAnnotationWiredMethods() {
assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar);
}
-}
+}
\ No newline at end of file
diff --git a/org.springframework.test/test.iml b/org.springframework.test/test.iml
index a5a65c18b9ae..924d7b776d9d 100644
--- a/org.springframework.test/test.iml
+++ b/org.springframework.test/test.iml
@@ -24,6 +24,7 @@
<orderEntry type="library" name="Commons Logging" level="project" />
<orderEntry type="library" name="EasyMock" level="project" />
<orderEntry type="library" name="javax.el" level="project" />
+ <orderEntry type="library" name="javax.inject" level="project" />
<orderEntry type="library" name="JUnit" level="project" />
<orderEntry type="module-library">
<library>
|
d9d05e0b057335f3d1c7923cbee9d37c3a528d01
|
drools
|
JBRULES-85--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@3162 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/base/ClassFieldExtractorFactory.java b/drools-core/src/main/java/org/drools/base/ClassFieldExtractorFactory.java
index 55618a83975..1d1d3b26154 100644
--- a/drools-core/src/main/java/org/drools/base/ClassFieldExtractorFactory.java
+++ b/drools-core/src/main/java/org/drools/base/ClassFieldExtractorFactory.java
@@ -29,9 +29,9 @@
import org.drools.asm.Opcodes;
/**
- *
+ * This is an alternative to FieldAccessorGenerator.
* @author Alexander Bagerman
- *
+ * TODO: Use this instead of FieldAccessorGenerator - it should be able to be more efficient.
*/
public class ClassFieldExtractorFactory {
@@ -55,7 +55,7 @@ public static BaseClassFieldExtractor getClassFieldExtractor(Class clazz,
String typeName = getTypeName(fieldType);
// generating byte array to create target class
byte[] bytes = dump(originalClassName, className, getterName,
- typeName, fieldType);
+ typeName, fieldType, clazz.isInterface());
// use bytes to get a class
ByteArrayClassLoader classLoader = new ByteArrayClassLoader(Thread
.currentThread().getContextClassLoader());
@@ -86,7 +86,7 @@ protected static Class getFieldType(Class clazz, String name)
}
private static byte[] dump(String originalClassName, String className,
- String getterName, String typeName, Class fieldType)
+ String getterName, String typeName, Class fieldType, boolean isInterface)
throws Exception {
ClassWriter cw = new ClassWriter(false);
@@ -142,8 +142,15 @@ private static byte[] dump(String originalClassName, String className,
mv.visitInsn(Opcodes.DUP);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.CHECKCAST, originalClassName);
- mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, originalClassName,
- getterName, "()" + primitiveTypeTag);
+
+ if (isInterface) {
+ mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, originalClassName,
+ getterName, "()" + primitiveTypeTag);
+
+ } else {
+ mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, originalClassName,
+ getterName, "()" + primitiveTypeTag);
+ }
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, typeName, "<init>", "("
+ primitiveTypeTag + ")V");
mv.visitInsn(Opcodes.ARETURN);
@@ -164,8 +171,13 @@ private static byte[] dump(String originalClassName, String className,
mv.visitLineNumber(15, l0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.CHECKCAST, originalClassName);
- mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, originalClassName,
- getterName, "()L" + typeName + ";");
+ if (isInterface) {
+ mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, originalClassName,
+ getterName, "()L" + typeName + ";");
+ } else {
+ mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, originalClassName,
+ getterName, "()L" + typeName + ";");
+ }
mv.visitInsn(Opcodes.ARETURN);
Label l1 = new Label();
mv.visitLabel(l1);
diff --git a/drools-core/src/main/java/org/drools/util/asm/ClassFieldInspector.java b/drools-core/src/main/java/org/drools/util/asm/ClassFieldInspector.java
index 2df93743468..fde561e9388 100644
--- a/drools-core/src/main/java/org/drools/util/asm/ClassFieldInspector.java
+++ b/drools-core/src/main/java/org/drools/util/asm/ClassFieldInspector.java
@@ -99,14 +99,14 @@ public MethodVisitor visitMethod(int access,
String[] exceptions) {
//only want public methods that start with 'get' or 'is'
//and have no args, and return a value
- if (access == Opcodes.ACC_PUBLIC) {
+ if ((access & Opcodes.ACC_PUBLIC) > 0) {
if (desc.startsWith( "()" ) && ( name.startsWith("get") || name.startsWith("is") ) ) {
try {
Method method = clazz.getMethod(name, null);
if (method.getReturnType() != void.class) {
int fieldIndex = methodList.size();
- methodList.add(method);
- addToMapping(method, fieldIndex);
+ methodList.add(method);
+ addToMapping(method.getName(), fieldIndex);
}
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Error in getting field access method.");
@@ -186,8 +186,8 @@ public FieldVisitor visitField(int arg0,
- private void addToMapping(Method method, int index) {
- String name = method.getName();
+ private void addToMapping(String name, int index) {
+
if (name.startsWith("is")) {
this.fieldNameMap.put(calcFieldName( name, 2 ), new Integer(index));
} else {
diff --git a/drools-core/src/main/java/org/drools/util/asm/FieldAccessorGenerator.java b/drools-core/src/main/java/org/drools/util/asm/FieldAccessorGenerator.java
index 515298e54ba..0889a014136 100644
--- a/drools-core/src/main/java/org/drools/util/asm/FieldAccessorGenerator.java
+++ b/drools-core/src/main/java/org/drools/util/asm/FieldAccessorGenerator.java
@@ -112,14 +112,14 @@ public static byte[] generateClass(Method getters[], Class targetClass, String g
doConstructor( cw );
- doMethods( cw, Type.getInternalName(targetClass), getters );
+ doMethods( cw, Type.getInternalName(targetClass), getters, targetClass.isInterface());
cw.visitEnd();
return cw.toByteArray();
}
- private static void doMethods(ClassWriter cw, String targetType, Method[] getters) {
+ private static void doMethods(ClassWriter cw, String targetType, Method[] getters, boolean isInterface) {
@@ -162,12 +162,13 @@ private static void doMethods(ClassWriter cw, String targetType, Method[] getter
//START switch items
for (int i= 0; i < getters.length; i++) {
+
Method method = getters[i];
if (method.getReturnType().isPrimitive()) {
doSwitchItemBoxed( mv, switchItems[i],
- target, targetType, method.getName(), method.getReturnType());
+ target, targetType, method.getName(), method.getReturnType(), isInterface);
} else {
- doSwitchItemObject(mv, switchItems[i], target, targetType, method.getName(), method.getReturnType());
+ doSwitchItemObject(mv, switchItems[i], target, targetType, method.getName(), method.getReturnType(), isInterface);
}
}
@@ -186,7 +187,7 @@ private static void doMethods(ClassWriter cw, String targetType, Method[] getter
/** a switch item that requires autoboxing */
private static void doSwitchItemBoxed(MethodVisitor mv, Label switchItem,
int target, String targetType, String targetMethod,
- Class scalarType) {
+ Class scalarType, boolean isInterface) {
Class boxType = null;
boxType = getBoxType( scalarType );
String scalarDescriptor = Type.getDescriptor(scalarType);
@@ -197,10 +198,19 @@ private static void doSwitchItemBoxed(MethodVisitor mv, Label switchItem,
mv.visitInsn( DUP );
mv.visitVarInsn( ALOAD,
target );
- mv.visitMethodInsn( INVOKEVIRTUAL,
- targetType,
- targetMethod,
- "()" + scalarDescriptor );
+ if (isInterface) {
+ mv.visitMethodInsn( INVOKEINTERFACE,
+ targetType,
+ targetMethod,
+ "()" + scalarDescriptor );
+
+ } else {
+ mv.visitMethodInsn( INVOKEVIRTUAL,
+ targetType,
+ targetMethod,
+ "()" + scalarDescriptor );
+
+ }
mv.visitMethodInsn( INVOKESPECIAL,
internalBoxName,
"<init>",
@@ -237,16 +247,24 @@ private static Class getBoxType(Class scalarType) {
/** A regular switch item, which doesn't require boxing */
private static void doSwitchItemObject(MethodVisitor mv, Label label,
- int target, String targetType, String targetMethod, Class returnClass) {
+ int target, String targetType,
+ String targetMethod, Class returnClass, boolean isInterface) {
String returnType = "()" + Type.getDescriptor(returnClass);
mv.visitLabel( label );
mv.visitVarInsn( ALOAD,
target );
- mv.visitMethodInsn( INVOKEVIRTUAL,
- targetType,
- targetMethod,
- returnType );
+ if (isInterface) {
+ mv.visitMethodInsn( INVOKEINTERFACE,
+ targetType,
+ targetMethod,
+ returnType );
+ } else {
+ mv.visitMethodInsn( INVOKEVIRTUAL,
+ targetType,
+ targetMethod,
+ returnType );
+ }
mv.visitInsn( ARETURN );
}
diff --git a/drools-core/src/test/java/org/drools/base/ClassFieldExtractorFactoryTest.java b/drools-core/src/test/java/org/drools/base/ClassFieldExtractorFactoryTest.java
new file mode 100644
index 00000000000..9317c4b2997
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/base/ClassFieldExtractorFactoryTest.java
@@ -0,0 +1,39 @@
+package org.drools.base;
+
+import org.drools.spi.FieldExtractor;
+import org.drools.util.asm.TestAbstract;
+import org.drools.util.asm.TestAbstractImpl;
+import org.drools.util.asm.TestInterface;
+import org.drools.util.asm.TestInterfaceImpl;
+
+import junit.framework.TestCase;
+
+public class ClassFieldExtractorFactoryTest extends TestCase {
+
+ public void testIt() throws Exception {
+ FieldExtractor ex = ClassFieldExtractorFactory.getClassFieldExtractor( TestBean.class, "name" );
+ assertEquals(0, ex.getIndex());
+ assertEquals("michael", ex.getValue( new TestBean() ));
+ ex = ClassFieldExtractorFactory.getClassFieldExtractor( TestBean.class, "age" );
+ assertEquals(1, ex.getIndex());
+ assertEquals(new Integer(42), ex.getValue( new TestBean() ));
+
+ }
+
+ public void testInterface() throws Exception {
+ FieldExtractor ex = ClassFieldExtractorFactory.getClassFieldExtractor( TestInterface.class, "something" );
+ assertEquals(0, ex.getIndex());
+ assertEquals("foo", ex.getValue( new TestInterfaceImpl() ));
+ }
+
+ public void testAbstract() throws Exception {
+ FieldExtractor ex = ClassFieldExtractorFactory.getClassFieldExtractor( TestAbstract.class, "something" );
+ assertEquals(0, ex.getIndex());
+ assertEquals("foo", ex.getValue( new TestAbstractImpl() ));
+ }
+
+
+
+
+}
+
diff --git a/drools-core/src/test/java/org/drools/base/TestBean.java b/drools-core/src/test/java/org/drools/base/TestBean.java
new file mode 100644
index 00000000000..2c1bf9dc406
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/base/TestBean.java
@@ -0,0 +1,14 @@
+package org.drools.base;
+
+public class TestBean {
+ private String name = "michael";
+ private int age = 42;
+
+ public String getName() {
+ return name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+}
diff --git a/drools-core/src/test/java/org/drools/util/asm/ClassFieldInspectorTest.java b/drools-core/src/test/java/org/drools/util/asm/ClassFieldInspectorTest.java
index adb768215a8..c7de4fe3fd9 100644
--- a/drools-core/src/test/java/org/drools/util/asm/ClassFieldInspectorTest.java
+++ b/drools-core/src/test/java/org/drools/util/asm/ClassFieldInspectorTest.java
@@ -23,6 +23,37 @@ public void testIt() throws Exception {
}
+
+ public void testInterface() throws Exception {
+ ClassFieldInspector ext = new ClassFieldInspector( TestInterface.class );
+ assertEquals(2, ext.getPropertyGetters().size());
+ assertEquals("getSomething", ((Method) ext.getPropertyGetters().get(0)).getName());
+ assertEquals("getAnother", ((Method) ext.getPropertyGetters().get(1)).getName());
+
+
+
+ Map names = ext.getFieldNames();
+ assertNotNull(names);
+ assertEquals(2, names.size());
+ assertEquals(0, ((Integer)names.get("something")).intValue());
+ assertEquals(1, ((Integer)names.get("another")).intValue());
+
+ }
+
+ public void testAbstract() throws Exception {
+ ClassFieldInspector ext = new ClassFieldInspector( TestAbstract.class );
+ assertEquals(2, ext.getPropertyGetters().size());
+ assertEquals("getSomething", ((Method) ext.getPropertyGetters().get(0)).getName());
+ assertEquals("getAnother", ((Method) ext.getPropertyGetters().get(1)).getName());
+
+ Map names = ext.getFieldNames();
+ assertNotNull(names);
+ assertEquals(2, names.size());
+ assertEquals(0, ((Integer)names.get("something")).intValue());
+ assertEquals(1, ((Integer)names.get("another")).intValue());
+
+ }
+
static class Person {
private boolean happy;
private String name;
diff --git a/drools-core/src/test/java/org/drools/util/asm/FieldAccessorGeneratorTest.java b/drools-core/src/test/java/org/drools/util/asm/FieldAccessorGeneratorTest.java
index 1d780e0c702..442fea486b7 100644
--- a/drools-core/src/test/java/org/drools/util/asm/FieldAccessorGeneratorTest.java
+++ b/drools-core/src/test/java/org/drools/util/asm/FieldAccessorGeneratorTest.java
@@ -46,4 +46,45 @@ public void testAnother() throws Exception {
assertEquals(ac, ac2);
}
+ public void testInterface() throws Exception {
+ FieldAccessorGenerator gen = FieldAccessorGenerator.getInstance();
+ FieldAccessorMap map = gen.newInstanceFor(TestInterface.class);
+ FieldAccessor ac = map.getFieldAccessor();
+ assertNotNull(ac);
+
+ TestInterface obj = new TestInterfaceImpl();
+
+ assertEquals("foo", (String)ac.getFieldByIndex(obj, 0));
+ assertEquals(42, ((Integer)ac.getFieldByIndex(obj, 1)).intValue());
+
+ Integer index = (Integer) map.getFieldNameMap().get("something");
+ assertEquals(0, index.intValue());
+
+ index = (Integer) map.getFieldNameMap().get("another");
+ assertEquals(1, index.intValue());
+
+
+ }
+
+ public void testAbstract() throws Exception {
+ FieldAccessorGenerator gen = FieldAccessorGenerator.getInstance();
+ FieldAccessorMap map = gen.newInstanceFor(TestAbstract.class);
+ FieldAccessor ac = map.getFieldAccessor();
+ assertNotNull(ac);
+
+ TestAbstract obj = new TestAbstractImpl();
+
+ assertEquals(42, ((Integer)ac.getFieldByIndex(obj, 1)).intValue());
+ assertEquals("foo", (String)ac.getFieldByIndex(obj, 0));
+
+
+ Integer index = (Integer) map.getFieldNameMap().get("something");
+ assertEquals(0, index.intValue());
+
+ index = (Integer) map.getFieldNameMap().get("another");
+ assertEquals(1, index.intValue());
+
+
+ }
+
}
diff --git a/drools-core/src/test/java/org/drools/util/asm/TestAbstract.java b/drools-core/src/test/java/org/drools/util/asm/TestAbstract.java
new file mode 100644
index 00000000000..a603dacc1bc
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/util/asm/TestAbstract.java
@@ -0,0 +1,10 @@
+package org.drools.util.asm;
+
+public abstract class TestAbstract {
+
+ public abstract String getSomething();
+ public int getAnother() {
+ return 42;
+ }
+
+}
diff --git a/drools-core/src/test/java/org/drools/util/asm/TestAbstractImpl.java b/drools-core/src/test/java/org/drools/util/asm/TestAbstractImpl.java
new file mode 100644
index 00000000000..2dad1e6f570
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/util/asm/TestAbstractImpl.java
@@ -0,0 +1,9 @@
+package org.drools.util.asm;
+
+public class TestAbstractImpl extends TestAbstract {
+
+ public String getSomething() {
+ return "foo";
+ }
+
+}
diff --git a/drools-core/src/test/java/org/drools/util/asm/TestInterface.java b/drools-core/src/test/java/org/drools/util/asm/TestInterface.java
new file mode 100644
index 00000000000..c61d2fbd7a7
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/util/asm/TestInterface.java
@@ -0,0 +1,8 @@
+package org.drools.util.asm;
+
+public interface TestInterface {
+
+ public String getSomething();
+ public int getAnother();
+
+}
diff --git a/drools-core/src/test/java/org/drools/util/asm/TestInterfaceImpl.java b/drools-core/src/test/java/org/drools/util/asm/TestInterfaceImpl.java
new file mode 100644
index 00000000000..58fa21c4381
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/util/asm/TestInterfaceImpl.java
@@ -0,0 +1,15 @@
+package org.drools.util.asm;
+
+public class TestInterfaceImpl
+ implements
+ TestInterface {
+
+ public String getSomething() {
+ return "foo";
+ }
+
+ public int getAnother() {
+ return 42;
+ }
+
+}
|
73b54f4efe43dbe674621ba81c7ab7e04e1157c8
|
spring-framework
|
SPR-6466 - ContentNegotiatingViewResolver can not- handle View implementations returning null as content type--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
index 1ffbb93e744e..0ad603a851a3 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
@@ -350,12 +350,15 @@ public View resolveViewName(String viewName, Locale locale) throws Exception {
}
for (View candidateView : candidateViews) {
- MediaType viewMediaType = MediaType.parseMediaType(candidateView.getContentType());
- for (MediaType requestedMediaType : requestedMediaTypes) {
- if (requestedMediaType.includes(viewMediaType)) {
- if (!views.containsKey(requestedMediaType)) {
- views.put(requestedMediaType, candidateView);
- break;
+ String contentType = candidateView.getContentType();
+ if (StringUtils.hasText(contentType)) {
+ MediaType viewMediaType = MediaType.parseMediaType(contentType);
+ for (MediaType requestedMediaType : requestedMediaTypes) {
+ if (requestedMediaType.includes(viewMediaType)) {
+ if (!views.containsKey(requestedMediaType)) {
+ views.put(requestedMediaType, candidateView);
+ break;
+ }
}
}
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java
index 8c1ce84dd003..49d4a1869da4 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java
@@ -280,4 +280,29 @@ public void resolveViewNameFilenameDefaultView() throws Exception {
verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3);
}
+ @Test
+ public void resolveViewContentTypeNull() throws Exception {
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
+ request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
+
+ ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+
+ View viewMock = createMock("application_xml", View.class);
+
+ String viewName = "view";
+ Locale locale = Locale.ENGLISH;
+
+ expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
+ expect(viewMock.getContentType()).andReturn(null);
+
+ replay(viewResolverMock, viewMock);
+
+ View result = viewResolver.resolveViewName(viewName, locale);
+ assertNull("Invalid view", result);
+
+ verify(viewResolverMock, viewMock);
+ }
+
}
|
6383157b2961749ab46b8d05653ffb5f757f0be8
|
ReactiveX-RxJava
|
Remove Unnecessary Subscription--- be explicit for error case in JoinObserver-
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/joins/JoinObserver1.java b/rxjava-core/src/main/java/rx/joins/JoinObserver1.java
index 873d3d1a7f..ede55f0584 100644
--- a/rxjava-core/src/main/java/rx/joins/JoinObserver1.java
+++ b/rxjava-core/src/main/java/rx/joins/JoinObserver1.java
@@ -19,9 +19,11 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
+import java.util.concurrent.atomic.AtomicBoolean;
+
import rx.Notification;
import rx.Observable;
-import rx.subscriptions.SingleAssignmentSubscription;
+import rx.operators.SafeObservableSubscription;
import rx.util.functions.Action1;
/**
@@ -33,14 +35,15 @@ public final class JoinObserver1<T> extends ObserverBase<Notification<T>> implem
private final Action1<Throwable> onError;
private final List<ActivePlan0> activePlans;
private final Queue<Notification<T>> queue;
- private final SingleAssignmentSubscription subscription;
+ private final SafeObservableSubscription subscription;
private volatile boolean done;
+ private final AtomicBoolean subscribed = new AtomicBoolean(false);
public JoinObserver1(Observable<T> source, Action1<Throwable> onError) {
this.source = source;
this.onError = onError;
queue = new LinkedList<Notification<T>>();
- subscription = new SingleAssignmentSubscription();
+ subscription = new SafeObservableSubscription();
activePlans = new ArrayList<ActivePlan0>();
}
public Queue<Notification<T>> queue() {
@@ -51,8 +54,12 @@ public void addActivePlan(ActivePlan0 activePlan) {
}
@Override
public void subscribe(Object gate) {
- this.gate = gate;
- subscription.set(source.materialize().subscribe(this));
+ if (subscribed.compareAndSet(false, true)) {
+ this.gate = gate;
+ subscription.wrap(source.materialize().subscribe(this));
+ } else {
+ throw new IllegalStateException("Can only be subscribed to once.");
+ }
}
@Override
diff --git a/rxjava-core/src/main/java/rx/subscriptions/SingleAssignmentSubscription.java b/rxjava-core/src/main/java/rx/subscriptions/SingleAssignmentSubscription.java
deleted file mode 100644
index c960db2ea4..0000000000
--- a/rxjava-core/src/main/java/rx/subscriptions/SingleAssignmentSubscription.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * 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.subscriptions;
-
-import java.util.concurrent.atomic.AtomicReference;
-import rx.Subscription;
-
-/**
- * A subscription that allows only a single resource to be assigned.
- * <p>
- * If this subscription is live, no other subscription may be set() and
- * yields an {@link IllegalStateException}.
- * <p>
- * If the unsubscribe has been called, setting a new subscription will
- * unsubscribe it immediately.
- */
-public final class SingleAssignmentSubscription implements Subscription {
- /** Holds the current resource. */
- private final AtomicReference<Subscription> current = new AtomicReference<Subscription>();
- /** Sentinel for the unsubscribed state. */
- private static final Subscription UNSUBSCRIBED_SENTINEL = new Subscription() {
- @Override
- public void unsubscribe() {
- }
- };
- /**
- * Returns the current subscription or null if not yet set.
- */
- public Subscription get() {
- Subscription s = current.get();
- if (s == UNSUBSCRIBED_SENTINEL) {
- return Subscriptions.empty();
- }
- return s;
- }
- /**
- * Sets a new subscription if not already set.
- * @param s the new subscription
- * @throws IllegalStateException if this subscription is live and contains
- * another subscription.
- */
- public void set(Subscription s) {
- if (current.compareAndSet(null, s)) {
- return;
- }
- if (current.get() != UNSUBSCRIBED_SENTINEL) {
- throw new IllegalStateException("Subscription already set");
- }
- if (s != null) {
- s.unsubscribe();
- }
- }
- @Override
- public void unsubscribe() {
- Subscription old = current.getAndSet(UNSUBSCRIBED_SENTINEL);
- if (old != null) {
- old.unsubscribe();
- }
- }
- /**
- * Test if this subscription is already unsubscribed.
- */
- public boolean isUnsubscribed() {
- return current.get() == UNSUBSCRIBED_SENTINEL;
- }
-
-}
|
a86f9ca85ffb3ce38a6abf2427df4b6a92360d70
|
frontlinesms-credit$plugin-paymentview
|
Working on the BaseClientDialog and BaseClientTable for stability. Changes to PaymentService Interface; addition and Separation from PaymentServiceAccount. Almost done with settings tab
|
p
|
https://github.com/frontlinesms-credit/plugin-paymentview
|
diff --git a/src/main/java/net/frontlinesms/payment/PaymentService.java b/src/main/java/net/frontlinesms/payment/PaymentService.java
index 15f61471..d20a66e3 100644
--- a/src/main/java/net/frontlinesms/payment/PaymentService.java
+++ b/src/main/java/net/frontlinesms/payment/PaymentService.java
@@ -1,31 +1,26 @@
-package net.frontlinesms.payment;
-
-import java.math.BigDecimal;
-
-import net.frontlinesms.events.EventObserver;
-import net.frontlinesms.messaging.sms.SmsService;
-
-import org.creditsms.plugins.paymentview.data.domain.Account;
-import org.creditsms.plugins.paymentview.data.repository.AccountDao;
-import org.creditsms.plugins.paymentview.data.repository.ClientDao;
-import org.creditsms.plugins.paymentview.data.repository.IncomingPaymentDao;
-import org.smslib.CService;
-
-public interface PaymentService extends EventObserver{
- //Untill We Decide How to Structure this..
- void setCService(CService cService);
- CService getCService();
-
- void setSmsService(SmsService smsService);
- SmsService getSmsService();
-
- void setPin(String pin);
-
- void setClientDao(ClientDao clientDao);
- void setIncomingPaymentDao(IncomingPaymentDao incomingPaymentDao);
- void setAccountDao(AccountDao accountDao);
-
-//> The Basic Methods
- void makePayment(Account account, BigDecimal amount) throws PaymentServiceException;
- void checkBalance() throws PaymentServiceException;
-}
+package net.frontlinesms.payment;
+
+import java.math.BigDecimal;
+
+import net.frontlinesms.messaging.sms.SmsService;
+
+import org.creditsms.plugins.paymentview.data.domain.Account;
+import org.creditsms.plugins.paymentview.data.repository.AccountDao;
+import org.creditsms.plugins.paymentview.data.repository.ClientDao;
+import org.creditsms.plugins.paymentview.data.repository.IncomingPaymentDao;
+import org.smslib.CService;
+
+public interface PaymentService {
+ void setCService(CService cService);
+ CService getCService();
+
+ void setSmsService(SmsService smsService);
+ SmsService getSmsService();
+
+ void setClientDao(ClientDao clientDao);
+ void setIncomingPaymentDao(IncomingPaymentDao incomingPaymentDao);
+ void setAccountDao(AccountDao accountDao);
+
+ void makePayment(Account account, BigDecimal amount) throws PaymentServiceException;
+ void checkBalance() throws PaymentServiceException;
+}
diff --git a/src/main/java/net/frontlinesms/payment/PaymentServiceAccount.java b/src/main/java/net/frontlinesms/payment/PaymentServiceAccount.java
new file mode 100644
index 00000000..bb5b367a
--- /dev/null
+++ b/src/main/java/net/frontlinesms/payment/PaymentServiceAccount.java
@@ -0,0 +1,30 @@
+package net.frontlinesms.payment;
+
+import net.frontlinesms.events.EventObserver;
+
+public interface PaymentServiceAccount extends EventObserver, PaymentService{
+ public enum PaymentAccountType{
+ PAYBILL("Paybill"),
+ PERSONAL("Personal");
+
+ private final String type;
+
+ PaymentAccountType(String type){ this.type = type; }
+ public String getType() { return this.type; }
+ }
+
+ String getName();
+ void setName(String name);
+
+ String getOperator();
+ void setOperator(String operator);
+
+ String getPin();
+ void setPin(String pin);
+
+ String getGeography();
+ void setGeography(String geography);
+
+ PaymentAccountType getPaymentAccountType();
+ void setPaymentAccountType(PaymentAccountType paymentAccountType);
+}
\ No newline at end of file
diff --git a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPayBillService.java b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPayBillService.java
index a64e3763..d2e5f67e 100644
--- a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPayBillService.java
+++ b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPayBillService.java
@@ -16,6 +16,14 @@ public class MpesaPayBillService extends MpesaPaymentService {
+ "New Utility balance is Ksh[,|\\d]+\n"
+ "Time: ([0-2]\\d|[3][0-1])/(0[1-9]|1[0-2])/(20[1][1-2]) (([2][0-3]|[0-1]\\d):([0-5]\\d):([0-5]\\d))";
+
+ public MpesaPayBillService(){
+ this.setPaymentAccountType(PaymentAccountType.PAYBILL);
+ this.setGeography("Kenya");
+ this.setOperator("Safaricom");
+ this.setName("M-Pesa");
+ }
+
@Override
Account getAccount(FrontlineMessage message) {
String accNumber = getFirstMatch(message, ACCOUNT_NUMBER_PATTERN);
@@ -61,8 +69,4 @@ boolean isMessageTextValid(String messageText) {
return true;
}
}
-
- public String toString(){
- return "MPesa Safaricom - Kenya: PayBill Service";
- }
}
diff --git a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java
index 21d4781e..d87ea624 100644
--- a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java
+++ b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java
@@ -11,7 +11,7 @@
import net.frontlinesms.events.FrontlineEventNotification;
import net.frontlinesms.messaging.sms.SmsService;
import net.frontlinesms.messaging.sms.modem.SmsModem;
-import net.frontlinesms.payment.PaymentService;
+import net.frontlinesms.payment.PaymentServiceAccount;
import net.frontlinesms.payment.PaymentServiceException;
import net.frontlinesms.ui.events.FrontlineUiUpateJob;
@@ -28,8 +28,8 @@
import org.smslib.stk.StkRequest;
import org.smslib.stk.StkResponse;
-public abstract class MpesaPaymentService implements PaymentService {
- // > CONSTANTS
+public abstract class MpesaPaymentService implements PaymentServiceAccount {
+//> REGEX PATTERN CONSTANTS
protected static final String AMOUNT_PATTERN = "Ksh[,|\\d]+";
protected static final String DATETIME_PATTERN = "d/M/yy hh:mm a";
protected static final String PHONE_PATTERN = "2547[\\d]{8}";
@@ -38,51 +38,24 @@ public abstract class MpesaPaymentService implements PaymentService {
protected static final String ACCOUNT_NUMBER_PATTERN = "Account Number [\\d]+";
protected static final String RECEIVED_FROM = "received from";
- // > INSTANCE PROPERTIES
+//> INSTANCE PROPERTIES
private final Logger log = FrontlineUtils.getLogger(this.getClass());
private SmsService smsService;
private CService cService;
- private String pin;
+//> DAOs
AccountDao accountDao;
ClientDao clientDao;
IncomingPaymentDao incomingPaymentDao;
-
- public void setSmsService(SmsService smsService) {
- this.smsService = smsService;
- }
-
- public SmsService getSmsService(){
- return smsService;
- }
- public void setCService(CService cService) {
- this.cService = cService;
- }
-
- public CService getCService(){
- if (smsService != null & smsService instanceof SmsModem && cService == null){
- return ((SmsModem)smsService).getCService();
- }
- return cService;
- }
+//> FIELDS
+ private String pin;
+ private PaymentAccountType paymentAccountType;
+ private String geography;
+ private String operator;
+ private String name;
- public void setPin(String pin) {
- this.pin = pin;
- }
-
- public void setAccountDao(AccountDao accountDao) {
- this.accountDao = accountDao;
- }
-
- public void setIncomingPaymentDao(IncomingPaymentDao incomingPaymentDao) {
- this.incomingPaymentDao = incomingPaymentDao;
- }
-
- public void setClientDao(ClientDao clientDao) {
- this.clientDao = clientDao;
- }
-
+//> STK & PAYMENT ACCOUNT
public void checkBalance() throws PaymentServiceException {
try {
StkMenu mPesaMenu = getMpesaMenu();
@@ -93,8 +66,8 @@ public void checkBalance() throws PaymentServiceException {
assert getBalanceResponse instanceof StkInputRequiremnent;
StkInputRequiremnent pinRequired = (StkInputRequiremnent) getBalanceResponse;
assert pinRequired.getText().contains("Enter PIN");
- StkResponse finalResponse = cService.stkRequest(
- pinRequired.getRequest(), this.pin);
+ //StkResponse finalResponse = cService.stkRequest(
+ //pinRequired.getRequest(), this.pin);
// TODO check finalResponse is OK
// TODO wait for response...
} catch (SMSLibDeviceException ex) {
@@ -131,25 +104,34 @@ public void makePayment(Account account, BigDecimal amount)
throw new PaymentServiceException(ex);
}
}
-
- @SuppressWarnings("unchecked")
+
+//> EVENTBUS NOTIFY
+ @SuppressWarnings("rawtypes")
public void notify(FrontlineEventNotification notification) {
+ //If the notification is of Importance to us
if (!(notification instanceof EntitySavedNotification)) {
return;
}
-
+
+ //And is of a saved message
Object entity = ((EntitySavedNotification) notification)
.getDatabaseEntity();
if (!(entity instanceof FrontlineMessage)) {
return;
}
-
final FrontlineMessage message = (FrontlineMessage) entity;
+ //Verify that its from MPESA and is of valid pattern
if (!messageIsValid(message)) {
return;
}
+
+ //Then process the payment
+ processPayment(message);
+ }
+//> INCOMING MESSAGE PAYMENT PROCESSORS
+ private void processPayment(final FrontlineMessage message) {
new FrontlineUiUpateJob() {
// This probably shouldn't be a UI job,
// but it certainly should be done on a separate thread!
@@ -173,7 +155,6 @@ public void run() {
}
}
}.execute();
-
}
private boolean messageIsValid(FrontlineMessage message) {
@@ -183,12 +164,10 @@ private boolean messageIsValid(FrontlineMessage message) {
return isMessageTextValid(message.getTextContent());
}
+
abstract Date getTimePaid(FrontlineMessage message);
-
abstract boolean isMessageTextValid(String messageText);
-
abstract Account getAccount(FrontlineMessage message);
-
abstract String getPaymentBy(FrontlineMessage message);
private BigDecimal getAmount(FrontlineMessage message) {
@@ -216,12 +195,15 @@ protected String getFirstMatch(FrontlineMessage message, String regexMatcher) {
}
public String toString(){
- return "MPesa Safaricom - Kenya: Abstract Payment Service";
+ return this.getName() + " " +
+ this.getOperator()+ " - " +
+ this.getGeography() + ":" +
+ this.getPaymentAccountType().getType() + " Service";
}
@Override
public boolean equals(Object other) {
- if (!(other instanceof PaymentService)){
+ if (!(other instanceof PaymentServiceAccount)){
return false;
}
@@ -238,4 +220,77 @@ public boolean equals(Object other) {
return super.equals(other);
}
+
+//> ACCESSORS AND MUTATORS
+ public void setSmsService(SmsService smsService) {
+ this.smsService = smsService;
+ }
+
+ public SmsService getSmsService(){
+ return smsService;
+ }
+
+ public void setCService(CService cService) {
+ this.cService = cService;
+ }
+
+ public CService getCService(){
+ if (smsService != null & smsService instanceof SmsModem && cService == null){
+ return ((SmsModem)smsService).getCService();
+ }
+ return cService;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getOperator() {
+ return operator;
+ }
+
+ public void setOperator(String operator) {
+ this.operator = operator;
+ }
+
+ public String getPin() {
+ return pin;
+ }
+
+ public String getGeography() {
+ return geography;
+ }
+
+ public void setGeography(String geography) {
+ this.geography = geography;
+ }
+
+ public PaymentAccountType getPaymentAccountType() {
+ return paymentAccountType;
+ }
+
+ public void setPaymentAccountType(PaymentAccountType paymentAccountType) {
+ this.paymentAccountType = paymentAccountType;
+ }
+
+ public void setPin(String pin) {
+ this.pin = pin;
+ }
+
+ public void setAccountDao(AccountDao accountDao) {
+ this.accountDao = accountDao;
+ }
+
+ public void setIncomingPaymentDao(IncomingPaymentDao incomingPaymentDao) {
+ this.incomingPaymentDao = incomingPaymentDao;
+ }
+
+ public void setClientDao(ClientDao clientDao) {
+ this.clientDao = clientDao;
+ }
+
}
\ No newline at end of file
diff --git a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java
index 9ff5c236..cfd6842c 100644
--- a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java
+++ b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java
@@ -17,6 +17,13 @@ public class MpesaPersonalService extends MpesaPaymentService {
"(([1-2]?[1-9]|3[0-1])/([1-9]|1[0-2])/(1[1-2]))\\s(at)\\s([1]?\\d:[0-5]\\d)\\s(AM|PM)" +
"\nNew M-PESA balance Ksh[,|[0-9]]+";
+ public MpesaPersonalService(){
+ this.setPaymentAccountType(PaymentAccountType.PERSONAL);
+ this.setGeography("Kenya");
+ this.setOperator("Safaricom");
+ this.setName("M-Pesa");
+ }
+
@Override
Account getAccount(FrontlineMessage message) {
Client client = clientDao.getClientByPhoneNumber(getPhoneNumber(message));
@@ -58,8 +65,4 @@ Date getTimePaid(FrontlineMessage message) {
boolean isMessageTextValid(String messageText) {
return messageText.matches(PERSONAL_REGEX_PATTERN);
}
-
- public String toString(){
- return "MPesa Safaricom - Kenya: Personal Service";
- }
}
diff --git a/src/main/java/net/frontlinesms/payment/safaricom/ui/SafaricomPaymentServiceConfigUiHandler.java b/src/main/java/net/frontlinesms/payment/safaricom/ui/SafaricomPaymentServiceConfigUiHandler.java
index a1d48b7b..d27c75a9 100644
--- a/src/main/java/net/frontlinesms/payment/safaricom/ui/SafaricomPaymentServiceConfigUiHandler.java
+++ b/src/main/java/net/frontlinesms/payment/safaricom/ui/SafaricomPaymentServiceConfigUiHandler.java
@@ -11,7 +11,6 @@
import org.creditsms.plugins.paymentview.data.repository.ClientDao;
import org.creditsms.plugins.paymentview.data.repository.IncomingPaymentDao;
import org.creditsms.plugins.paymentview.ui.handler.BaseDialog;
-import org.smslib.CService;
public class SafaricomPaymentServiceConfigUiHandler extends BaseDialog {
private static final String DIALOG_XML_FILE = "/ui/plugins/paymentview/services/safaricom/dgConfig.xml";
diff --git a/src/main/java/org/creditsms/plugins/paymentview/data/domain/CustomField.java b/src/main/java/org/creditsms/plugins/paymentview/data/domain/CustomField.java
index b2327e3e..4b225f6e 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/data/domain/CustomField.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/data/domain/CustomField.java
@@ -13,7 +13,7 @@
import net.frontlinesms.data.EntityField;
-import org.creditsms.plugins.paymentview.utils.StringUtil;
+import org.creditsms.plugins.paymentview.utils.PaymentViewUtils;
/**
* @Author Roy
@@ -98,7 +98,7 @@ public void setReadableName(String strName) {
}
public String getCamelCaseName() {
- return StringUtil.toCamelCase(this.readableName);
+ return PaymentViewUtils.toCamelCase(this.readableName);
}
public void setUsed(boolean used) {
diff --git a/src/main/java/org/creditsms/plugins/paymentview/data/importexport/PaymentViewCsvExporter.java b/src/main/java/org/creditsms/plugins/paymentview/data/importexport/PaymentViewCsvExporter.java
index a5b1852d..2da7b9f3 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/data/importexport/PaymentViewCsvExporter.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/data/importexport/PaymentViewCsvExporter.java
@@ -32,7 +32,6 @@
import org.creditsms.plugins.paymentview.data.repository.CustomFieldDao;
import org.creditsms.plugins.paymentview.data.repository.CustomValueDao;
import org.creditsms.plugins.paymentview.utils.PaymentViewUtils;
-import org.creditsms.plugins.paymentview.utils.StringUtil;
public class PaymentViewCsvExporter extends net.frontlinesms.csv.CsvExporter {
/**
@@ -70,7 +69,7 @@ public static void exportClients(File exportFile,
items.add(InternationalisationUtils.getI18nString(COMMON_ACCOUNTS));
for (CustomField cf : usedCustomFields) {
- items.add(StringUtil.getMarkerFromString(cf.getReadableName()));
+ items.add(PaymentViewUtils.getMarkerFromString(cf.getReadableName()));
items.add(cf.getReadableName());
}
String[] str = new String[items.size()];
@@ -101,13 +100,13 @@ public static void exportClients(File exportFile,
curr = cfi.next();
for (CustomValue cv : allCustomValues) {
if (cv.getCustomField().equals(curr)) {
- items.add(StringUtil.getMarkerFromString(curr.getReadableName()));
+ items.add(PaymentViewUtils.getMarkerFromString(curr.getReadableName()));
items.add(cv.getStrValue());
markerReplaced = true;
}
}
if (!markerReplaced) {
- items.add(StringUtil.getMarkerFromString(curr.getReadableName()));
+ items.add(PaymentViewUtils.getMarkerFromString(curr.getReadableName()));
items.add("");
}
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/PaymentViewThinletTabController.java b/src/main/java/org/creditsms/plugins/paymentview/ui/PaymentViewThinletTabController.java
index 9e42eb67..e0f7dbf1 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/PaymentViewThinletTabController.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/PaymentViewThinletTabController.java
@@ -4,6 +4,7 @@
*/
package org.creditsms.plugins.paymentview.ui;
+import net.frontlinesms.BuildProperties;
import net.frontlinesms.plugins.BasePluginThinletTabController;
import net.frontlinesms.ui.ThinletUiEventHandler;
import net.frontlinesms.ui.UiGeneratorController;
@@ -12,7 +13,6 @@
import org.creditsms.plugins.paymentview.ui.handler.IncomingPaymentsTabHandler;
import org.creditsms.plugins.paymentview.ui.handler.tabanalytics.AnalyticsTabHandler;
import org.creditsms.plugins.paymentview.ui.handler.tabclients.ClientsTabHandler;
-import org.creditsms.plugins.paymentview.ui.handler.tabexport.ExportTabHandler;
import org.creditsms.plugins.paymentview.ui.handler.taboutgoingpayments.OutgoingPaymentsTabHandler;
import org.creditsms.plugins.paymentview.ui.handler.tabsettings.SettingsTabHandler;
@@ -32,7 +32,6 @@ public class PaymentViewThinletTabController extends
private OutgoingPaymentsTabHandler outgoingPayTab;
private IncomingPaymentsTabHandler incomingPayTab;
private ClientsTabHandler clientsTab;
- private ExportTabHandler exportTab;
private AnalyticsTabHandler analyticsTab;
private Object mainPane;
@@ -70,9 +69,12 @@ public void initTabs() {
outgoingPayTab.refresh();
ui.add(mainPane, outgoingPayTab.getTab());
- exportTab = new ExportTabHandler(ui, getPluginController());
- exportTab.refresh();
- ui.add(mainPane, exportTab.getTab());
+ /** UNCOMMENT FOR VERSION 0.1.3
+ * exportTab = new ExportTabHandler(ui, getPluginController());
+ * exportTab.refresh();
+ * ui.add(mainPane, exportTab.getTab());
+ *
+ */
analyticsTab = new AnalyticsTabHandler(ui, getPluginController());
analyticsTab.refresh();
@@ -82,9 +84,12 @@ public void initTabs() {
settingsTab.refresh();
ui.add(mainPane, settingsTab.getTab());
- cdtController = new PvDebugTabController(ui);
- cdtController.setMessageDao(ui.getFrontlineController().getMessageDao());
- ui.add(mainPane, cdtController.getTab());
+ //For Tests Only
+ if(BuildProperties.getInstance().isSnapshot() && getPluginController().getClientDao().getClientCount()==0) {
+ cdtController = new PvDebugTabController(ui);
+ cdtController.setMessageDao(ui.getFrontlineController().getMessageDao());
+ ui.add(mainPane, cdtController.getTab());
+ }
}
/**
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java
index 9f544058..622f88ca 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java
@@ -30,7 +30,7 @@ public abstract class BaseClientTable implements PagedComponentItemProvider,
protected CustomFieldDao customFieldDao;
protected CustomValueDao customValueDao;
protected Object tableClientsPanel;
- protected List<Client> selectedUsers;
+ protected List<Client> clients;
public BaseClientTable(UiGeneratorController ui, PaymentViewPluginController pluginController) {
this.ui = ui;
@@ -38,7 +38,7 @@ public BaseClientTable(UiGeneratorController ui, PaymentViewPluginController plu
this.customFieldDao = pluginController.getCustomFieldDao();
this.customValueDao = pluginController.getCustomValueDao();
- this.selectedUsers = new ArrayList<Client>();
+ this.clients = new ArrayList<Client>();
this.init();
}
@@ -72,7 +72,7 @@ protected PagedListDetails getClientListDetails(int startIndex, int limit) {
}
protected List<Client> getClients(String filter, int startIndex, int limit) {
- if (selectedUsers.isEmpty()){
+ if (clients.isEmpty()){
if (!filter.trim().isEmpty()) {
return this.clientDao.getClientsByName(filter, startIndex, limit);
}else{
@@ -80,9 +80,9 @@ protected List<Client> getClients(String filter, int startIndex, int limit) {
}
}else{
if (filter.trim().isEmpty()) {
- return selectedUsers.subList(startIndex, startIndex);
+ return clients.subList(startIndex, startIndex);
}else{
- List<Client> subList = selectedUsers.subList(startIndex, startIndex);
+ List<Client> subList = clients.subList(startIndex, startIndex);
List<Client> copy = new ArrayList<Client>();
for (Client c : subList) {
if (c.getName().equalsIgnoreCase(filter)) {
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseDialog.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseDialog.java
index 53b6979b..366de18a 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseDialog.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseDialog.java
@@ -12,6 +12,9 @@ public BaseDialog(UiGeneratorController ui) {
this.ui = ui;
}
+ protected void refresh() {
+ }
+
/**
* @return the customizeClientDialog
*/
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseSelectClientTableHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseSelectClientTableHandler.java
index ca2d048a..91fe6eac 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseSelectClientTableHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseSelectClientTableHandler.java
@@ -1,5 +1,6 @@
package org.creditsms.plugins.paymentview.ui.handler;
+import java.util.ArrayList;
import java.util.List;
import net.frontlinesms.ui.UiGeneratorController;
@@ -14,8 +15,11 @@ public abstract class BaseSelectClientTableHandler extends BaseClientTable {
protected static final String ICONS_CHECKBOX_SELECTED_PNG = "/icons/checkbox-selected.png";
protected static final String ICONS_CHECKBOX_UNSELECTED_PNG = "/icons/checkbox-unselected.png";
+ protected List<Client> selectedClients;
+
public BaseSelectClientTableHandler(UiGeneratorController ui, PaymentViewPluginController pluginController) {
super(ui, pluginController);
+ selectedClients = new ArrayList<Client>();
}
@Override
@@ -119,11 +123,11 @@ public void selectUsers(Object tbl_clients) {
Client attachedClient = (Client) ui.getAttachedObject(row);
if (attachedClient.isSelected()) {
attachedClient.setSelected(false);
- selectedUsers.remove(attachedClient);
+ selectedClients.remove(attachedClient);
markCell(cell, false);
} else {
attachedClient.setSelected(true);
- selectedUsers.add(attachedClient);
+ selectedClients.add(attachedClient);
markCell(cell, true);
}
@@ -131,7 +135,7 @@ public void selectUsers(Object tbl_clients) {
}
public List<Client> getSelectedUsers() {
- return this.selectedUsers;
+ return this.selectedClients;
}
}
\ No newline at end of file
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/IncomingPaymentsTabHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/IncomingPaymentsTabHandler.java
index f9f8ee15..d36f5a1b 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/IncomingPaymentsTabHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/IncomingPaymentsTabHandler.java
@@ -135,16 +135,15 @@ public void updateIncomingPaymentsList() {
this.incomingPaymentsTablePager.refresh();
}
//> INCOMING PAYMENT NOTIFICATION...
+ @SuppressWarnings("rawtypes")
public void notify(FrontlineEventNotification notification) {
if (!(notification instanceof EntitySavedNotification)) {
return;
}
Object entity = ((EntitySavedNotification) notification).getDatabaseEntity();
- if (!(entity instanceof IncomingPayment)) {
- return;
+ if (entity instanceof IncomingPayment) {
+ this.refresh();
}
- final IncomingPayment incomingPayment = (IncomingPayment) entity;
- this.refresh();
}
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientExportHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientExportHandler.java
index c0f7f212..ccd72f5a 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientExportHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientExportHandler.java
@@ -17,7 +17,7 @@
import org.creditsms.plugins.paymentview.data.repository.ClientDao;
import org.creditsms.plugins.paymentview.data.repository.CustomFieldDao;
import org.creditsms.plugins.paymentview.data.repository.CustomValueDao;
-import org.creditsms.plugins.paymentview.utils.StringUtil;
+import org.creditsms.plugins.paymentview.utils.PaymentViewUtils;
public class ClientExportHandler extends ExportDialogHandler<Client> {
private static final String COMPONENT_ACCOUNTS = "cbAccounts";
@@ -112,7 +112,7 @@ protected CsvRowFormat getRowFormatForClient() {
COMPONENT_ACCOUNTS);
for(CustomField cf : customFieldDao.getAllActiveUsedCustomFields()){
- addMarker(rowFormat, StringUtil.getMarkerFromString(cf.getReadableName()),
+ addMarker(rowFormat, PaymentViewUtils.getMarkerFromString(cf.getReadableName()),
cf.getCamelCaseName());
}
return rowFormat;
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientImportHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientImportHandler.java
index 99cd4372..dd88074f 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientImportHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/importexport/ClientImportHandler.java
@@ -20,7 +20,7 @@
import org.creditsms.plugins.paymentview.data.repository.CustomValueDao;
import org.creditsms.plugins.paymentview.ui.handler.tabclients.ClientsTabHandler;
import org.creditsms.plugins.paymentview.utils.PaymentPluginConstants;
-import org.creditsms.plugins.paymentview.utils.StringUtil;
+import org.creditsms.plugins.paymentview.utils.PaymentViewUtils;
public class ClientImportHandler extends ImportDialogHandler {
private static final String COMPONENT_ACCOUNTS = "cbAccounts";
@@ -157,7 +157,7 @@ protected CsvRowFormat getRowFormatForClient() {
COMPONENT_CB_PHONE);
for(CustomField cf : customFieldDao.getAllActiveUsedCustomFields()){
- addMarker(rowFormat, StringUtil.getMarkerFromString(cf.getReadableName()),
+ addMarker(rowFormat, PaymentViewUtils.getMarkerFromString(cf.getReadableName()),
cf.getCamelCaseName());
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/CreateSettingsHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/CreateSettingsHandler.java
index 9b601ddb..cf8b0a85 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/CreateSettingsHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/CreateSettingsHandler.java
@@ -16,9 +16,11 @@
public class CreateSettingsHandler extends BasePanelHandler implements EventObserver{
private static final String ENTER_NEW_TARGET = "Enter New Target";
private static final String XML_STEP_CREATE_SETTINGS = "/ui/plugins/paymentview/analytics/addclient/stepcreatesettings.xml";
+
private final AddClientTabHandler addClientTabHandler;
private final SelectClientsHandler previousSelectClientsHandler;
private final PaymentViewPluginController pluginController;
+
private Object cmbtargets;
private Object pnlFields;
@@ -105,6 +107,7 @@ public Object getPanelFieldsComponent() {
return pnlFields;
}
+ @SuppressWarnings("rawtypes")
public void notify(FrontlineEventNotification notification) {
if (!(notification instanceof EntitySavedNotification)) {
return;
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/SelectTargetSavingsHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/SelectTargetSavingsHandler.java
index b2103b0a..2b034181 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/SelectTargetSavingsHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/addclient/SelectTargetSavingsHandler.java
@@ -7,14 +7,21 @@
import org.creditsms.plugins.paymentview.ui.handler.tabanalytics.innertabs.AddClientTabHandler;
public class SelectTargetSavingsHandler extends BasePanelHandler {
+private static final String CHK_TARGET_SAVINGS_LAYAWAY = "target_savings_layaway";
+
+//> CONSTANTS
private static final String XML_STEP_SELECT_TARGET_SAVING = "/ui/plugins/paymentview/analytics/addclient/stepselecttargetsavings.xml";
+
private AddClientTabHandler addClientTabHandler;
private PaymentViewPluginController pluginController;
+ private Object chkTargetSavingsLayaway;
+
public SelectTargetSavingsHandler(UiGeneratorController ui,
PaymentViewPluginController pluginController,
final AddClientTabHandler addClientTabHandler) {
super(ui);
+
this.pluginController = pluginController;
this.addClientTabHandler = addClientTabHandler;
this.loadPanel(XML_STEP_SELECT_TARGET_SAVING);
@@ -26,8 +33,17 @@ public Object getPanelComponent() {
}
public void next() {
- addClientTabHandler.setCurrentStepPanel(new SelectClientsHandler(
- (UiGeneratorController) ui, pluginController, addClientTabHandler, this).getPanelComponent());
+ if (selectedRadiosButtons()){
+ addClientTabHandler.setCurrentStepPanel(new SelectClientsHandler(
+ (UiGeneratorController) ui, pluginController, addClientTabHandler, this).getPanelComponent());
+ }
+ }
+
+ private boolean selectedRadiosButtons() {
+ if(chkTargetSavingsLayaway == null){
+ chkTargetSavingsLayaway = ui.find(this.getPanelComponent(), CHK_TARGET_SAVINGS_LAYAWAY);
+ }
+ return ui.isSelected(chkTargetSavingsLayaway);
}
public void selectService() {
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/CustomizeClientDBHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/CustomizeClientDBHandler.java
index 19d9ddb0..293c03e4 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/CustomizeClientDBHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/CustomizeClientDBHandler.java
@@ -12,7 +12,7 @@
import org.creditsms.plugins.paymentview.data.domain.CustomField;
import org.creditsms.plugins.paymentview.data.repository.CustomFieldDao;
import org.creditsms.plugins.paymentview.ui.handler.tabclients.ClientsTabHandler;
-import org.creditsms.plugins.paymentview.utils.StringUtil;
+import org.creditsms.plugins.paymentview.utils.PaymentViewUtils;
public class CustomizeClientDBHandler implements ThinletUiEventHandler {
private static final String ENTER_NEW_FIELD = "Enter New Field";
@@ -57,7 +57,7 @@ private void init() {
c = 0;
for (Field field : Client.class.getDeclaredFields()) {
if (field.isAnnotationPresent(Column.class)) {
- addField(StringUtil.getReadableFieldName(field.getName()));
+ addField(PaymentViewUtils.getReadableFieldName(field.getName()));
}
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java
index 84f5d3db..54bf0b06 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java
@@ -19,30 +19,34 @@
import org.creditsms.plugins.paymentview.ui.handler.tabclients.ClientsTabHandler;
public class EditClientHandler extends BaseDialog{
+//> CONSTANTS
private static final String COMPONENT_LIST_ACCOUNTS = "fldAccounts";
-
private static final String COMPONENT_TEXT_FIRST_NAME = "fldFirstName";
private static final String COMPONENT_TEXT_OTHER_NAME = "fldOtherName";
private static final String COMPONENT_TEXT_PHONE_NUMBER = "fldPhoneNumber";
private static final String XML_EDIT_CLIENT = "/ui/plugins/paymentview/clients/dialogs/dlgEditClient.xml";
+//>DAOs
private ClientDao clientDao;
- private Client client;
- private boolean editMode;
+ private CustomValueDao customValueDao;
+ private CustomFieldDao customFieldDao;
+ private Client client;
+
+//> UI FIELDS
private Object fieldFirstName;
private Object fieldListAccounts;
private Object fieldOtherName;
private Object fieldPhoneNumber;
+//UI HELPERS
private ClientsTabHandler clientsTabHandler;
-
- private CustomValueDao customValueDao;
- private CustomFieldDao customFieldDao;
-
+
private Object compPanelFields;
private Map<CustomField, Object> customComponents;
+ private boolean editMode;
+
public EditClientHandler(UiGeneratorController ui, PaymentViewPluginController pluginController, ClientsTabHandler clientsTabHandler) {
super(ui);
this.clientDao = pluginController.getClientDao();
@@ -71,13 +75,6 @@ private Object createListItem(Account acc) {
return ui.createListItem(acc.getAccountNumber(), acc, true);
}
- /**
- * @return the clientObj
- */
- public Client getClientObj() {
- return client;
- }
-
public void init() {
dialogComponent = ui.loadComponentFromFile(XML_EDIT_CLIENT, this);
compPanelFields = ui.find(dialogComponent, "pnlFields");
@@ -215,4 +212,12 @@ public void saveClient() {
removeDialog();
clientsTabHandler.refresh();
}
+
+ /**
+ * @return the clientObj
+ */
+ public Client getClientObj() {
+ return client;
+ }
+
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java
index 772ef805..4ca34402 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java
@@ -7,7 +7,7 @@
import net.frontlinesms.messaging.mms.email.MmsEmailServiceStatus;
import net.frontlinesms.messaging.sms.SmsService;
import net.frontlinesms.messaging.sms.modem.SmsModemStatus;
-import net.frontlinesms.payment.PaymentService;
+import net.frontlinesms.payment.PaymentServiceAccount;
import net.frontlinesms.ui.Icon;
import net.frontlinesms.ui.UiGeneratorController;
import net.frontlinesms.ui.UiGeneratorControllerConstants;
@@ -17,8 +17,7 @@
import org.creditsms.plugins.paymentview.PaymentViewPluginController;
import org.creditsms.plugins.paymentview.data.domain.Account;
import org.creditsms.plugins.paymentview.data.repository.AccountDao;
-import org.creditsms.plugins.paymentview.data.repository.ClientDao;
-import org.creditsms.plugins.paymentview.data.repository.IncomingPaymentDao;
+import org.creditsms.plugins.paymentview.ui.handler.tabsettings.dialogs.ConfigureAccountHandler;
import org.creditsms.plugins.paymentview.ui.handler.tabsettings.dialogs.steps.createnewsettings.MobilePaymentService;
public class SettingsTabHandler extends BaseTabHandler {
@@ -27,10 +26,7 @@ public class SettingsTabHandler extends BaseTabHandler {
private AccountDao accountDao;
- private ClientDao clientDao;
- private IncomingPaymentDao incomingPaymentDao;
-
- private List<PaymentService> paymentServices;
+ private List<PaymentServiceAccount> paymentServices;
private Object settingsTab;
private Object settingsTableComponent;
@@ -40,14 +36,14 @@ public SettingsTabHandler(UiGeneratorController ui, PaymentViewPluginController
super(ui);
this.pluginController = pluginController;
- this.incomingPaymentDao = pluginController.getIncomingPaymentDao();
this.accountDao = pluginController.getAccountDao();
- this.clientDao = pluginController.getClientDao();
- paymentServices = new ArrayList<PaymentService>(0);
+ this.paymentServices = new ArrayList<PaymentServiceAccount>(0);
init();
}
public void configureAccount() {
+ ConfigureAccountHandler configureAccountHandler = new ConfigureAccountHandler(ui, pluginController);
+ configureAccountHandler.showDialog();
}
public void createNew() {
@@ -63,8 +59,7 @@ public void deleteAccount() {
accountDao.deleteAccount(a);
}
- ui.removeDialog(ui
- .find(UiGeneratorControllerConstants.COMPONENT_CONFIRM_DIALOG));
+ ui.removeDialog(ui.find(UiGeneratorControllerConstants.COMPONENT_CONFIRM_DIALOG));
ui.infoMessage("You have succesfully deleted from the operator!");
this.refresh();
}
@@ -81,17 +76,18 @@ protected Object initialiseTab() {
return settingsTab;
}
- public void addPaymentService(PaymentService paymentService) {
+ public void addPaymentService(PaymentServiceAccount paymentService) {
if (!paymentServices.contains(paymentService)){
paymentServices.add(paymentService);
}else{
ui.getFrontlineController().getEventBus().unregisterObserver(paymentService);
paymentService = null;
}
+
refresh();
}
- public Object getRow(PaymentService paymentService){
+ public Object getRow(PaymentServiceAccount paymentService){
SmsService service = paymentService.getSmsService();
Object cellServiceName = ui.createTableCell(service.getServiceName());
@@ -132,7 +128,7 @@ public Object getRow(PaymentService paymentService){
@Override
public void refresh() {
ui.removeAll(settingsTableComponent);
- for(PaymentService paymentService : paymentServices){
+ for(PaymentServiceAccount paymentService : paymentServices){
ui.add(settingsTableComponent, getRow(paymentService));
}
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/ConfigureAccountHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/ConfigureAccountHandler.java
index a2ec29e5..c5380c63 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/ConfigureAccountHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/ConfigureAccountHandler.java
@@ -1,46 +1,31 @@
package org.creditsms.plugins.paymentview.ui.handler.tabsettings.dialogs;
-import net.frontlinesms.ui.ThinletUiEventHandler;
import net.frontlinesms.ui.UiGeneratorController;
-public class ConfigureAccountHandler implements ThinletUiEventHandler {
+import org.creditsms.plugins.paymentview.PaymentViewPluginController;
+import org.creditsms.plugins.paymentview.ui.handler.BaseDialog;
+
+public class ConfigureAccountHandler extends BaseDialog {
private static final String XML_CONFIGURE_ACCOUNT = "/ui/plugins/paymentview/settings/dialogs/dlgConfigureAccount.xml";
- private Object dialogComponent;
- private UiGeneratorController ui;
+ private final PaymentViewPluginController pluginController;
- public ConfigureAccountHandler(UiGeneratorController ui) {
- this.ui = ui;
+ public ConfigureAccountHandler(UiGeneratorController ui, PaymentViewPluginController pluginController) {
+ super(ui);
+ this.pluginController = pluginController;
init();
refresh();
}
- public void deteteAccount() {
+ public void deleteAccount() {
// TODO Auto-generated method stub
}
- /**
- * @return the customizeClientDialog
- */
- public Object getDialog() {
- return dialogComponent;
- }
-
private void init() {
dialogComponent = ui.loadComponentFromFile(XML_CONFIGURE_ACCOUNT, this);
}
- private void refresh() {
- }
-
- /** Remove the dialog from view. */
- public void removeDialog() {
- this.removeDialog(this.dialogComponent);
- }
-
- /** Remove a dialog from view. */
- public void removeDialog(Object dialog) {
- this.ui.removeDialog(dialog);
+ protected void refresh() {
}
public void updateAccPIN() {
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/CreateNewAccountHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/CreateNewAccountHandler.java
index 489097c1..782dbf2b 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/CreateNewAccountHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/CreateNewAccountHandler.java
@@ -18,7 +18,6 @@ public CreateNewAccountHandler(UiGeneratorController ui) {
private void init() {
dialogComponent = ui.loadComponentFromFile(XML_CONFIGURE_ACCOUNT, this);
}
-
- private void refresh() {
- }
+
+ protected void refresh() { }
}
\ No newline at end of file
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPin.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPin.java
index 1f5c7edb..8cc04173 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPin.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPin.java
@@ -1,7 +1,7 @@
package org.creditsms.plugins.paymentview.ui.handler.tabsettings.dialogs.steps.createnewsettings;
import net.frontlinesms.messaging.sms.modem.SmsModem;
-import net.frontlinesms.payment.PaymentService;
+import net.frontlinesms.payment.PaymentServiceAccount;
import net.frontlinesms.ui.UiGeneratorController;
import org.creditsms.plugins.paymentview.PaymentViewPluginController;
@@ -39,7 +39,7 @@ public void next(final String Pin, final String VPin) {
public void setUpThePaymentService(final String pin, final String vPin) {
if(checkValidityOfPinFields(pin, vPin)){
- PaymentService paymentService = previousMobilePaymentService.getPaymentService();
+ PaymentServiceAccount paymentService = previousMobilePaymentService.getPaymentService();
paymentService.setPin(pin);
paymentService.setSmsService((SmsModem) previousMobilePaymentService.getSmsService());
@@ -55,7 +55,7 @@ public void setUpThePaymentService(final String pin, final String vPin) {
}
}
- PaymentService getPaymentService() {
+ PaymentServiceAccount getPaymentService() {
return previousMobilePaymentService.getPaymentService();
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentService.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentService.java
index d58f8310..d5c21948 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentService.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentService.java
@@ -1,7 +1,7 @@
package org.creditsms.plugins.paymentview.ui.handler.tabsettings.dialogs.steps.createnewsettings;
import net.frontlinesms.messaging.sms.SmsService;
-import net.frontlinesms.payment.PaymentService;
+import net.frontlinesms.payment.PaymentServiceAccount;
import net.frontlinesms.payment.safaricom.MpesaPayBillService;
import net.frontlinesms.payment.safaricom.MpesaPaymentService;
import net.frontlinesms.payment.safaricom.MpesaPersonalService;
@@ -14,7 +14,7 @@
public class MobilePaymentService extends BaseDialog {
private static final String XML_MOBILE_PAYMENT_SERVICE = "/ui/plugins/paymentview/settings/dialogs/createnewpaymentsteps/dlgCreateNewAccountStep1.xml";
private final PaymentViewPluginController pluginController;
- private PaymentService paymentService;
+ private PaymentServiceAccount paymentService;
private SmsService smsService;
private final SettingsTabHandler settingsTabHandler;
@@ -65,7 +65,7 @@ public void next(Object cmbSelectPaymentService, Object cmbDevices) {
if(smsService == null){
throw new RuntimeException("No Device Selected.");
}
- paymentService = ui.getAttachedObject(ui.getItem(cmbSelectPaymentService, selectedIndex), PaymentService.class);
+ paymentService = ui.getAttachedObject(ui.getItem(cmbSelectPaymentService, selectedIndex), PaymentServiceAccount.class);
if (paymentService != null) {
EnterPin accountType = new EnterPin(ui, pluginController, this);
accountType.showDialog();
@@ -82,7 +82,7 @@ private void cleanUp() {
}
//> ACCESSORS
- PaymentService getPaymentService() {
+ PaymentServiceAccount getPaymentService() {
return paymentService;
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/utils/PaymentViewUtils.java b/src/main/java/org/creditsms/plugins/paymentview/utils/PaymentViewUtils.java
index 9ad7e7c2..85467b9a 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/utils/PaymentViewUtils.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/utils/PaymentViewUtils.java
@@ -1,12 +1,16 @@
package org.creditsms.plugins.paymentview.utils;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
+import java.util.List;
-import org.creditsms.plugins.paymentview.data.domain.Account;
+import net.frontlinesms.FrontlineUtils;
-public class PaymentViewUtils extends net.frontlinesms.FrontlineUtils {
+import org.creditsms.plugins.paymentview.data.domain.Account;
+import org.springframework.util.StringUtils;
+public class PaymentViewUtils extends FrontlineUtils {
public static String accountsAsString(Collection<Account> accounts,
String groupsDelimiter) {
String str_accounts = "";
@@ -19,4 +23,83 @@ public static String accountsAsString(Collection<Account> accounts,
return str_accounts;
}
+ public static String toCamelCase(String str) {
+ if (str != null) {
+ String[] strings = str.split(" ");
+ str = "";
+ for (int i = 0; i < strings.length; i++) {
+ strings[i] = strings[i].toLowerCase();
+ if (i != 0) {
+ strings[i] = StringUtils.capitalize(strings[i]);
+ }
+ str += strings[i];
+ }
+ return str;
+ }
+ return null;
+ }
+
+ public static String[] splitByCharacterTypeCamelCase(String str) {
+ return splitByCharacterType(str, true);
+ }
+
+ // From Apache Commons
+ private static String[] splitByCharacterType(String str, boolean camelCase) {
+ if (str == null) {
+ return null;
+ }
+ if (str.length() == 0) {
+ return new String[0];
+ }
+ char[] c = str.toCharArray();
+ List<String> list = new ArrayList<String>();
+ int tokenStart = 0;
+ int currentType = Character.getType(c[tokenStart]);
+ for (int pos = tokenStart + 1; pos < c.length; pos++) {
+ int type = Character.getType(c[pos]);
+ if (type == currentType) {
+ continue;
+ }
+ if (camelCase && type == Character.LOWERCASE_LETTER
+ && currentType == Character.UPPERCASE_LETTER) {
+ int newTokenStart = pos - 1;
+ if (newTokenStart != tokenStart) {
+ list.add(new String(c, tokenStart, newTokenStart
+ - tokenStart));
+ tokenStart = newTokenStart;
+ }
+ } else {
+ list.add(new String(c, tokenStart, pos - tokenStart));
+ tokenStart = pos;
+ }
+ currentType = type;
+ }
+ list.add(new String(c, tokenStart, c.length - tokenStart));
+ return (String[]) list.toArray(new String[list.size()]);
+ }
+
+ public static String getReadableFieldName(String fieldName) {
+ String str = StringUtils.capitalize(fieldName);
+ String[] strArr = splitByCharacterTypeCamelCase(str);
+ StringBuilder str2 = new StringBuilder(2);
+ for (String s : strArr) {
+ str2.append(s);
+ str2.append(" ");
+ }
+ return str2.toString().trim();
+ }
+
+ public static String getFormLabel(String fieldName) {
+ return getReadableFieldName(fieldName) + ":";
+ }
+
+ public static String getMarkerFromString(String readableName) {
+ if (readableName != null) {
+ readableName = readableName.toLowerCase();
+ readableName = StringUtils.replace(readableName, " ", "_");
+ readableName = "${" + readableName + "}";
+ return readableName;
+ }
+ return "";
+ }
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/utils/StringUtil.java b/src/main/java/org/creditsms/plugins/paymentview/utils/StringUtil.java
deleted file mode 100644
index 2d956dc8..00000000
--- a/src/main/java/org/creditsms/plugins/paymentview/utils/StringUtil.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package org.creditsms.plugins.paymentview.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.util.StringUtils;
-
-public final class StringUtil {
-
- public static String toCamelCase(String str) {
- if (str != null) {
- String[] strings = str.split(" ");
- str = "";
- for (int i = 0; i < strings.length; i++) {
- strings[i] = strings[i].toLowerCase();
- if (i != 0) {
- strings[i] = StringUtils.capitalize(strings[i]);
- }
- str += strings[i];
- }
- return str;
- }
- return null;
- }
-
- public static String[] splitByCharacterTypeCamelCase(String str) {
- return splitByCharacterType(str, true);
- }
-
- /**
- * <p>
- * Splits a String by Character type as returned by
- * <code>java.lang.Character.getType(char)</code>. Groups of contiguous
- * characters of the same type are returned as complete tokens, with the
- * following exception: if <code>camelCase</code> is <code>true</code>, the
- * character of type <code>Character.UPPERCASE_LETTER</code>, if any,
- * immediately preceding a token of type
- * <code>Character.LOWERCASE_LETTER</code> will belong to the following
- * token rather than to the preceding, if any,
- * <code>Character.UPPERCASE_LETTER</code> token.
- *
- * @param str
- * the String to split, may be <code>null</code>
- * @param camelCase
- * whether to use so-called "camel-case" for letter types
- * @return an array of parsed Strings, <code>null</code> if null String
- * input
- * @since 2.4
- */
- // From Apache Commons
- private static String[] splitByCharacterType(String str, boolean camelCase) {
- if (str == null) {
- return null;
- }
- if (str.length() == 0) {
- return new String[0];
- }
- char[] c = str.toCharArray();
- List list = new ArrayList();
- int tokenStart = 0;
- int currentType = Character.getType(c[tokenStart]);
- for (int pos = tokenStart + 1; pos < c.length; pos++) {
- int type = Character.getType(c[pos]);
- if (type == currentType) {
- continue;
- }
- if (camelCase && type == Character.LOWERCASE_LETTER
- && currentType == Character.UPPERCASE_LETTER) {
- int newTokenStart = pos - 1;
- if (newTokenStart != tokenStart) {
- list.add(new String(c, tokenStart, newTokenStart
- - tokenStart));
- tokenStart = newTokenStart;
- }
- } else {
- list.add(new String(c, tokenStart, pos - tokenStart));
- tokenStart = pos;
- }
- currentType = type;
- }
- list.add(new String(c, tokenStart, c.length - tokenStart));
- return (String[]) list.toArray(new String[list.size()]);
- }
-
- public static String getReadableFieldName(String fieldName) {
- String str = StringUtils.capitalize(fieldName);
- String[] strArr = splitByCharacterTypeCamelCase(str);
- StringBuilder str2 = new StringBuilder(2);
- for (String s : strArr) {
- str2.append(s);
- str2.append(" ");
- }
- return str2.toString().trim();
- }
-
- public static String getFormFieldName(String fieldName) {
- return fieldName;
- }
-
- public static String getFieldFromFormField(String formFieldName) {
- return "";
- }
-
- public static String getFormLabel(String fieldName) {
- return getReadableFieldName(fieldName) + ":";
- }
-
- public static String getMarkerFromString(String readableName) {
- if (readableName != null) {
- readableName = readableName.toLowerCase();
- readableName = StringUtils.replace(readableName, " ", "_");
- readableName = "${" + readableName + "}";
- return readableName;
- }
- return "";
- }
-}
diff --git a/src/main/resources/ui/plugins/paymentview/analytics/addclient/stepselecttargetsavings.xml b/src/main/resources/ui/plugins/paymentview/analytics/addclient/stepselecttargetsavings.xml
index 102e6d19..50b2044a 100644
--- a/src/main/resources/ui/plugins/paymentview/analytics/addclient/stepselecttargetsavings.xml
+++ b/src/main/resources/ui/plugins/paymentview/analytics/addclient/stepselecttargetsavings.xml
@@ -13,7 +13,7 @@
<label text="1. Select the Service for client or a group of clients" />
<panel columns="2" gap="5" left="10" right="10" weightx="1">
<label colspan="2" text="Incoming Payment" font="Bold"/>
- <checkbox group="incomingPay" text="Targeted Savings / Layaway" />
+ <checkbox group="incomingPay" name="target_savings_layaway" text="Targeted Savings / Layaway" />
</panel>
</panel>
diff --git a/src/main/resources/ui/plugins/paymentview/settings/dialogs/dlgConfigureAccount.xml b/src/main/resources/ui/plugins/paymentview/settings/dialogs/dlgConfigureAccount.xml
index 3fac332a..82292e1f 100644
--- a/src/main/resources/ui/plugins/paymentview/settings/dialogs/dlgConfigureAccount.xml
+++ b/src/main/resources/ui/plugins/paymentview/settings/dialogs/dlgConfigureAccount.xml
@@ -1,42 +1,54 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
-<dialog bottom="9" close="removeDialog(this)"
- columns="3" gap="15" left="9" name="clientDetailsDialog"
- right="9" text="Configure Mobile Payment Account"
+<dialog bottom="9" close="removeDialog(this)" icon="/icons/keyword.png"
+ columns="1" gap="15" left="9" name="clientDetailsDialog"
+ right="9" text="Configure Payment Account"
top="9" resizable="true" modal="true" closable="true">
-
- <label text="Name:" />
- <label name="txtName" text="" colspan="2"/>
- <label text="Phone Number:" />
- <label name="txtNumber" text="" colspan="2"/>
-
- <label text="Balance:" />
- <label name="txtBalance" text="" colspan="2"/>
-
- <label text="Type:" />
- <label name="txtType" text="" colspan="2"/>
-
- <label text="SYSTEM" colspan="3"/>
- <label text="Operator:" />
- <label name="txtOperator" text="" colspan="2"/>
-
- <label text="Geography:" />
- <label name="txtGeography" text="" colspan="2"/>
-
- <label text="Outgoing Payments:" />
- <label name="txtOutgoingPayments" text="" colspan="2"/>
-
- <label text="Incoming Payments:" />
- <label name="txtIncomingPayments" text="" colspan="2"/>
-
- <panel colspan="3" columns="1" weightx="1">
- <button icon="/icons/keyword.png" text="Update Account PIN"
- action="updateAccPIN" />
- <button icon="/icons/keyword.png" text="Update Authorization Settings"
- action="updateAuthSettings" />
- <button icon="/icons/delete.png" text="Delete"
- action="deteteAccount" />
- <button text="Close"
- action="removeDialog" />
+ <panel columns="1" gap="10" weightx="1">
+ <panel columns="3" gap="10" weightx="1">
+ <label text="Name:" />
+ <label name="txtName" text="" colspan="2"/>
+
+ <label text="Phone Number:" />
+ <label name="txtNumber" text="" colspan="2"/>
+
+ <panel weightx="1" colspan="3"/>
+
+ <label text="Balance:" />
+ <label name="txtBalance" text="" colspan="2"/>
+
+ <label text="Type:" />
+ <label name="txtType" text="" colspan="2"/>
+
+ <panel weightx="1" colspan="3"/>
+
+ <label text="SYSTEM" colspan="3" font="bold"/>
+ <label text="Operator:" />
+ <label name="txtOperator" text="" colspan="2"/>
+
+ <label text="Geography:" />
+ <label name="txtGeography" text="" colspan="2"/>
+
+ <label text="Outgoing Payments:" />
+ <label name="txtOutgoingPayments" text="" colspan="2"/>
+
+ <label text="Incoming Payments:" />
+ <label name="txtIncomingPayments" text="" colspan="2"/>
+ </panel>
+ <panel columns="1" weightx="1" gap="10">
+ <button text="Update Account PIN"
+ action="updateAccPIN"/>
+ </panel>
+ <panel columns="1" weightx="1" gap="10">
+ <button text="Update Authorization Settings"
+ action="updateAuthSettings" />
+ </panel>
+ <panel weightx="1">
+ <button icon="/icons/delete.png" text="Delete"
+ action="deleteAccount" weightx="1"/>
+ <panel weightx="1"/>
+ <button text="Close" icon="/icons/cross.png"
+ action="removeDialog" weightx="1"/>
+ </panel>
</panel>
</dialog>
\ No newline at end of file
diff --git a/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml b/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml
index ea0c7d73..89cc5fcc 100644
--- a/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml
+++ b/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml
@@ -28,7 +28,6 @@
</panel>
<panel gap="5" bottom="5" name="pnl_buttons"
weightx="1">
- <button name="btn_analyse" icon="/icons/keyword.png" text="i18n.plugins.paymentview.action.configure" action="configureAccount"/>
<button name="btn_analyse" icon="/icons/keyword_add.png" text="i18n.plugins.paymentview.action.createnew" action="createNew" />
<panel weightx="1"/>
<panel weightx="1"/>
|
08dbf2ed3696c16a8c2f67e436ace7f6a7622386
|
cloudname$cloudname
|
Brave new world
Rewrite into a core library with simple methods and an abstraction layer on
top of the backend system.
The following backends are implemented
* Memory (for testing; only works within a single JVM)
* ZooKeeper (proof-of-concept implementation of the backend)
The following libraries are created:
* Service discovery library
This brings the overall functionality on par with 2.x with a few exceptions:
* Locking isn't implemented. That did not work for the old library so
there's no real change in functionality
* It isn't possible to query *everything* from a client. This will be
addressed in another commit (or just ignored completely since the
backends offers this in some shape or form)
* It isn't possible to resolve coordinates partially, f.e. finding
"logserver" when your own coordinate is "service.tag.region";
"logserver" should resolve to "logserver.tag.region". This will
be solved in a later commit by making a separate resolver class that
creates service coordinates based on existing coordinates.
|
p
|
https://github.com/cloudname/cloudname
|
diff --git a/README.md b/README.md
index 4a1fbe9b..90ef64d5 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,31 @@
# Brave new world: Cloudname 3.0
-Forget everything we said earlier. This is going to be even greater.
+## cn-core
+The core Cloudname library for resource management
+
+## cn-service
+Service discovery built on top of the core library.
+
+---
+# The yet-to-be-updated section
+
+## a3 -- Authentication, Authorization and Access library
+Mostly the first, some of the second. Still unchanged from 2.x
+
+## Idgen - Generating IDs
+Generate bucketloads of unique IDs spread across multiple hosts, services and
+regions.
+
+## Flags - Command line Flags
+Simple command line flag handling via annotations on properties and accessors.
+
+## Log - Core logging library
+Core entities for logging.
+
+## Timber - A log server and client
+A networked high-performance log server that uses protobuf entities. Server and
+client code.
+
+## Testtools - Testing tools and utilities
+
+Mostly for internal use by the various modules.
diff --git a/cn-core/README.md b/cn-core/README.md
new file mode 100644
index 00000000..9df86e77
--- /dev/null
+++ b/cn-core/README.md
@@ -0,0 +1,30 @@
+# Cloudname Core
+
+The core libraries are mostly for internal use and are the basic building block for the other libraries. Clients won't use or access this library directly but through the libraries build on the core library.
+
+The core library supports various backends. The build-in backend is memory-based and is *not* something you want to use in a production service. Its sole purpose is to provide a fast single-JVM backend used when testing other modules built on top of the core library.
+
+## Key concepts
+### Leases
+The backends expose **leases** to clients. Each lease is represented by a **path**. Clients belong to a **region**. A region is typically a cluster of servers that are coordinate through a single backend.
+
+
+
+#### Client leases
+Ordinary leases exists only as long as the client is running and is connected to the backend. When the client terminates the connection the lease expires and anyone listening on changes will be notified.
+
+#### Permanent leases
+Permanent leases persist between client connections. If a client connects to the backend, creates a permanent lease and then disconnects the lease will still be in place. The permanent leases does not expire and will only be removed if done so explicitly by the clients.
+
+### Paths
+A **path** is nothing more than an ordered set of strings that represents a (real or virtual) tree structure. The backend itself does not need to use a hierarchical storage mechanism since the paths can be used directly as identifiers.
+
+Elements in the paths follows the DNS naming conventions in RFC 952 and RFC 1123: Strings between 1-63 characters long, a-z characters (case insensitive) and hyphens. A string cannot start or end with a hyphen.
+
+
+## Backend requirements
+* Paths are guaranteed unique for all clients in the same cluster. There is no guarantee that a lease will be unique for other regions.
+* The backend ensures there are no duplicate leases for the current region.
+* The backend will create notifications in the same order as they occur.
+* Past leases given to disconnected clients are not guaranteed to be unique
+* The backend is responsible for cleanups of leases; if all clients disconnect the only leases that should be left is the permanent leases.
diff --git a/cn-core/pom.xml b/cn-core/pom.xml
new file mode 100644
index 00000000..1c8fe5f9
--- /dev/null
+++ b/cn-core/pom.xml
@@ -0,0 +1,46 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cloudname-parent</artifactId>
+ <version>3.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>cn-core</artifactId>
+ <packaging>jar</packaging>
+
+ <name>Cloudname Library</name>
+ <description>Managing distributed resources</description>
+ <url>https://github.com/Cloudname/cloudname</url>
+
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-all</artifactId>
+ <version>1.3</version>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+
+ </plugins>
+ </build>
+</project>
diff --git a/cn-core/src/main/java/org/cloudname/core/CloudnameBackend.java b/cn-core/src/main/java/org/cloudname/core/CloudnameBackend.java
new file mode 100644
index 00000000..ed7f2270
--- /dev/null
+++ b/cn-core/src/main/java/org/cloudname/core/CloudnameBackend.java
@@ -0,0 +1,133 @@
+package org.cloudname.core;
+
+/**
+ * Backends implement this interface. Clients won't use this interface; the logic is handled by the
+ * libaries built on top of the backend. Each backend provides a few basic primitives that must be
+ * implemented. One caveat: The backend is responsible for cleaning up unused paths. The clients won't
+ * remote unused elements.
+ *
+ * There are two kinds of leases - permanent and temporary. The permanent leases persist in the
+ * backend and aren't removed when clients disconnect, even if *all* clients disconnects.
+ * The temporary leases are removed by the backend when the client closes. Note that clients might
+ * not be well-behaved and may terminate without calling close(). The backend should remove
+ * these leases automatically.
+ *
+ * Clients listen on both kinds of leases and get notifications through listeners whenever something
+ * is changed. Notifications to the clients are sent in the same order they are received.
+ *
+ * Each lease have a data string attached to the lease and clients may update this freely.
+ *
+ * @author [email protected]
+ */
+public interface CloudnameBackend extends AutoCloseable {
+ /**
+ * Create a temporary lease. The temporary lease is limited by the client's connection and will
+ * be available for as long as the client is connected to the backend. Once the client
+ * disconnects (either through the LeaseHandle instance that is returned or just vanishing
+ * from the face of the earth) the lease is removed by the backend. The backend should support
+ * an unlimited number of leases (FSVO "unlimited")
+ *
+ * @param path Path to temporary lease. This value cannot be null. The path supplied by the
+ * client is just the stem of the full lease, i.e. if a client supplies foo:bar the backend
+ * will return an unique path to the client which represent the lease (for "foo:bar" the
+ * backend might return "foo:bar:uniqueid0", "foo:bar:uniqueid1"... to clients acquiring
+ * the lease.
+ *
+ * @param data Temporary lease data. This is an arbitrary string supplied by the client. It
+ * carries no particular semantics for the backend and the backend only have to return the
+ * same string to the client. This value cannot be null.
+ *
+ * @return A LeaseHandle instance that the client can use to manipulate its data or release
+ * the lease (ie closing it).
+ */
+ LeaseHandle createTemporaryLease(final CloudnamePath path, final String data);
+
+ /**
+ * Update a client's lease. Normally this is something the client does itself but libraries
+ * built on top of the backends might use it to set additional properties.
+ * @param path Path to the temporary lease.
+ * @param data The updated lease data.
+ * @return True if successful, false otherwise
+ */
+ boolean writeTemporaryLeaseData(final CloudnamePath path, final String data);
+
+ /**
+ * Read temporary lease data. Clients won't use this in regular use but rather monitor changes
+ * through the listeners but libraries built on top of the backend might read the data.
+ *
+ * @param path Path to the client lease.
+ * @return The data stored in the client lease.
+ */
+ String readTemporaryLeaseData(final CloudnamePath path);
+
+ /**
+ * Add a listener to a set of temporary leases identified by a path. The temporary leases
+ * doesn't have to exist but as soon as someone creates a lease matching the given path a
+ * notification must be sent by the backend implementation.
+ *
+ * @param pathToObserve The path to observe for changes.
+ * @param listener Client's listener. Callbacks on this listener will be invoked by the backend.
+ */
+ void addTemporaryLeaseListener(final CloudnamePath pathToObserve, final LeaseListener listener);
+
+ /**
+ * Remove a previously attached listener. The backend will ignore leases that doesn't exist.
+ *
+ * @param listener The listener to remove
+ */
+ void removeTemporaryLeaseListener(final LeaseListener listener);
+
+ /**
+ * Create a permanent lease. A permanent lease persists even if the client that created it
+ * terminates or closes the connection. Other clients will still see the lease. Permanent leases
+ * must persist until they are explicitly removed.
+ *
+ * All permanent leases must be unique. Duplicate permanent leases yields an error.
+ *
+ * @param path Path to the permanent lease.
+ * @param data Data to store in the permanent lease when it is created.
+ * @return true if successful
+ */
+ boolean createPermanantLease(final CloudnamePath path, final String data);
+
+ /**
+ * Remove a permanent lease. The lease will be removed and clients listening on the lease
+ * will be notified.
+ *
+ * @param path The path to the lease
+ * @return true if lease is removed.
+ */
+ boolean removePermanentLease(final CloudnamePath path);
+
+ /**
+ * Update data on permanent lease.
+ *
+ * @param path path to the permanent lease
+ * @param data data to write to the lease
+ * @return true if successful
+ */
+ boolean writePermanentLeaseData(final CloudnamePath path, final String data);
+
+ /**
+ * Read data from permanent lease.
+ *
+ * @param path path to permanent lease
+ * @return data stored in lease or null if the lease doesn't exist
+ */
+ String readPermanentLeaseData(final CloudnamePath path);
+
+ /**
+ * Add a listener to a permanent lease. The listener is attached to just one lease, as opposed
+ * to the termporary lease listener.
+ *
+ * @param pathToObserver Path to lease
+ * @param listener Listener. Callbacks on this listener is invoked by the backend.
+ */
+ void addPermanentLeaseListener(final CloudnamePath pathToObserver, final LeaseListener listener);
+
+ /**
+ * Remove listener on permanent lease. Unknown listeners are ignored by the backend.
+ * @param listener The listener to remove
+ */
+ void removePermanentLeaseListener(final LeaseListener listener);
+}
diff --git a/cn-core/src/main/java/org/cloudname/core/CloudnamePath.java b/cn-core/src/main/java/org/cloudname/core/CloudnamePath.java
new file mode 100644
index 00000000..269d57cd
--- /dev/null
+++ b/cn-core/src/main/java/org/cloudname/core/CloudnamePath.java
@@ -0,0 +1,195 @@
+package org.cloudname.core;
+
+import java.util.Arrays;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A generic representation of a path. A "path" might be a bit of a misnomer in the actual
+ * backend implementation but it can be represented as an uniquely identifying string for the
+ * leases handed out. A path can be split into elements which can be accessed individually.
+ *
+ * Paths are an ordered set of strings consisting of the characters according to RFC 952 and
+ * RFC 1123, ie [a-z,0-9,-]. The names cannot start or end with an hyphen and can be between
+ * 1 and 63 characters long.
+ *
+ * @author [email protected]
+ */
+public class CloudnamePath {
+ private final String[] pathElements;
+ private static final Pattern NAME_PATTERN = Pattern.compile("[a-z0-9-]*");
+
+ /**
+ * Check if path element is a valid name according to RFC 953/RCC 1123
+ *
+ * @param name The element to check
+ * @return true if element is a valid stirng
+ */
+ public static boolean isValidPathElementName(final String name) {
+ if (name == null || name.isEmpty()) {
+ return false;
+ }
+
+ final Matcher matcher = NAME_PATTERN.matcher(name);
+ if (!matcher.matches()) {
+ return false;
+ }
+ if (name.length() > 64) {
+ return false;
+ }
+ if (name.charAt(0) == '-' || name.charAt(name.length() - 1) == '-') {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @param pathElements the string array to create the path from. Order is preserved so
+ * pathElements[0] corresponds to the first element in the path.
+ * @throws AssertionError if the pathElements parameter is null.
+ */
+ public CloudnamePath(final String[] pathElements) {
+ if (pathElements == null) {
+ throw new IllegalArgumentException("Path elements can not be null");
+ }
+ this.pathElements = new String[pathElements.length];
+ for (int i = 0; i < pathElements.length; i++) {
+ if (pathElements[i] == null) {
+ throw new IllegalArgumentException("Path element at index " + i + " is null");
+ }
+ final String element = pathElements[i].toLowerCase();
+ if (!isValidPathElementName(element)) {
+ throw new IllegalArgumentException("Name element " + element + " isn't a valid name");
+ }
+ this.pathElements[i] = element;
+ }
+ }
+
+ /**
+ * Create a new path based on an existing one by appending a new element
+ *
+ * @param path The original CloudnamePath instance
+ * @param additionalElement Element to append to the end of the original path
+ * @throws AssertionError if one or more of the parameters are null
+ */
+ public CloudnamePath(final CloudnamePath path, final String additionalElement) {
+ if (path == null) {
+ throw new IllegalArgumentException("Path can not be null");
+ }
+ if (additionalElement == null) {
+ throw new IllegalArgumentException("additionalElement can not be null");
+ }
+
+ if (!isValidPathElementName(additionalElement)) {
+ throw new IllegalArgumentException(additionalElement + " isn't a valid path name");
+ }
+ this.pathElements = Arrays.copyOf(path.pathElements, path.pathElements.length + 1);
+ this.pathElements[this.pathElements.length - 1] = additionalElement;
+
+ }
+
+ /**
+ * @return the number of elements in the path
+ */
+ public int length() {
+ return pathElements.length;
+ }
+
+ /**
+ * Join the path elements into a string, f.e. join "foo", "bar" into "foo:bar"
+ *
+ * @param separator separator character between elements
+ * @return joined elements
+ */
+ public String join(final char separator) {
+ final StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ for (final String element : pathElements) {
+ if (!first) {
+ sb.append(separator);
+ }
+ sb.append(element);
+ first = false;
+ }
+ return sb.toString();
+ }
+
+ /**
+ * @param index index of element
+ * @return element at index
+ * @throws IndexOutOfBoundsException if the index is out of range
+ */
+ public String get(final int index) {
+ return pathElements[index];
+ }
+
+ /**
+ * Check if this path is a subpath. A path is a subpath whenever it starts with the
+ * same elements as the other path ("foo/bar/baz" would be a subpath of "foo/bar/baz/baz"
+ * but not of "bar/foo")
+ *
+ * @param other Path to check
+ * @return true if this path is a subpath of the specified path
+ */
+ public boolean isSubpathOf(final CloudnamePath other) {
+ if (other == null) {
+ return false;
+ }
+ if (this.pathElements.length > other.pathElements.length) {
+ return false;
+ }
+
+ if (this.pathElements.length == 0) {
+ // This is an empty path. It is the subpath of any other path.
+ return true;
+ }
+
+ for (int i = 0; i < this.pathElements.length; i++) {
+ if (!other.pathElements[i].equals(this.pathElements[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @return parent path of current. If this is the root path (ie it is empty), return the
+ * current path
+ */
+ public CloudnamePath getParent() {
+ if (this.pathElements.length == 0) {
+ return this;
+ }
+ return new CloudnamePath(Arrays.copyOf(pathElements, this.pathElements.length - 1));
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (other == null || !(other instanceof CloudnamePath)) {
+ return false;
+ }
+ final CloudnamePath otherPath = (CloudnamePath) other;
+ if (otherPath.pathElements.length != pathElements.length) {
+ return false;
+ }
+ for (int i = 0; i < pathElements.length; i++) {
+ if (!pathElements[i].equals(otherPath.pathElements[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(pathElements);
+ }
+
+ @Override
+ public String toString() {
+ return "[ CloudnamePath (" + Arrays.toString(pathElements) + ") ]";
+ }
+
+
+}
diff --git a/cn-core/src/main/java/org/cloudname/core/LeaseHandle.java b/cn-core/src/main/java/org/cloudname/core/LeaseHandle.java
new file mode 100644
index 00000000..45b79740
--- /dev/null
+++ b/cn-core/src/main/java/org/cloudname/core/LeaseHandle.java
@@ -0,0 +1,21 @@
+package org.cloudname.core;
+
+/**
+ * Handle returned by the backend when a temporary lease is created.
+ *
+ * @author [email protected]
+ */
+public interface LeaseHandle extends AutoCloseable {
+ /**
+ * Write data to the lease.
+ *
+ * @param data data to write. Cannot be null.
+ * @return true if data is written
+ */
+ boolean writeLeaseData(final String data);
+
+ /**
+ * @return The full path of the lease
+ */
+ CloudnamePath getLeasePath();
+}
\ No newline at end of file
diff --git a/cn-core/src/main/java/org/cloudname/core/LeaseListener.java b/cn-core/src/main/java/org/cloudname/core/LeaseListener.java
new file mode 100644
index 00000000..1586b100
--- /dev/null
+++ b/cn-core/src/main/java/org/cloudname/core/LeaseListener.java
@@ -0,0 +1,31 @@
+package org.cloudname.core;
+
+/**
+ * Lease notifications to clients.
+ *
+ * @author [email protected]
+ */
+public interface LeaseListener {
+ /**
+ * A new lease is created. The lease is created at this point in time.
+ *
+ * @param path The full path of the lease
+ * @param data The data stored on the lease
+ */
+ void leaseCreated(final CloudnamePath path, final String data);
+
+ /**
+ * A lease is removed. The lease might not exist anymore at this point in time.
+ *
+ * @param path The path of the lease.
+ */
+ void leaseRemoved(final CloudnamePath path);
+
+ /**
+ * Lease data have changed in one of the leases the client is listening on.
+ *
+ * @param path Full path to the lease that have changed
+ * @param data The new data element stored in the lease
+ */
+ void dataChanged(final CloudnamePath path, final String data);
+}
diff --git a/cn-core/src/test/java/org/cloudname/core/CloudnamePathTest.java b/cn-core/src/test/java/org/cloudname/core/CloudnamePathTest.java
new file mode 100644
index 00000000..0e6bff9b
--- /dev/null
+++ b/cn-core/src/test/java/org/cloudname/core/CloudnamePathTest.java
@@ -0,0 +1,204 @@
+package org.cloudname.core;
+
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * Test the CloudnamePath class.
+ */
+public class CloudnamePathTest {
+ private final String[] emptyElements = new String[] {};
+ private final String[] oneElement = new String[] { "foo" };
+ private final String[] twoElements = new String[] { "foo", "bar" };
+
+ @Test (expected = IllegalArgumentException.class)
+ public void elementsCantBeNull() {
+ new CloudnamePath(null);
+ fail("No exception, no pass for you!");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void pathCantBeNull() {
+ new CloudnamePath(null, "foof");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void additionalElementCantBeNull() {
+ new CloudnamePath(new CloudnamePath(new String[] { "foo" }), null);
+ }
+
+ @Test
+ public void appendPath() {
+ final CloudnamePath singleElement = new CloudnamePath(new String[] { "one" });
+ final CloudnamePath twoElements = new CloudnamePath(new String[] { "one", "two" });
+ assertThat("Elements aren't equal", singleElement.equals(twoElements), is(false));
+ final CloudnamePath appendedElement = new CloudnamePath(singleElement, "two");
+ assertThat("Appended are equal", appendedElement.equals(twoElements), is(true));
+ }
+
+ @Test
+ public void elementAccess() {
+ final CloudnamePath path = new CloudnamePath(twoElements);
+ assertThat(path.get(0), is(twoElements[0]));
+ assertThat(path.get(1), is(twoElements[1]));
+ }
+
+ @Test (expected = IndexOutOfBoundsException.class)
+ public void elementAccessMustBeWithinBounds() {
+ final CloudnamePath path = new CloudnamePath(twoElements);
+ path.get(2);
+ }
+
+ @Test
+ public void joinPaths() {
+ final CloudnamePath empty = new CloudnamePath(emptyElements);
+ assertThat("The empty path is length = 0", empty.length(), is(0));
+ assertThat("String representation of emmpty path is empty string", empty.join('.'), is(""));
+
+ final CloudnamePath one = new CloudnamePath(oneElement);
+ assertThat("A single element path has length 1", one.length(), is(1));
+ assertThat("String representation of a single element path is the element",
+ one.join('.'), is(oneElement[0]));
+
+ final CloudnamePath two = new CloudnamePath(twoElements);
+ assertThat("Two element paths have length 2", two.length(), is(2));
+ assertThat("String representation of two element paths includes both elements",
+ two.join('.'), is(twoElements[0] + '.' + twoElements[1]));
+ }
+
+ @Test
+ public void equalsTest() {
+ final CloudnamePath twoA = new CloudnamePath(twoElements);
+ final CloudnamePath twoB = new CloudnamePath(twoElements);
+ final CloudnamePath none = new CloudnamePath(emptyElements);
+ final CloudnamePath entirelyDifferent = new CloudnamePath(new String[] { "foo", "2" });
+
+ assertThat("Identical paths are equal", twoA.equals(twoB), is(true));
+ assertThat("Hash codes for equal objects are the same",
+ twoA.hashCode(), is(twoB.hashCode()));
+ assertThat("Identical paths are equal, ignore order", twoB.equals(twoA), is(true));
+ assertThat("Paths aren't equal to strings", twoA.equals(""), is(false));
+ assertThat("Empty path does not equal actual path", twoA.equals(none), is(false));
+ assertThat("Null elements aren't equal", twoA.equals(null), is(false));
+ assertThat("Differen is just different", twoA.equals(entirelyDifferent), is(false));
+ }
+
+ @Test
+ public void subpaths() {
+ final String[] e1 = new String[] { "1", "2", "3", "4" };
+ final String[] e2 = new String[] { "1", "2" };
+
+ final CloudnamePath first = new CloudnamePath(e1);
+ final CloudnamePath second = new CloudnamePath(e2);
+ final CloudnamePath last = new CloudnamePath(twoElements);
+
+
+ assertThat("More specific paths can't be subpaths", first.isSubpathOf(second), is(false));
+ assertThat("More generic paths are subpaths", second.isSubpathOf(first), is(true));
+ assertThat("A path can be subpath of itself", first.isSubpathOf(first), is(true));
+
+ assertThat("Paths must match at root levels", last.isSubpathOf(second), is(false));
+
+ assertThat("Null paths are not subpaths of anything", first.isSubpathOf(null), is(false));
+
+ final CloudnamePath empty = new CloudnamePath(emptyElements);
+ assertThat("An empty path is a subpath of everything", empty.isSubpathOf(first), is(true));
+ assertThat("Empty paths can't have subpaths", first.isSubpathOf(empty), is(false));
+ }
+
+ @Test
+ public void parentPaths() {
+ final CloudnamePath originalPath = new CloudnamePath(new String[] { "foo", "bar", "baz" });
+
+ assertTrue(originalPath.getParent().isSubpathOf(originalPath));
+
+ assertThat(originalPath.getParent(), is(equalTo(
+ new CloudnamePath(new String[] { "foo", "bar" }))));
+
+ assertThat(originalPath.getParent().getParent(),
+ is(equalTo(new CloudnamePath(new String[] { "foo" }))));
+
+ final CloudnamePath emptyPath = new CloudnamePath(new String[] { });
+
+ assertThat(originalPath.getParent().getParent().getParent(),
+ is(equalTo(emptyPath)));
+
+ assertThat(originalPath.getParent().getParent().getParent().getParent(),
+ is(equalTo(emptyPath)));
+
+ assertThat(emptyPath.getParent(), is(equalTo(emptyPath)));
+ }
+ @Test
+ public void testToString() {
+ final CloudnamePath one = new CloudnamePath(oneElement);
+ final CloudnamePath two = new CloudnamePath(twoElements);
+ final CloudnamePath three = new CloudnamePath(emptyElements);
+
+ assertThat(one.toString(), is(notNullValue()));
+ assertThat(two.toString(), is(notNullValue()));
+ assertThat(three.toString(), is(notNullValue()));
+ }
+
+ @Test
+ public void invalidPathNameWithHyphenFirst() {
+ assertThat(CloudnamePath.isValidPathElementName("-invalid"), is(false));
+ }
+
+ @Test
+ public void invalidPathNameIsNull() {
+ assertThat(CloudnamePath.isValidPathElementName(null), is(false));
+ }
+ @Test
+ public void invalidPathNameWithHyphenLast() {
+ assertThat(CloudnamePath.isValidPathElementName("invalid-"), is(false));
+ }
+
+ @Test
+ public void invalidPathNameWithEmptyString() {
+ assertThat(CloudnamePath.isValidPathElementName(""), is(false));
+ }
+
+ @Test
+ public void invalidPathNameWithIllegalChars() {
+ assertThat(CloudnamePath.isValidPathElementName("__"), is(false));
+ }
+
+ @Test
+ public void invalidPathNameWithTooLongLabel() {
+ assertThat(CloudnamePath.isValidPathElementName(
+ "rindfleischetikettierungsueberwachungsaufgabenuebertragungsgesetz"), is(false));
+ }
+
+ @Test
+ public void labelNamesAreCaseInsensitive() {
+ final CloudnamePath one = new CloudnamePath(new String[] { "FirstSecond" });
+ final CloudnamePath two = new CloudnamePath(new String[] { "fIRSTsECOND" });
+ assertTrue("Label names aren't case sensitive", one.equals(two));
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void pathCanNotBeNull() {
+ new CloudnamePath(null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void pathElementsCanNotBeNull() {
+ new CloudnamePath(new String[] { null, null });
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void pathElementNamesCanNotBeInvalid() {
+ new CloudnamePath(new String[] { "__", "foo", "bar"});
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void additionalElementsMustBeValid() {
+ new CloudnamePath(new CloudnamePath(new String[] { "foo" }), "__");
+ }
+}
diff --git a/cn-memory/README.md b/cn-memory/README.md
new file mode 100644
index 00000000..bea9e848
--- /dev/null
+++ b/cn-memory/README.md
@@ -0,0 +1,4 @@
+# Memory-based backend
+
+This backend is only suitable for testing. It will only work in a single
+VM.
diff --git a/cn-memory/pom.xml b/cn-memory/pom.xml
new file mode 100644
index 00000000..ea56d0c7
--- /dev/null
+++ b/cn-memory/pom.xml
@@ -0,0 +1,57 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cloudname-parent</artifactId>
+ <version>3.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>cn-memory</artifactId>
+ <packaging>jar</packaging>
+
+ <name>Cloudname Memory backend</name>
+ <description>Memory backend for Cloudname</description>
+ <url>https://github.com/Cloudname/cloudname</url>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cn-core</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-all</artifactId>
+ <version>1.3</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>testtools</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+
+ </plugins>
+ </build>
+</project>
diff --git a/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryBackend.java b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryBackend.java
new file mode 100644
index 00000000..0a869de6
--- /dev/null
+++ b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryBackend.java
@@ -0,0 +1,270 @@
+package org.cloudname.backends.memory;
+
+import org.cloudname.core.CloudnameBackend;
+import org.cloudname.core.CloudnamePath;
+import org.cloudname.core.LeaseHandle;
+import org.cloudname.core.LeaseListener;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+
+/**
+ * Memory backend. This is the canonical implementation. The synchronization is probably not
+ * optimal but for testing this is OK. It defines the correct behaviour for backends, including
+ * calling listeners, return values and uniqueness. The actual timing of the various backends
+ * will of course vary.
+ *
+ * @author [email protected]
+ */
+public class MemoryBackend implements CloudnameBackend {
+ private enum LeaseEvent {
+ CREATED,
+ REMOVED,
+ DATA
+ }
+
+ private final Map<CloudnamePath,String> temporaryLeases = new HashMap<>();
+ private final Map<CloudnamePath,String> permanentLeases = new HashMap<>();
+ private final Map<CloudnamePath, Set<LeaseListener>> observedTemporaryPaths = new HashMap<>();
+ private final Map<CloudnamePath, Set<LeaseListener>> observedPermanentPaths = new HashMap<>();
+ private final Object syncObject = new Object();
+
+ /* package-private */ void removeTemporaryLease(final CloudnamePath leasePath) {
+ synchronized (syncObject) {
+ if (temporaryLeases.containsKey(leasePath)) {
+ temporaryLeases.remove(leasePath);
+ notifyTemporaryObservers(leasePath, LeaseEvent.REMOVED, null);
+ }
+ }
+ }
+ private final Random random = new Random();
+
+ private String createRandomInstanceName() {
+ return Long.toHexString(random.nextLong());
+ }
+
+ /**
+ * @param path The path that has changed
+ * @param event The event
+ * @param data The data
+ */
+ private void notifyTemporaryObservers(
+ final CloudnamePath path, final LeaseEvent event, final String data) {
+ for (final CloudnamePath observedPath : observedTemporaryPaths.keySet()) {
+ if (observedPath.isSubpathOf(path)) {
+ for (final LeaseListener listener : observedTemporaryPaths.get(observedPath)) {
+ switch (event) {
+ case CREATED:
+ listener.leaseCreated(path, data);
+ break;
+ case REMOVED:
+ listener.leaseRemoved(path);
+ break;
+ case DATA:
+ listener.dataChanged(path, data);
+ break;
+ default:
+ throw new RuntimeException("Don't know how to handle " + event);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Notify observers of changes
+ */
+ private void notifyPermanentObservers(
+ final CloudnamePath path, final LeaseEvent event, final String data) {
+ for (final CloudnamePath observedPath : observedPermanentPaths.keySet()) {
+ if (observedPath.isSubpathOf(path)) {
+ for (final LeaseListener listener : observedPermanentPaths.get(observedPath)) {
+ switch (event) {
+ case CREATED:
+ listener.leaseCreated(path, data);
+ break;
+ case REMOVED:
+ listener.leaseRemoved(path);
+ break;
+ case DATA:
+ listener.dataChanged(path, data);
+ break;
+ default:
+ throw new RuntimeException("Don't know how to handle " + event);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public boolean createPermanantLease(final CloudnamePath path, final String data) {
+ assert path != null : "Path to lease must be set!";
+ assert data != null : "Lease data is required";
+ synchronized (syncObject) {
+ if (permanentLeases.containsKey(path)) {
+ return false;
+ }
+ permanentLeases.put(path, data);
+ notifyPermanentObservers(path, LeaseEvent.CREATED, data);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean removePermanentLease(final CloudnamePath path) {
+ synchronized (syncObject) {
+ if (!permanentLeases.containsKey(path)) {
+ return false;
+ }
+ permanentLeases.remove(path);
+ notifyPermanentObservers(path, LeaseEvent.REMOVED, null);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean writePermanentLeaseData(final CloudnamePath path, String data) {
+ synchronized (syncObject) {
+ if (!permanentLeases.containsKey(path)) {
+ return false;
+ }
+ permanentLeases.put(path, data);
+ notifyPermanentObservers(path, LeaseEvent.DATA, data);
+ }
+ return true;
+ }
+
+ @Override
+ public String readPermanentLeaseData(final CloudnamePath path) {
+ synchronized (syncObject) {
+ if (!permanentLeases.containsKey(path)) {
+ return null;
+ }
+ return permanentLeases.get(path);
+ }
+ }
+
+ @Override
+ public boolean writeTemporaryLeaseData(final CloudnamePath path, String data) {
+ synchronized (syncObject) {
+ if (!temporaryLeases.containsKey(path)) {
+ return false;
+ }
+ temporaryLeases.put(path, data);
+ notifyTemporaryObservers(path, LeaseEvent.DATA, data);
+ }
+ return true;
+ }
+
+ @Override
+ public String readTemporaryLeaseData(final CloudnamePath path) {
+ synchronized (syncObject) {
+ if (!temporaryLeases.containsKey(path)) {
+ return null;
+ }
+ return temporaryLeases.get(path);
+ }
+ }
+
+ @Override
+ public LeaseHandle createTemporaryLease(final CloudnamePath path, final String data) {
+ synchronized (syncObject) {
+ final String instanceName = createRandomInstanceName();
+ CloudnamePath instancePath = new CloudnamePath(path, instanceName);
+ while (temporaryLeases.containsKey(instancePath)) {
+ instancePath = new CloudnamePath(path, instanceName);
+ }
+ temporaryLeases.put(instancePath, data);
+ notifyTemporaryObservers(instancePath, LeaseEvent.CREATED, data);
+ return new MemoryLeaseHandle(this, instancePath);
+ }
+ }
+
+ /**
+ * Generate created events for temporary leases for newly attached listeners.
+ */
+ private void regenerateEventsForTemporaryListener(
+ final CloudnamePath path, final LeaseListener listener) {
+ for (final CloudnamePath temporaryPath : temporaryLeases.keySet()) {
+ if (path.isSubpathOf(temporaryPath)) {
+ listener.leaseCreated(temporaryPath, temporaryLeases.get(temporaryPath));
+ }
+ }
+ }
+
+ /**
+ * Generate created events on permanent leases for newly attached listeners.
+ */
+ private void regenerateEventsForPermanentListener(
+ final CloudnamePath path, final LeaseListener listener) {
+ for (final CloudnamePath permanentPath : permanentLeases.keySet()) {
+ if (path.isSubpathOf(permanentPath)) {
+ listener.leaseCreated(permanentPath, permanentLeases.get(permanentPath));
+ }
+ }
+ }
+
+ @Override
+ public void addTemporaryLeaseListener(
+ final CloudnamePath pathToObserve, final LeaseListener listener) {
+ synchronized (syncObject) {
+ Set<LeaseListener> listeners = observedTemporaryPaths.get(pathToObserve);
+ if (listeners == null) {
+ listeners = new HashSet<>();
+ }
+ listeners.add(listener);
+ observedTemporaryPaths.put(pathToObserve, listeners);
+ regenerateEventsForTemporaryListener(pathToObserve, listener);
+ }
+ }
+
+ @Override
+ public void removeTemporaryLeaseListener(final LeaseListener listener) {
+ synchronized (syncObject) {
+ for (final Set<LeaseListener> listeners : observedTemporaryPaths.values()) {
+ if (listeners.contains(listener)) {
+ listeners.remove(listener);
+ return;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void addPermanentLeaseListener(
+ final CloudnamePath pathToObserve, final LeaseListener listener) {
+ synchronized (syncObject) {
+ Set<LeaseListener> listeners = observedPermanentPaths.get(pathToObserve);
+ if (listeners == null) {
+ listeners = new HashSet<>();
+ }
+ listeners.add(listener);
+ observedPermanentPaths.put(pathToObserve, listeners);
+ regenerateEventsForPermanentListener(pathToObserve, listener);
+ }
+ }
+
+ @Override
+ public void removePermanentLeaseListener(final LeaseListener listener) {
+ synchronized (syncObject) {
+ for (final Set<LeaseListener> listeners : observedPermanentPaths.values()) {
+ if (listeners.contains(listener)) {
+ listeners.remove(listener);
+ return;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void close() {
+ synchronized (syncObject) {
+ observedTemporaryPaths.clear();
+ observedPermanentPaths.clear();
+ }
+ }
+}
diff --git a/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryLeaseHandle.java b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryLeaseHandle.java
new file mode 100644
index 00000000..53b1e277
--- /dev/null
+++ b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryLeaseHandle.java
@@ -0,0 +1,47 @@
+package org.cloudname.backends.memory;
+
+import org.cloudname.core.CloudnamePath;
+import org.cloudname.core.LeaseHandle;
+
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * A handle returned to clients acquiring temporary leases.
+ *
+ * @author [email protected]
+ */
+public class MemoryLeaseHandle implements LeaseHandle {
+ private final MemoryBackend backend;
+ private final CloudnamePath clientLeasePath;
+ private AtomicBoolean expired = new AtomicBoolean(false);
+
+ /**
+ * @param backend The backend issuing the lease
+ * @param clientLeasePath The path to the lease
+ */
+ public MemoryLeaseHandle(final MemoryBackend backend, final CloudnamePath clientLeasePath) {
+ this.backend = backend;
+ this.clientLeasePath = clientLeasePath;
+ expired.set(false);
+ }
+
+ @Override
+ public boolean writeLeaseData(String data) {
+ return backend.writeTemporaryLeaseData(clientLeasePath, data);
+ }
+
+ @Override
+ public CloudnamePath getLeasePath() {
+ if (expired.get()) {
+ return null;
+ }
+ return clientLeasePath;
+ }
+
+ @Override
+ public void close() throws IOException {
+ backend.removeTemporaryLease(clientLeasePath);
+ expired.set(true);
+ }
+}
diff --git a/cn-memory/src/test/java/org/cloudname/backends/memory/MemoryBackendTest.java b/cn-memory/src/test/java/org/cloudname/backends/memory/MemoryBackendTest.java
new file mode 100644
index 00000000..acc1ad8e
--- /dev/null
+++ b/cn-memory/src/test/java/org/cloudname/backends/memory/MemoryBackendTest.java
@@ -0,0 +1,18 @@
+package org.cloudname.backends.memory;
+
+import org.cloudname.core.CloudnameBackend;
+import org.cloudname.testtools.backend.CoreBackendTest;
+
+/**
+ * Test the memory backend. Since the memory backend is the reference implementation this test
+ * shouldn't fail. Ever.
+ */
+public class MemoryBackendTest extends CoreBackendTest {
+ private static final CloudnameBackend BACKEND = new MemoryBackend();
+
+ @Override
+ protected CloudnameBackend getBackend() {
+ return BACKEND;
+ }
+
+}
diff --git a/cn-service/README.md b/cn-service/README.md
new file mode 100644
index 00000000..8cf7df15
--- /dev/null
+++ b/cn-service/README.md
@@ -0,0 +1,107 @@
+# Cloudname service discovery
+
+## Coordinates
+Each service that runs is represented by a **coordinate**. There are two kinds of coordinates:
+* **Service coordinates** which are generic coordinates that points to one or more services
+* **Instance coordinates** which points to a particular service
+
+Coordinates are specified through **regions** and **tags**. A **region** is a separate (logical) cluster of services. One region is usually not connected to another region. The simplest comparison is either a *data center* or an AWS *region* or *availability zone* (like eu-west-1, us-east-1 and so on).
+
+The **tag** is just that - a tag that you can assign to a cluster of different services. The tag doesn't contain any particular semantics.
+
+A **service coordinate** looks like `<service>.<tag>.<region>`, f.e. `geolocation.rel1501.dc1` or (if you are running in AWS and have decided that you'll assume regions are availability zones) `geolocation.rel1501.eu-west-1a`.
+
+Instance coordinates points to a particular service instance and looks like this: `<instance identifier>.<service name>.<tag>.<region>`. For the examples above the instance coordinates might look like `ff08f0ah.geolocation.rel1501.dc1` or `ab08bed5.geolocation.rel1501.eu-west-1a`.
+
+The instance identifier is an unique identifier for that instance. Note that the instance identifier isn't unique across all services, isn't sequential and does not carry any semantic information.
+
+## Register a service
+A service is registered through the `CloudnameService` class:
+```java
+// Create the service class. Note that getBackend() returns a Cloudname backend
+// instance. There ar multiple types available.
+try (CloudnameService cloudnameService = new CloudnameService(getBackend())) {
+ // Create the coordinate and endpoint
+ ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse("myservice.demo.local");
+ Endpoint httpEndpoint = new Endpoint("http", "127.0.0.1", 80);
+
+ ServiceData serviceData = new ServiceData(Arrays.asList(httpEndpoint));
+
+ // This will register the service. The returned handle will expose the registration
+ // to other clients until it is closed.
+ try (ServiceHandle handle = cloudnameService.registerService(serviceCoordinate, serviceData)) {
+
+ // ...Run your service here
+
+ }
+}
+```
+
+## Looking up services
+Services can be located without registering a service; supply a listener to the CloudnameService instance to get notified of new services:
+```java
+CloudnameService cloudnameService = new CloudnameService(getBackend());
+ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse("myservice.demo.local");
+cloudnameService.addServiceListener(ServiceCoordinate, new ServiceListener() {
+ @Override
+ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) {
+ // A new instance is launched. Retrieve the endpoints via the data parameter.
+ // Note that this method is also called when the listener is set so you'll
+ // get notifications on already existing services as well.
+ }
+
+ @Override
+ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) {
+ // There's a change in endpoints for the given instance. The updated endpoints
+ // are supplied in the data parameter
+ }
+
+ @Override
+ public void onServiceRemoved(final InstanceCoordinate coordinate) {
+ // One of the instances is stopped. It might become unavailable shortly
+ // (or it might have terminated)
+ }
+});
+```
+
+## Permanent services
+Some resources might not be suitable for service discovery, either because they are not under your control, they are pet services or not designed for cloud-like behavior (aka "pet servers"). You can still use those in service discovery; just add them as *permanent services*. Permanent services behave a bit differently from ordinary services; they stay alive for long periods of time and on some rare occasions they change their endpoint. Registering permanent services are similar to ordinary services. The following snippet registers a permanent service, then terminates. The service registration will still be available to other clients when this client has terminated:
+
+```java
+try (CloudnameService cloudnameService = new CloudnameService(getBackend())) {
+ ServiceCoordinate coordinate = ServiceCoordinate.parse("mydb.demo.local");
+ Endpoint endpoint = new Endpoint("db", "127.0.0.1", 5678);
+
+ if (!cloudnameService.createPermanentService(coordinate, endpoint)) {
+ System.out.println("Couldn't register permanent service!");
+ }
+}
+```
+Note that permanent services can not have more than one endpoint registered at any time. A permanent service registration applies only to *one* service at a time.
+
+Looking up permanent service registrations is similar to ordinary services:
+
+```java
+try (CloudnameService cloudnameService = new CloudnameService(getBackend())) {
+ ServiceCoordinate coordinate = ServiceCoordinate.parse("mydb.demo.local");
+ cloudnameService.addPermanentServiceListener(coordinate,
+ new PermanentServiceListener() {
+ @Override
+ public void onServiceCreated(Endpoint endpoint) {
+ // Service is created. Note that this is also called when the
+ // listener is set so you'll get notifications on already
+ // existing services as well.
+ }
+
+ @Override
+ public void onServiceChanged(Endpoint endpoint) {
+ // The endpoint is updated
+ }
+
+ @Override
+ public void onServiceRemoved() {
+ // The service has been removed
+ }
+ });
+}
+```
diff --git a/cn-service/pom.xml b/cn-service/pom.xml
new file mode 100644
index 00000000..f3788ed2
--- /dev/null
+++ b/cn-service/pom.xml
@@ -0,0 +1,63 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cloudname-parent</artifactId>
+ <version>3.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>cn-service</artifactId>
+ <packaging>jar</packaging>
+
+ <name>Cloudname Service Discovery</name>
+ <description>Simple library for service discovery (and notifications)</description>
+ <url>https://github.com/Cloudname/cloudname</url>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cn-core</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-all</artifactId>
+ <version>1.3</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ <version>20140107</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cn-memory</artifactId>
+ <scope>test</scope>
+
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+
+ </plugins>
+ </build>
+</project>
diff --git a/cn-service/src/main/java/org/cloudname/service/CloudnameService.java b/cn-service/src/main/java/org/cloudname/service/CloudnameService.java
new file mode 100644
index 00000000..9c4747f4
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/CloudnameService.java
@@ -0,0 +1,237 @@
+package org.cloudname.service;
+import org.cloudname.core.CloudnameBackend;
+import org.cloudname.core.CloudnamePath;
+import org.cloudname.core.LeaseHandle;
+import org.cloudname.core.LeaseListener;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Service discovery implementation. Use registerService() and addServiceListener() to register
+ * and locate services.
+ *
+ * TODO: Enable lookups based on partial coordinates. Create builder for service coordinates,
+ * use own coordinate to resolve complete coordinate.
+ *
+ * @author [email protected]
+ */
+public class CloudnameService implements AutoCloseable {
+ private final Logger LOG = Logger.getLogger(CloudnameService.class.getName());
+
+ private final CloudnameBackend backend;
+ private final List<ServiceHandle> handles = new ArrayList<>();
+ private final List<LeaseListener> temporaryListeners = new ArrayList<>();
+ private final List<LeaseListener> permanentListeners = new ArrayList<>();
+ private final Set<ServiceCoordinate> permanentUpdatesInProgress = new CopyOnWriteArraySet<>();
+ private final Object syncObject = new Object();
+
+ /**
+ * @oaram backend backend implementation to use
+ * @throws IllegalArgumentException if parameter is invalid
+ */
+ public CloudnameService(final CloudnameBackend backend) {
+ if (backend == null) {
+ throw new IllegalArgumentException("Backend can not be null");
+ }
+ this.backend = backend;
+ }
+
+ /**
+ * Register an instance with the given service coordinate. The service will get its own
+ * instance coordinate under the given service coordinate.
+ *
+ * @param serviceCoordinate The service coordinate that the service (instance) will attach to
+ * @param serviceData Service data for the instance
+ * @return ServiceHandle a handle the client can use to manage the endpoints for the service.
+ * The most typical use case is to register all endpoints
+ * @throws IllegalArgumentException if the parameters are invalid
+ */
+ public ServiceHandle registerService(
+ final ServiceCoordinate serviceCoordinate, final ServiceData serviceData) {
+
+ if (serviceCoordinate == null) {
+ throw new IllegalArgumentException("Coordinate cannot be null");
+ }
+ if (serviceData == null) {
+ throw new IllegalArgumentException("Service Data cannot be null");
+ }
+ final LeaseHandle leaseHandle = backend.createTemporaryLease(
+ serviceCoordinate.toCloudnamePath(), serviceData.toJsonString());
+
+ final ServiceHandle serviceHandle = new ServiceHandle(
+ new InstanceCoordinate(leaseHandle.getLeasePath()), serviceData, leaseHandle);
+
+ synchronized (syncObject) {
+ handles.add(serviceHandle);
+ }
+ return serviceHandle;
+ }
+
+ /**
+ * Add listener for service events. This only applies to ordinary services.
+ *
+ * @param coordinate The coordinate to monitor.
+ * @param listener Listener getting notifications on changes.
+ * @throws IllegalArgumentException if parameters are invalid
+ */
+ public void addServiceListener(
+ final ServiceCoordinate coordinate, final ServiceListener listener) {
+ if (coordinate == null) {
+ throw new IllegalArgumentException("Coordinate can not be null");
+ }
+ if (listener == null) {
+ throw new IllegalArgumentException("Listener can not be null");
+ }
+ // Just create the corresponding listener on the backend and translate the parameters
+ // from the listener.
+ final LeaseListener leaseListener = new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ final InstanceCoordinate instanceCoordinate = new InstanceCoordinate(path);
+ final ServiceData serviceData = ServiceData.fromJsonString(data);
+ listener.onServiceCreated(instanceCoordinate, serviceData);
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ final InstanceCoordinate instanceCoordinate = new InstanceCoordinate(path);
+ listener.onServiceRemoved(instanceCoordinate);
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ final InstanceCoordinate instanceCoordinate = new InstanceCoordinate(path);
+ final ServiceData serviceData = ServiceData.fromJsonString(data);
+ listener.onServiceDataChanged(instanceCoordinate, serviceData);
+ }
+ };
+ synchronized (syncObject) {
+ temporaryListeners.add(leaseListener);
+ }
+ backend.addTemporaryLeaseListener(coordinate.toCloudnamePath(), leaseListener);
+ }
+
+ /**
+ * Create a permanent service. The service registration will be kept when the client exits. The
+ * service will have a single endpoint.
+ */
+ public boolean createPermanentService(
+ final ServiceCoordinate coordinate, final Endpoint endpoint) {
+ if (coordinate == null) {
+ throw new IllegalArgumentException("Service coordinate can't be null");
+ }
+ if (endpoint == null) {
+ throw new IllegalArgumentException("Endpoint can't be null");
+ }
+
+ return backend.createPermanantLease(coordinate.toCloudnamePath(), endpoint.toJsonString());
+ }
+
+ /**
+ * Update permanent service coordinate. Note that this is a non-atomic operation with multiple
+ * trips to the backend system. The update is done in two operations; one delete and one
+ * create. If the delete operation fail and the create operation succeeds it might end up
+ * removing the permanent service coordinate. Clients will not be notified of the removal.
+ */
+ public boolean updatePermanentService(
+ final ServiceCoordinate coordinate, final Endpoint endpoint) {
+ if (coordinate == null) {
+ throw new IllegalArgumentException("Coordinate can't be null");
+ }
+ if (endpoint == null) {
+ throw new IllegalArgumentException("Endpoint can't be null");
+ }
+
+ if (permanentUpdatesInProgress.contains(coordinate)) {
+ LOG.log(Level.WARNING, "Attempt to update a permanent service which is already"
+ + " updating. (coordinate: " + coordinate + ", endpoint: " + endpoint);
+ return false;
+ }
+ // Check if the endpoint name still matches.
+ final String data = backend.readPermanentLeaseData(coordinate.toCloudnamePath());
+ if (data == null) {
+ return false;
+ }
+ final Endpoint oldEndpoint = Endpoint.fromJson(data);
+ if (!oldEndpoint.getName().equals(endpoint.getName())) {
+ LOG.log(Level.INFO, "Rejecting attempt to update permanent service with a new endpoint"
+ + " that has a different name. Old name: " + oldEndpoint + " new: " + endpoint);
+ return false;
+ }
+ permanentUpdatesInProgress.add(coordinate);
+ try {
+ return backend.writePermanentLeaseData(
+ coordinate.toCloudnamePath(), endpoint.toJsonString());
+ } catch (final RuntimeException ex) {
+ LOG.log(Level.WARNING, "Got exception updating permanent lease. The system might be in"
+ + " an indeterminate state", ex);
+ return false;
+ } finally {
+ permanentUpdatesInProgress.remove(coordinate);
+ }
+ }
+
+ /**
+ * Remove a perviously registered permanent service. Needless to say: Use with caution.
+ */
+ public boolean removePermanentService(final ServiceCoordinate coordinate) {
+ if (coordinate == null) {
+ throw new IllegalArgumentException("Coordinate can not be null");
+ }
+ return backend.removePermanentLease(coordinate.toCloudnamePath());
+ }
+
+ /**
+ * Listen for changes in permanent services. The changes are usually of the earth-shattering
+ * variety so as a client you'd be interested in knowing about these as soon as possible.
+ */
+ public void addPermanentServiceListener(
+ final ServiceCoordinate coordinate, final PermanentServiceListener listener) {
+ if (coordinate == null) {
+ throw new IllegalArgumentException("Coordinate can not be null");
+ }
+ if (listener == null) {
+ throw new IllegalArgumentException("Listener can not be null");
+ }
+ final LeaseListener leaseListener = new LeaseListener() {
+ @Override
+ public void leaseCreated(CloudnamePath path, String data) {
+ listener.onServiceCreated(Endpoint.fromJson(data));
+ }
+
+ @Override
+ public void leaseRemoved(CloudnamePath path) {
+ listener.onServiceRemoved();
+ }
+
+ @Override
+ public void dataChanged(CloudnamePath path, String data) {
+ listener.onServiceChanged(Endpoint.fromJson(data));
+ }
+ };
+ synchronized (syncObject) {
+ permanentListeners.add(leaseListener);
+ }
+ backend.addPermanentLeaseListener(coordinate.toCloudnamePath(), leaseListener);
+ }
+
+ @Override
+ public void close() {
+ synchronized (syncObject) {
+ for (final ServiceHandle handle : handles) {
+ handle.close();
+ }
+ for (final LeaseListener listener : temporaryListeners) {
+ backend.removeTemporaryLeaseListener(listener);
+ }
+ for (final LeaseListener listener : permanentListeners) {
+ backend.removePermanentLeaseListener(listener);
+ }
+ }
+ }
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/Endpoint.java b/cn-service/src/main/java/org/cloudname/service/Endpoint.java
new file mode 100644
index 00000000..d20371fd
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/Endpoint.java
@@ -0,0 +1,114 @@
+package org.cloudname.service;
+
+import org.cloudname.core.CloudnamePath;
+import org.json.JSONObject;
+
+/**
+ * Endpoints exposed by services. Endpoints contains host address and port number.
+ *
+ * @author [email protected]
+ */
+public class Endpoint {
+ private final String name;
+ private final String host;
+ private final int port;
+
+ /**
+ * @param name Name of endpoint. Must conform to RFC 952 and RFC 1123,
+ * ie [a-z,0-9,-]
+ * @param host Host name or IP address
+ * @param port Port number (1- max port number)
+ * @throws IllegalArgumentException if one of the parameters are null (name/host) or zero (port)
+ */
+ public Endpoint(final String name, final String host, final int port) {
+ if (name == null || name.isEmpty()) {
+ throw new IllegalArgumentException("Name can not be null or empty");
+ }
+ if (host == null || host.isEmpty()) {
+ throw new IllegalArgumentException("Host can not be null or empty");
+ }
+ if (port < 1) {
+ throw new IllegalArgumentException("Port can not be < 1");
+ }
+ if (!CloudnamePath.isValidPathElementName(name)) {
+ throw new IllegalArgumentException("Name is not a valid identifier");
+ }
+
+ this.name = name;
+ this.host = host;
+ this.port = port;
+ }
+
+ /**
+ * @return The endpoint's name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @return The endpoint's host name or IP address
+ */
+ public String getHost() {
+ return host;
+ }
+
+ /**
+ * @return The endpoint's port number
+ */
+ public int getPort() {
+ return port;
+ }
+
+ /**
+ * @return JSON representation of isntance
+ */
+ /* package-private */ String toJsonString() {
+ return new JSONObject()
+ .put("name", name)
+ .put("host", host)
+ .put("port", port)
+ .toString();
+ }
+
+ /**
+ * @param jsonString String with JSON representation of instance
+ * @return Endpoint instance
+ * @throws org.json.JSONException if the string is malformed.
+ */
+ /* package-private */ static Endpoint fromJson(final String jsonString) {
+ final JSONObject json = new JSONObject(jsonString);
+ return new Endpoint(
+ json.getString("name"),
+ json.getString("host"),
+ json.getInt("port"));
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (o == null || !(o instanceof Endpoint)) {
+ return false;
+ }
+ final Endpoint other = (Endpoint) o;
+
+ if (!this.name.equals(other.name)
+ || !this.host.equals(other.host)
+ || this.port != other.port) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return this.toString().hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "[ name = " + name
+ + ", host = " + host
+ + ", port = " + port
+ + "]";
+ }
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/InstanceCoordinate.java b/cn-service/src/main/java/org/cloudname/service/InstanceCoordinate.java
new file mode 100644
index 00000000..7d219357
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/InstanceCoordinate.java
@@ -0,0 +1,146 @@
+package org.cloudname.service;
+
+import org.cloudname.core.CloudnamePath;
+import org.json.JSONObject;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A coordinate representing a running service. The coordinate consists of four parts; instance id,
+ * service name, tag and region.
+ *
+ * Note that the order of elements in the string representation is opposite of the CloudnamePath
+ * class; you can't create a canonical representation of the instance coordinate by calling join()
+ * on the CloudnamePath instance.
+ *
+ * @author [email protected]
+ */
+public class InstanceCoordinate {
+ private static final Pattern COORDINATE_PATTERN = Pattern.compile("(.*)\\.(.*)\\.(.*)\\.(.*)");
+ private static final String REGION_NAME = "region";
+ private static final String TAG_NAME = "tag";
+ private static final String SERVICE_NAME = "service";
+ private static final String INSTANCE_NAME = "instance";
+
+
+ private final String region;
+ private final String tag;
+ private final String service;
+ private final String instance;
+
+ /**
+ * @param path CloudnamePath instance to use as source
+ * @throws IllegalArgumentException if parameters are invalid
+ */
+ /* package-private */ InstanceCoordinate(final CloudnamePath path) {
+ if (path == null) {
+ throw new IllegalArgumentException("Path can not be null");
+ }
+ if (path.length() != 4) {
+ throw new IllegalArgumentException("Path must contain 4 elements");
+ }
+ this.region = path.get(0);
+ this.tag = path.get(1);
+ this.service = path.get(2);
+ this.instance = path.get(3);
+ }
+
+ /**
+ * @return The region of the coordinate
+ */
+ public String getRegion() {
+ return region;
+ }
+
+ /**
+ * @return The tag of the coordinate
+ */
+ public String getTag() {
+ return tag;
+ }
+
+ /**
+ * @return The service name
+ */
+ public String getService() {
+ return service;
+ }
+
+ /**
+ * @return The instance identifier
+ */
+ public String getInstance() {
+ return instance;
+ }
+
+ /**
+ * @return A CloudnamePath instance representing this coordinate
+ */
+ /* package-private */ CloudnamePath toCloudnamePath() {
+ return new CloudnamePath(
+ new String[] { this.region, this.tag, this.service, this.instance });
+ }
+
+ /**
+ * @return Canonical string representation of coordinate
+ */
+ public String toCanonicalString() {
+ return new StringBuffer()
+ .append(instance).append(".")
+ .append(service).append(".")
+ .append(tag).append(".")
+ .append(region)
+ .toString();
+ }
+
+ /**
+ * @return Coordinate represented as a JSON-formatted string
+ */
+ /* package-private */ String toJsonString() {
+ return new JSONObject()
+ .put(REGION_NAME, this.region)
+ .put(TAG_NAME, this.tag)
+ .put(SERVICE_NAME, this.service)
+ .put(INSTANCE_NAME, this.instance)
+ .toString();
+ }
+
+ /**
+ * @param jsonString A coordinate serialized as a JSON-formatted string
+ * @return InstanceCoordinate built from the string
+ */
+ /* package-private */ static InstanceCoordinate fromJson(final String jsonString) {
+ final JSONObject object = new JSONObject(jsonString);
+ final String[] pathElements = new String[4];
+ pathElements[0] = object.getString(REGION_NAME);
+ pathElements[1] = object.getString(TAG_NAME);
+ pathElements[2] = object.getString(SERVICE_NAME);
+ pathElements[3] = object.getString(INSTANCE_NAME);
+
+ return new InstanceCoordinate(new CloudnamePath(pathElements));
+ }
+
+ /**
+ * @param string A canonical string representation of a coordinate
+ * @return InstanceCoordinate built from the string
+ */
+ public static InstanceCoordinate parse(final String string) {
+ if (string == null) {
+ return null;
+ }
+ final Matcher matcher = COORDINATE_PATTERN.matcher(string);
+ if (!matcher.matches()) {
+ return null;
+ }
+ final String[] path = new String[] {
+ matcher.group(4), matcher.group(3), matcher.group(2), matcher.group(1)
+ };
+ return new InstanceCoordinate(new CloudnamePath(path));
+ }
+
+ @Override
+ public String toString() {
+ return "[ Coordinate " + toCanonicalString() + "]";
+ }
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/PermanentServiceListener.java b/cn-service/src/main/java/org/cloudname/service/PermanentServiceListener.java
new file mode 100644
index 00000000..5d644b89
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/PermanentServiceListener.java
@@ -0,0 +1,25 @@
+package org.cloudname.service;
+
+/**
+ * Listener interface for permanent services.
+ *
+ * @author [email protected]
+ */
+public interface PermanentServiceListener {
+ /**
+ * A service is created. This method will be called on start-up for all existing services.
+ * @param endpoint The endpoint of the service
+ */
+ void onServiceCreated(final Endpoint endpoint);
+
+ /**
+ * Service endpoint has changed.
+ * @param endpoint The new value of the service endpoint
+ */
+ void onServiceChanged(final Endpoint endpoint);
+
+ /**
+ * Service has been removed.
+ */
+ void onServiceRemoved();
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceCoordinate.java b/cn-service/src/main/java/org/cloudname/service/ServiceCoordinate.java
new file mode 100644
index 00000000..02a74637
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/ServiceCoordinate.java
@@ -0,0 +1,107 @@
+package org.cloudname.service;
+
+import org.cloudname.core.CloudnamePath;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A coordinate pointing to a set of services or a single permanent service.
+ *
+ * @author [email protected]
+ */
+public class ServiceCoordinate {
+ private final String region;
+ private final String tag;
+ private final String service;
+
+ // Pattern for string parsing
+ private static final Pattern COORDINATE_PATTERN = Pattern.compile("(.*)\\.(.*)\\.(.*)");
+
+ /**
+ * @param path The CloudnamePath instance to use when building the coordinate. The coordinate
+ * must consist of three elements and can not be null.
+ * @throws IllegalArgumentException if parameter is invalid
+ */
+ /* package-private */ ServiceCoordinate(final CloudnamePath path) {
+ if (path == null) {
+ throw new IllegalArgumentException("Path can not be null");
+ }
+ if (path.length() != 3) {
+ throw new IllegalArgumentException("Path must have three elements");
+ }
+ region = path.get(0);
+ tag = path.get(1);
+ service = path.get(2);
+ }
+
+ /**
+ * @return The coordinate's region
+ */
+ public String getRegion() {
+ return region;
+ }
+
+ /**
+ * @return The coordinate's tag
+ */
+ public String getTag() {
+ return tag;
+ }
+
+ /**
+ * @return The coordinate's service name
+ */
+ public String getService() {
+ return service;
+ }
+
+ /**
+ * @param serviceCoordinateString String representation of coordinate
+ * @return ServiceCoordinate instance built from the string. Null if the coordinate
+ * can't be parsed correctly.
+ */
+ public static ServiceCoordinate parse(final String serviceCoordinateString) {
+ final Matcher matcher = COORDINATE_PATTERN.matcher(serviceCoordinateString);
+ if (!matcher.matches()) {
+ return null;
+ }
+ final String[] path = new String[] { matcher.group(3), matcher.group(2), matcher.group(1) };
+ return new ServiceCoordinate(new CloudnamePath(path));
+ }
+
+ /**
+ * @return CloudnamePath representing this coordinate
+ */
+ /* package-private */ CloudnamePath toCloudnamePath() {
+ return new CloudnamePath(new String[] { this.region, this.tag, this.service });
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final ServiceCoordinate other = (ServiceCoordinate) o;
+
+ if (!this.region.equals(other.region)
+ || !this.tag.equals(other.tag)
+ || !this.service.equals(other.service)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = region.hashCode();
+ result = 31 * result + tag.hashCode();
+ result = 31 * result + service.hashCode();
+ return result;
+ }
+
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceData.java b/cn-service/src/main/java/org/cloudname/service/ServiceData.java
new file mode 100644
index 00000000..dec36ea1
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/ServiceData.java
@@ -0,0 +1,123 @@
+package org.cloudname.service;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service data stored for each service. This data only contains endpoints at the moment. Endpoint
+ * names must be unique.
+ *
+ * @author [email protected]
+ */
+public class ServiceData {
+ private final Object syncObject = new Object();
+ private final Map<String, Endpoint> endpoints = new HashMap<>();
+
+ /**
+ * Create empty service data object with no endpoints.
+ */
+ public ServiceData() {
+
+ }
+
+ /**
+ * Create a new instance with the given list of endpoints. If there's duplicates in the list
+ * the duplicates will be discarded.
+ *
+ * @param endpointList List of endpoints to add
+ */
+ /* package-private */ ServiceData(final List<Endpoint> endpointList) {
+ synchronized (syncObject) {
+ for (final Endpoint endpoint : endpointList) {
+ endpoints.put(endpoint.getName(), endpoint);
+ }
+ }
+ }
+
+ /**
+ * @param name Name of endpoint
+ * @return The endpoint with the specified name. Null if the endpoint doesn't exist
+ */
+ public Endpoint getEndpoint(final String name) {
+ synchronized (syncObject) {
+ for (final String epName : endpoints.keySet()) {
+ if (epName.equals(name)) {
+ return endpoints.get(name);
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @param endpoint Endpoint to add
+ * @return true if endpoint can be added. False if the endpoint already exists.
+ * @throws IllegalArgumentException if endpoint is invalid
+ */
+ public boolean addEndpoint(final Endpoint endpoint) {
+ if (endpoint == null) {
+ throw new IllegalArgumentException("Endpoint can not be null");
+ }
+ synchronized (syncObject) {
+ if (endpoints.containsKey(endpoint.getName())) {
+ return false;
+ }
+ endpoints.put(endpoint.getName(), endpoint);
+ }
+ return true;
+ }
+
+ /**
+ * @param endpoint endpoint to remove
+ * @return True if the endpoint has been removed, false if the endpoint can't be removed. Nulls
+ * @throws IllegalArgumentException if endpoint is invalid
+ */
+ public boolean removeEndpoint(final Endpoint endpoint) {
+ if (endpoint == null) {
+ throw new IllegalArgumentException("Endpoint can't be null");
+ }
+ synchronized (syncObject) {
+ if (!endpoints.containsKey(endpoint.getName())) {
+ return false;
+ }
+ endpoints.remove(endpoint.getName());
+ }
+ return true;
+ }
+
+ /**
+ * @return Service data serialized as a JSON string
+ */
+ /* package-private */ String toJsonString() {
+ final JSONArray epList = new JSONArray();
+ int i = 0;
+ for (Map.Entry<String, Endpoint> entry : endpoints.entrySet()) {
+ epList.put(i++, new JSONObject(entry.getValue().toJsonString()));
+ }
+ return new JSONObject().put("endpoints", epList).toString();
+ }
+
+ /**
+ * @param jsonString JSON string to create instance from
+ * @throws IllegalArgumentException if parameter is invalid
+ */
+ /* package-private */ static ServiceData fromJsonString(final String jsonString) {
+ if (jsonString == null || jsonString.isEmpty()) {
+ throw new IllegalArgumentException("json string can not be null or empty");
+ }
+
+ final List<Endpoint> endpoints = new ArrayList<>();
+
+ final JSONObject json = new JSONObject(jsonString);
+ final JSONArray epList = json.getJSONArray("endpoints");
+ for (int i = 0; i < epList.length(); i++) {
+ endpoints.add(Endpoint.fromJson(epList.getJSONObject(i).toString()));
+ }
+ return new ServiceData(endpoints);
+ }
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceHandle.java b/cn-service/src/main/java/org/cloudname/service/ServiceHandle.java
new file mode 100644
index 00000000..a9305bb2
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/ServiceHandle.java
@@ -0,0 +1,75 @@
+package org.cloudname.service;
+import org.cloudname.core.LeaseHandle;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * A handle to a service registration. The handle is used to modify the registered endpoints. The
+ * state is kept in the ServiceData instance held by the handle. Note that endpoints in the
+ * ServiceData instance isn't registered automatically when the handle is created.
+ *
+ * @author [email protected]
+ */
+public class ServiceHandle implements AutoCloseable {
+ private static final Logger LOG = Logger.getLogger(ServiceHandle.class.getName());
+ private final LeaseHandle leaseHandle;
+ private final InstanceCoordinate instanceCoordinate;
+ private final ServiceData serviceData;
+
+ /**
+ * @param instanceCoordinate The instance coordinate this handle belongs to
+ * @param serviceData The service data object
+ * @param leaseHandle The Cloudname handle for the lease
+ * @throws IllegalArgumentException if parameters are invalid
+ */
+ public ServiceHandle(
+ final InstanceCoordinate instanceCoordinate,
+ final ServiceData serviceData,
+ final LeaseHandle leaseHandle) {
+ if (instanceCoordinate == null) {
+ throw new IllegalArgumentException("Instance coordinate cannot be null");
+ }
+ if (serviceData == null) {
+ throw new IllegalArgumentException("Service data must be set");
+ }
+ if (leaseHandle == null) {
+ throw new IllegalArgumentException("Lease handle cannot be null");
+ }
+ this.leaseHandle = leaseHandle;
+ this.instanceCoordinate = instanceCoordinate;
+ this.serviceData = serviceData;
+ }
+
+ /**
+ * @param endpoint The endpoint to register
+ * @return true if endpoint is registered
+ */
+ boolean registerEndpoint(final Endpoint endpoint) {
+ if (!serviceData.addEndpoint(endpoint)) {
+ return false;
+ }
+ return this.leaseHandle.writeLeaseData(serviceData.toJsonString());
+ }
+
+ /**
+ * @param endpoint The endpoint to remove
+ * @return true if endpoint is removed
+ */
+ boolean removeEndpoint(final Endpoint endpoint) {
+ if (!serviceData.removeEndpoint(endpoint)) {
+ return false;
+ }
+ return this.leaseHandle.writeLeaseData(serviceData.toJsonString());
+ }
+
+ @Override
+ public void close() {
+ try {
+ leaseHandle.close();
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Got exception closing lease for instance "
+ + instanceCoordinate.toCanonicalString(), ex);
+ }
+ }
+}
diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceListener.java b/cn-service/src/main/java/org/cloudname/service/ServiceListener.java
new file mode 100644
index 00000000..ac36e6c8
--- /dev/null
+++ b/cn-service/src/main/java/org/cloudname/service/ServiceListener.java
@@ -0,0 +1,33 @@
+package org.cloudname.service;
+
+/**
+ * Listener interface for services.
+ *
+ * @author [email protected]
+ */
+public interface ServiceListener {
+ /**
+ * Service is created. Note that this method is called once for every service that already
+ * exists when the listener is attached.
+ *
+ * @param coordinate Coordinate of instance
+ * @param serviceData The instance's data, ie its endpoints
+ */
+ void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData serviceData);
+
+ /**
+ * Service's data have changed.
+ * @param coordinate Coordinate of instance
+ * @param data The instance's data
+ */
+ void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data);
+
+ /**
+ * Instance is removed. This means that the service has either closed its connection to
+ * the Cloudname backend or it has become unavailable for some other reason (f.e. caused
+ * by a network partition)
+ *
+ * @param coordinate The instance's coordinate
+ */
+ void onServiceRemoved(final InstanceCoordinate coordinate);
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/CloudnameServicePermanentTest.java b/cn-service/src/test/java/org/cloudname/service/CloudnameServicePermanentTest.java
new file mode 100644
index 00000000..d819931c
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/CloudnameServicePermanentTest.java
@@ -0,0 +1,261 @@
+package org.cloudname.service;
+
+import org.cloudname.backends.memory.MemoryBackend;
+import org.cloudname.core.CloudnameBackend;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * Test persistent services functions.
+ */
+public class CloudnameServicePermanentTest {
+ private static final String SERVICE_COORDINATE = "myoldskoolserver.test.local";
+ private static final CloudnameBackend memoryBackend = new MemoryBackend();
+ private static final Endpoint DEFAULT_ENDPOINT = new Endpoint("serviceport", "localhost", 80);
+ private final ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(SERVICE_COORDINATE);
+
+ @BeforeClass
+ public static void createServiceRegistration() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ assertThat(
+ cloudnameService.createPermanentService(
+ ServiceCoordinate.parse(SERVICE_COORDINATE), DEFAULT_ENDPOINT),
+ is(true));
+ }
+ }
+
+ @Test
+ public void testPersistentServiceChanges() throws InterruptedException {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+
+ final CountDownLatch callCounter = new CountDownLatch(2);
+ final int secondsToWait = 1;
+
+ // ...a listener on the service will trigger when there's a change plus the initial
+ // onCreate call.
+ cloudnameService.addPermanentServiceListener(serviceCoordinate,
+ new PermanentServiceListener() {
+ private final AtomicInteger createCount = new AtomicInteger(0);
+ private final AtomicInteger changeCount = new AtomicInteger(0);
+
+ @Override
+ public void onServiceCreated(Endpoint endpoint) {
+ // Expect this to be called once and only once, even on updates
+ assertThat(createCount.incrementAndGet(), is(1));
+ callCounter.countDown();
+ }
+
+ @Override
+ public void onServiceChanged(Endpoint endpoint) {
+ // This will be called when the endpoint changes
+ assertThat(changeCount.incrementAndGet(), is(1));
+ callCounter.countDown();
+ }
+
+ @Override
+ public void onServiceRemoved() {
+ // This won't be called
+ fail("Did not expect onServiceRemoved to be called");
+ }
+ });
+
+ // Updating with invalid endpoint name fails
+ assertThat(cloudnameService.updatePermanentService(serviceCoordinate,
+ new Endpoint("wrongep", DEFAULT_ENDPOINT.getHost(), 81)),
+ is(false));
+
+ // Using the right one, however, does work
+ assertThat(cloudnameService.updatePermanentService(serviceCoordinate,
+ new Endpoint(
+ DEFAULT_ENDPOINT.getName(), DEFAULT_ENDPOINT.getHost(), 81)),
+ is(true));
+ // Wait for notifications
+ callCounter.await(secondsToWait, TimeUnit.SECONDS);
+
+ }
+
+ // At this point the service created above is closed; changes to the service won't
+ // trigger errors in the listener declared. Just do one change to make sure.
+ final CloudnameService cloudnameService = new CloudnameService(memoryBackend);
+ assertThat(cloudnameService.updatePermanentService(
+ ServiceCoordinate.parse(SERVICE_COORDINATE), DEFAULT_ENDPOINT), is(true));
+ }
+
+ @Test
+ public void testDuplicateRegistration() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ // Creating the same permanent service will fail
+ assertThat("Can't create two identical permanent services",
+ cloudnameService.createPermanentService(serviceCoordinate, DEFAULT_ENDPOINT),
+ is(false));
+ }
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testNullCoordinateRegistration() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ cloudnameService.createPermanentService(null, DEFAULT_ENDPOINT);
+ }
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testInvalidEndpoint() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ cloudnameService.createPermanentService(serviceCoordinate, null);
+ }
+ }
+
+ @Test
+ public void testListenerOnServiceThatDoesntExist() throws InterruptedException {
+ final String anotherServiceCoordinate = "someother.service.coordinate";
+
+ // It should be possible to listen for a permanent service that doesn't exist yet. Once the
+ // service is created it must trigger a callback to the clients listening.
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+
+ final CountDownLatch createCalls = new CountDownLatch(1);
+ final CountDownLatch removeCalls = new CountDownLatch(1);
+ final CountDownLatch updateCalls = new CountDownLatch(1);
+
+ cloudnameService.addPermanentServiceListener(
+ ServiceCoordinate.parse(anotherServiceCoordinate),
+ new PermanentServiceListener() {
+ final AtomicInteger order = new AtomicInteger(0);
+ @Override
+ public void onServiceCreated(Endpoint endpoint) {
+ createCalls.countDown();
+ assertThat(order.incrementAndGet(), is(1));
+ }
+
+ @Override
+ public void onServiceChanged(Endpoint endpoint) {
+ updateCalls.countDown();
+ assertThat(order.incrementAndGet(), is(2));
+ }
+
+ @Override
+ public void onServiceRemoved() {
+ removeCalls.countDown();
+ assertThat(order.incrementAndGet(), is(3));
+ }
+ });
+
+ // Create the new service registration, change the endpoint, then remove it. The
+ // count down latches should count down and the order should be create, change, remove
+ final ServiceCoordinate another = ServiceCoordinate.parse(anotherServiceCoordinate);
+ cloudnameService.createPermanentService(another, DEFAULT_ENDPOINT);
+ cloudnameService.updatePermanentService(another,
+ new Endpoint(DEFAULT_ENDPOINT.getName(), "otherhost", 4711));
+ cloudnameService.removePermanentService(another);
+
+ final int secondsToWait = 1;
+ assertTrue("Expected callback for create to trigger but it didn't",
+ createCalls.await(secondsToWait, TimeUnit.SECONDS));
+ assertTrue("Expected callback for update to trigger but it didn't",
+ updateCalls.await(secondsToWait, TimeUnit.SECONDS));
+ assertTrue("Expected callback for remove to trigger but it didn't",
+ removeCalls.await(secondsToWait, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ public void testLeaseUpdateOnLeaseThatDoesntExist() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ assertThat("Can't update a service that doesn't exist",
+ cloudnameService.updatePermanentService(
+ ServiceCoordinate.parse("foo.bar.baz"), DEFAULT_ENDPOINT),
+ is(false));
+ }
+ }
+
+ @Test
+ public void testRemoveServiceThatDoesntExist() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ assertThat("Can't remove a service that doesn't exist",
+ cloudnameService.removePermanentService(ServiceCoordinate.parse("foo.bar.baz")),
+ is(false));
+ }
+ }
+
+ @AfterClass
+ public static void removeServiceRegistration() throws InterruptedException {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ final ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(SERVICE_COORDINATE);
+ final CountDownLatch callCounter = new CountDownLatch(2);
+ final int secondsToWait = 1;
+ cloudnameService.addPermanentServiceListener(serviceCoordinate,
+ new PermanentServiceListener() {
+ private final AtomicInteger createCount = new AtomicInteger(0);
+ private final AtomicInteger removeCount = new AtomicInteger(0);
+
+ @Override
+ public void onServiceCreated(final Endpoint endpoint) {
+ // This will be called once and only once
+ assertThat("Did not onServiceCreated to be called multiple times",
+ createCount.incrementAndGet(), is(1));
+ callCounter.countDown();
+ }
+
+ @Override
+ public void onServiceChanged(final Endpoint endpoint) {
+ fail("Did not expect any calls to onServiceChanged");
+ }
+
+ @Override
+ public void onServiceRemoved() {
+ assertThat("Did not expect onServiceRemoved to be called multiple"
+ + " times", removeCount.incrementAndGet(), is(1));
+ callCounter.countDown();
+ }
+ });
+
+ // Remove the service created in the setup.
+ assertThat(cloudnameService.removePermanentService(serviceCoordinate), is(true));
+
+ assertTrue("Did not receive the expected number of calls to listener. "
+ + callCounter.getCount() + " calls remaining.",
+ callCounter.await(secondsToWait, TimeUnit.SECONDS));
+
+ // Removing it twice will fail.
+ assertThat(cloudnameService.removePermanentService(serviceCoordinate), is(false));
+ }
+ }
+
+ private final ServiceCoordinate coordinate = ServiceCoordinate.parse("service.tag.region");
+
+ @Test (expected = IllegalArgumentException.class)
+ public void coordinateCanNotBeNullWhenUpdatingService() {
+ new CloudnameService(memoryBackend).updatePermanentService(null, null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void endpointCanNotBeNullWhenUpdatingService() {
+ new CloudnameService(memoryBackend).updatePermanentService(coordinate, null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void coordinateCanNotBeNullWhenRemovingService() {
+ new CloudnameService(memoryBackend).removePermanentService(null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void coordinateCanNotBeNullWhenAddingListener() {
+ new CloudnameService(memoryBackend).addPermanentServiceListener(null, null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void listenerCanNotBeNullWhenAddingListener() {
+ new CloudnameService(memoryBackend).addPermanentServiceListener(coordinate, null);
+ }
+
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/CloudnameServiceTest.java b/cn-service/src/test/java/org/cloudname/service/CloudnameServiceTest.java
new file mode 100644
index 00000000..6fe4a9a9
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/CloudnameServiceTest.java
@@ -0,0 +1,316 @@
+package org.cloudname.service;
+
+import org.cloudname.backends.memory.MemoryBackend;
+import org.cloudname.core.CloudnameBackend;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertThat;
+import static org.hamcrest.CoreMatchers.is;
+
+/**
+ * Test service registration with memory-based backend.
+ */
+public class CloudnameServiceTest {
+ private static final CloudnameBackend memoryBackend = new MemoryBackend();
+
+ private final ServiceCoordinate coordinate = ServiceCoordinate.parse("service.tag.region");
+
+ /**
+ * Max time to wait for changes to propagate to clients. In seconds.
+ */
+ private static final int MAX_WAIT_S = 1;
+
+ private final Random random = new Random();
+ private int getRandomPort() {
+ return Math.max(1, Math.abs(random.nextInt(4096)));
+ }
+
+ private ServiceHandle registerService(final CloudnameService cloudnameService, final String serviceCoordinateString) {
+ final ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(serviceCoordinateString);
+
+ final Endpoint httpEndpoint = new Endpoint("http", "127.0.0.1", getRandomPort());
+ final Endpoint webconsoleEndpoint = new Endpoint("webconsole", "127.0.0.2", getRandomPort());
+
+ final ServiceData serviceData = new ServiceData(Arrays.asList(httpEndpoint, webconsoleEndpoint));
+ return cloudnameService.registerService(serviceCoordinate, serviceData);
+ }
+
+ /**
+ * Create two sets of services, register both and check that notifications are sent to the
+ * subscribers.
+ */
+ @Test
+ public void testServiceNotifications() throws InterruptedException {
+ final String SOME_COORDINATE = "someservice.test.local";
+ final String ANOTHER_COORDINATE = "anotherservice.test.local";
+
+ final CloudnameService mainCloudname = new CloudnameService(memoryBackend);
+
+ final int numOtherServices = 10;
+ final List<ServiceHandle> handles = new ArrayList<>();
+ for (int i = 0; i < numOtherServices; i++) {
+ handles.add(registerService(mainCloudname, ANOTHER_COORDINATE));
+ }
+
+ final Executor executor = Executors.newCachedThreadPool();
+ final int numServices = 5;
+ final CountDownLatch registrationLatch = new CountDownLatch(numServices);
+ final CountDownLatch instanceLatch = new CountDownLatch(numServices * numOtherServices);
+ final CountDownLatch httpEndpointLatch = new CountDownLatch(numServices * numOtherServices);
+ final CountDownLatch webconsoleEndpointLatch = new CountDownLatch(numServices * numOtherServices);
+ final CountDownLatch removeLatch = new CountDownLatch(numServices * numOtherServices);
+ final Semaphore terminateSemaphore = new Semaphore(1);
+ final CountDownLatch completedLatch = new CountDownLatch(numServices);
+
+ final Runnable service = new Runnable() {
+ @Override
+ public void run() {
+ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) {
+ try (final ServiceHandle handle = registerService(cloudnameService, SOME_COORDINATE)) {
+ registrationLatch.countDown();
+
+ final ServiceCoordinate otherServiceCoordinate = ServiceCoordinate.parse(ANOTHER_COORDINATE);
+
+ // Do a service lookup on the other service. This will yield N elements.
+ cloudnameService.addServiceListener(otherServiceCoordinate, new ServiceListener() {
+ @Override
+ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) {
+ instanceLatch.countDown();
+ if (data.getEndpoint("http") != null) {
+ httpEndpointLatch.countDown();
+ }
+ if (data.getEndpoint("webconsole") != null) {
+ webconsoleEndpointLatch.countDown();
+ }
+ }
+
+ @Override
+ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) {
+ if (data.getEndpoint("http") != null) {
+ httpEndpointLatch.countDown();
+ }
+ if (data.getEndpoint("webconsole") != null) {
+ webconsoleEndpointLatch.countDown();
+ }
+ }
+
+ @Override
+ public void onServiceRemoved(final InstanceCoordinate coordinate) {
+ removeLatch.countDown();
+ }
+ });
+
+ // Wait for the go ahead before terminating
+ try {
+ terminateSemaphore.acquire();
+ terminateSemaphore.release();
+ } catch (final InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+ }
+ // The service handle will close and the instance will be removed at this point.
+ }
+ completedLatch.countDown();
+ }
+ };
+
+ // Grab the semaphore. This wil stop the services from terminating
+ terminateSemaphore.acquire();
+
+ // Start two threads which will register a service and look up a set of another.
+ for (int i = 0; i < numServices; i++) {
+ executor.execute(service);
+ }
+
+ // Wait for the registrations and endpoints to propagate
+ assertTrue("Expected registrations to complete",
+ registrationLatch.await(MAX_WAIT_S, TimeUnit.SECONDS));
+
+ assertTrue("Expected http endpoints to be registered but missing "
+ + httpEndpointLatch.getCount(),
+ httpEndpointLatch.await(MAX_WAIT_S, TimeUnit.SECONDS));
+
+ assertTrue("Expected webconsole endpoints to be registered but missing "
+ + webconsoleEndpointLatch.getCount(),
+ webconsoleEndpointLatch.await(MAX_WAIT_S, TimeUnit.SECONDS));
+
+ // Registrations are now completed; remove the existing services
+ for (final ServiceHandle handle : handles) {
+ handle.close();
+ }
+
+ // This will trigger remove events in the threads.
+ assertTrue("Expected services to be removed but " + removeLatch.getCount()
+ + " still remains", removeLatch.await(MAX_WAIT_S, TimeUnit.SECONDS));
+
+ // Let the threads terminate. This will remove the registrations
+ terminateSemaphore.release();
+
+ assertTrue("Expected services to complete but " + completedLatch.getCount()
+ + " still remains", completedLatch.await(MAX_WAIT_S, TimeUnit.SECONDS));
+
+ // Success! There shouldn't be any more services registered at this point. Check to make sure
+ mainCloudname.addServiceListener(ServiceCoordinate.parse(SOME_COORDINATE), new ServiceListener() {
+ @Override
+ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) {
+ fail("Should not have any services but " + coordinate + " is still there");
+ }
+
+ @Override
+ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) {
+ fail("Should not have any services but " + coordinate + " reports data");
+ }
+
+ @Override
+ public void onServiceRemoved(final InstanceCoordinate coordinate) {
+
+ }
+ });
+ mainCloudname.addServiceListener(ServiceCoordinate.parse(ANOTHER_COORDINATE), new ServiceListener() {
+ @Override
+ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) {
+ fail("Should not have any services but " + coordinate + " is still there");
+ }
+
+ @Override
+ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) {
+ fail("Should not have any services but " + coordinate + " is still there");
+ }
+
+ @Override
+ public void onServiceRemoved(InstanceCoordinate coordinate) {
+
+ }
+ });
+ }
+
+ /**
+ * Ensure data notifications works as expecte. Update a lot of endpoints on a single
+ * service and check that the subscribers get notified of all changes in the correct order.
+ */
+ @Test
+ public void testDataNotifications() throws InterruptedException {
+ final CloudnameService cs = new CloudnameService(memoryBackend);
+
+ final String serviceCoordinate = "some.service.name";
+ final ServiceHandle serviceHandle = cs.registerService(
+ ServiceCoordinate.parse(serviceCoordinate),
+ new ServiceData(new ArrayList<Endpoint>()));
+
+ final int numClients = 10;
+ final int numDataChanges = 50;
+ final int maxSecondsForNotifications = 1;
+ final CountDownLatch dataChangeLatch = new CountDownLatch(numClients * numDataChanges);
+ final CountDownLatch readyLatch = new CountDownLatch(numClients);
+ final String EP_NAME = "endpoint";
+ final Semaphore terminateSemaphore = new Semaphore(1);
+
+ // Grab the semaphore, prevent threads from completing
+ terminateSemaphore.acquire();
+
+ final Runnable clientServices = new Runnable() {
+ @Override
+ public void run() {
+ try (final CloudnameService cn = new CloudnameService(memoryBackend)) {
+ cn.addServiceListener(ServiceCoordinate.parse(serviceCoordinate), new ServiceListener() {
+ int portNum = 0;
+ @Override
+ public void onServiceCreated(InstanceCoordinate coordinate, ServiceData serviceData) {
+ // ignore this
+ }
+
+ @Override
+ public void onServiceDataChanged(InstanceCoordinate coordinate, ServiceData data) {
+ final Endpoint ep = data.getEndpoint(EP_NAME);
+ if (ep != null) {
+ dataChangeLatch.countDown();
+ assertThat(ep.getPort(), is(portNum + 1));
+ portNum = portNum + 1;
+ }
+ }
+
+ @Override
+ public void onServiceRemoved(InstanceCoordinate coordinate) {
+ // ignore this
+ }
+ });
+ readyLatch.countDown();
+
+ // Wait for the test to finish before closing. The endpoints will be
+ // processed once every thread is ready.
+ try {
+ terminateSemaphore.acquire();
+ terminateSemaphore.release();
+ } catch (final InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+ }
+ }
+ };
+
+ final Executor executor = Executors.newCachedThreadPool();
+ for (int i = 0; i < numClients; i++) {
+ executor.execute(clientServices);
+ }
+
+ // Wait for the threads to be ready
+ readyLatch.await();
+
+ // Publish changes to the same endpoint; the endpoint is updated with a new port
+ // number for each update.
+ Endpoint oldEndpoint = null;
+ for (int portNum = 1; portNum < numDataChanges + 1; portNum++) {
+ if (oldEndpoint != null) {
+ serviceHandle.removeEndpoint(oldEndpoint);
+ }
+ final Endpoint newEndpoint = new Endpoint(EP_NAME, "localhost", portNum);
+ serviceHandle.registerEndpoint(newEndpoint);
+ oldEndpoint = newEndpoint;
+ }
+
+ // Check if the threads have been notified of all the changes
+ assertTrue("Expected " + (numDataChanges * numClients) + " changes but "
+ + dataChangeLatch.getCount() + " remains",
+ dataChangeLatch.await(maxSecondsForNotifications, TimeUnit.SECONDS));
+
+ // Let threads terminate
+ terminateSemaphore.release();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void coordinateCanNotBeNullWhenAddingListener() {
+ new CloudnameService(memoryBackend).addServiceListener(null, null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void listenerCanNotBeNullWhenAddingListener() {
+ new CloudnameService(memoryBackend).addServiceListener(coordinate, null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void serviceCannotBeNullWhenRegister() {
+ new CloudnameService(memoryBackend).registerService(null, null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void serviceDataCannotBeNullWhenRegister() {
+ new CloudnameService(memoryBackend).registerService(coordinate, null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void backendMustBeValid() {
+ new CloudnameService(null);
+ }
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/EndpointTest.java b/cn-service/src/test/java/org/cloudname/service/EndpointTest.java
new file mode 100644
index 00000000..8d1b368e
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/EndpointTest.java
@@ -0,0 +1,97 @@
+package org.cloudname.service;
+import org.junit.Test;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+
+/**
+ * Test the Endpoint class. Relatively straightforward; test creation and that
+ * fields are set correctly, test conversion to and from JSON, test the equals()
+ * implementation and test assertions in constructor.
+ */
+public class EndpointTest {
+ @Test
+ public void testCreation() {
+ final Endpoint endpoint = new Endpoint("foo", "localhost", 80);
+ assertThat(endpoint.getName(), is("foo"));
+ assertThat(endpoint.getHost(), is("localhost"));
+ assertThat(endpoint.getPort(), is(80));
+ }
+
+ @Test
+ public void testJsonConversion() {
+ final Endpoint endpoint = new Endpoint("bar", "baz", 8888);
+ final String jsonString = endpoint.toJsonString();
+
+ final Endpoint endpointCopy = Endpoint.fromJson(jsonString);
+
+ assertThat(endpointCopy.getName(), is(endpoint.getName()));
+ assertThat(endpointCopy.getHost(), is(endpoint.getHost()));
+ assertThat(endpointCopy.getPort(), is(endpoint.getPort()));
+ }
+
+ @Test
+ public void testEquals() {
+ final Endpoint a = new Endpoint("foo", "bar", 1);
+ final Endpoint b = new Endpoint("foo", "bar", 1);
+ assertThat(a.equals(b), is(true));
+ assertThat(b.equals(a), is(true));
+ assertThat(b.hashCode(), is(a.hashCode()));
+
+ final Endpoint c = new Endpoint("bar", "foo", 1);
+ assertThat(a.equals(c), is(false));
+ assertThat(b.equals(c), is(false));
+
+ final Endpoint d = new Endpoint("foo", "bar", 2);
+ assertThat(a.equals(d), is(false));
+
+ final Endpoint e = new Endpoint("foo", "baz", 1);
+ assertThat(a.equals(e), is(false));
+
+ assertThat(a.equals(null), is(false));
+ assertThat(a.equals("some string"), is(false));
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testNullName() {
+ new Endpoint(null, "foo", 0);
+ fail("Constructor should have thrown exception for null name");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testEmptyName() {
+ new Endpoint("", "foo", 0);
+ fail("Constructor should have thrown exception for null name");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testNullHost() {
+ new Endpoint("foo", null, 0);
+ fail("Constructor should have thrown exception for null host");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testEmptyHost() {
+ new Endpoint("foo", "", 0);
+ fail("Constructor should have thrown exception for null host");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testZeroPort() {
+ new Endpoint("foo", "bar", 0);
+ fail("Constructor should have thrown exception for 0 port");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testNegativePort() {
+ new Endpoint("foo", "bar", -1);
+ fail("Constructor should have thrown exception for 0 port");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testInvalidName() {
+ new Endpoint("æøå", "bar", 80);
+ fail("Constructor should have thrown exception for 0 port");
+ }
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/InstanceCoordinateTest.java b/cn-service/src/test/java/org/cloudname/service/InstanceCoordinateTest.java
new file mode 100644
index 00000000..c7009f0b
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/InstanceCoordinateTest.java
@@ -0,0 +1,92 @@
+package org.cloudname.service;
+
+import org.cloudname.core.CloudnamePath;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+public class InstanceCoordinateTest {
+ @Test
+ public void testCreation() {
+ final String[] path = new String[] { "region", "tag", "service", "instance" };
+ final InstanceCoordinate coordinate = new InstanceCoordinate(new CloudnamePath(path));
+
+ final String canonicalString = coordinate.toCanonicalString();
+ assertThat(canonicalString, is("instance.service.tag.region"));
+
+ final InstanceCoordinate fromCanonical = InstanceCoordinate.parse(canonicalString);
+ assertThat(fromCanonical.toCanonicalString(), is(canonicalString));
+ assertThat(fromCanonical.getRegion(), is(coordinate.getRegion()));
+ assertThat(fromCanonical.getTag(), is(coordinate.getTag()));
+ assertThat(fromCanonical.getService(), is(coordinate.getService()));
+ assertThat(fromCanonical.getInstance(), is(coordinate.getInstance()));
+
+ final String jsonString = coordinate.toJsonString();
+ final InstanceCoordinate fromJson = InstanceCoordinate.fromJson(jsonString);
+ assertThat(fromJson.getRegion(), is(coordinate.getRegion()));
+ assertThat(fromJson.getTag(), is(coordinate.getTag()));
+ assertThat(fromJson.getService(), is(coordinate.getService()));
+ assertThat(fromJson.getInstance(), is(coordinate.getInstance()));
+ assertThat(fromJson.toCanonicalString(), is(coordinate.toCanonicalString()));
+ }
+
+ @Test
+ public void testPathConversion() {
+ final CloudnamePath path = new CloudnamePath(
+ new String[] {"test", "local", "service", "instance" });
+
+ final InstanceCoordinate coordinate = new InstanceCoordinate(path);
+
+ final CloudnamePath cnPath = coordinate.toCloudnamePath();
+ assertThat(cnPath.length(), is(path.length()));
+ assertThat(cnPath, is(equalTo(path)));
+ }
+
+ /**
+ * Ensure toString() has a sensible representation ('ish)
+ */
+ @Test
+ public void toStringMethod() {
+ final CloudnamePath pathA = new CloudnamePath(
+ new String[] {"test", "local", "service", "instance" });
+ final CloudnamePath pathB = new CloudnamePath(
+ new String[] {"test", "local", "service", "instance" });
+ final CloudnamePath pathC = new CloudnamePath(
+ new String[] {"test", "local", "service", "x" });
+
+ final InstanceCoordinate a = new InstanceCoordinate(pathA);
+ final InstanceCoordinate b = new InstanceCoordinate(pathB);
+ final InstanceCoordinate c = new InstanceCoordinate(pathC);
+ assertThat(a.toString(), is(a.toString()));
+ assertThat(a.toString(), is(not(c.toString())));
+
+ assertThat(a.toCanonicalString(), is(b.toCanonicalString()));
+ }
+
+ @Test
+ public void invalidStringConversion() {
+ assertThat(InstanceCoordinate.parse("foo:bar.baz"), is(nullValue()));
+ assertThat(InstanceCoordinate.parse(null), is(nullValue()));
+ assertThat(InstanceCoordinate.parse("foo.bar.baz"), is(nullValue()));
+ assertThat(InstanceCoordinate.parse(""), is(nullValue()));
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void invalidNames2() {
+ assertThat(InstanceCoordinate.parse("æ.ø.å.a"), is(nullValue()));
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void nullPathInConstructor() {
+ new InstanceCoordinate(null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void invalidPathInConstructor() {
+ new InstanceCoordinate(new CloudnamePath(new String[] { "foo" }));
+ }
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/ServiceCoordinateTest.java b/cn-service/src/test/java/org/cloudname/service/ServiceCoordinateTest.java
new file mode 100644
index 00000000..c49126e0
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/ServiceCoordinateTest.java
@@ -0,0 +1,87 @@
+package org.cloudname.service;
+
+import org.cloudname.core.CloudnamePath;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+public class ServiceCoordinateTest {
+ private final CloudnamePath cnPath = new CloudnamePath(
+ new String[] { "local", "test", "service" });
+
+
+ @Test
+ public void testCreation() {
+ final ServiceCoordinate coordinate = new ServiceCoordinate(cnPath);
+ assertThat(coordinate.getRegion(), is(cnPath.get(0)));
+ assertThat(coordinate.getTag(), is(cnPath.get(1)));
+ assertThat(coordinate.getService(), is(cnPath.get(2)));
+ }
+
+ @Test
+ public void testParse() {
+ final ServiceCoordinate coord = ServiceCoordinate.parse("service.tag.region");
+ assertThat(coord.getRegion(), is("region"));
+ assertThat(coord.getTag(), is("tag"));
+ assertThat(coord.getService(), is("service"));
+ }
+
+ @Test
+ public void testEquals() {
+ final ServiceCoordinate coordA = ServiceCoordinate.parse("a.b.c");
+ final ServiceCoordinate coordB = ServiceCoordinate.parse("a.b.c");
+ final ServiceCoordinate coordC = ServiceCoordinate.parse("a.b.d");
+ final ServiceCoordinate coordD = ServiceCoordinate.parse("a.a.c");
+ final ServiceCoordinate coordE = ServiceCoordinate.parse("a.a.a");
+ final ServiceCoordinate coordF = ServiceCoordinate.parse("c.b.c");
+
+ assertThat(coordA, is(equalTo(coordB)));
+ assertThat(coordB, is(equalTo(coordA)));
+
+ assertThat(coordA, is(not(equalTo(coordC))));
+ assertThat(coordA, is(not(equalTo(coordD))));
+ assertThat(coordA, is(not(equalTo(coordE))));
+ assertThat(coordA, is(not(equalTo(coordF))));
+
+ assertThat(coordA.equals(null), is(false));
+ assertThat(coordA.equals(new Object()), is(false));
+ }
+
+ @Test
+ public void testHashCode() {
+ final ServiceCoordinate coordA = ServiceCoordinate.parse("a.b.c");
+ final ServiceCoordinate coordB = ServiceCoordinate.parse("a.b.c");
+ final ServiceCoordinate coordC = ServiceCoordinate.parse("x.x.x");
+ assertThat(coordA.hashCode(), is(coordB.hashCode()));
+ assertThat(coordC.hashCode(), is(not(coordA.hashCode())));
+ }
+ @Test
+ public void testInvalidCoordinateString0() {
+ assertThat(ServiceCoordinate.parse("foo bar baz"), is(nullValue()));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testInvalidCoordinateString1() {
+ ServiceCoordinate.parse("..");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testInvalidCoordinateString2() {
+ ServiceCoordinate.parse("_._._");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void nullPathParameter() {
+ new ServiceCoordinate(null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void illegalPathParameter() {
+ new ServiceCoordinate(new CloudnamePath(new String[] { "foo" }));
+ }
+
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/ServiceDataTest.java b/cn-service/src/test/java/org/cloudname/service/ServiceDataTest.java
new file mode 100644
index 00000000..0154a78a
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/ServiceDataTest.java
@@ -0,0 +1,124 @@
+package org.cloudname.service;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+public class ServiceDataTest {
+ @Test
+ public void testCreation() {
+ final Endpoint ep1 = new Endpoint("foo", "bar", 1);
+ final Endpoint ep2 = new Endpoint("bar", "baz", 1);
+
+ final ServiceData data = new ServiceData(Arrays.asList(ep1, ep2));
+ assertThat(data.getEndpoint("foo"), is(equalTo(ep1)));
+ assertThat(data.getEndpoint("bar"), is(equalTo(ep2)));
+ assertThat(data.getEndpoint("baz"), is(nullValue()));
+ }
+
+ @Test
+ public void testAddRemoveEndpoint() {
+ final ServiceData data = new ServiceData(new ArrayList<Endpoint>());
+ assertThat(data.getEndpoint("a"), is(nullValue()));
+ assertThat(data.getEndpoint("b"), is(nullValue()));
+
+ final Endpoint ep1 = new Endpoint("a", "localhost", 80);
+ final Endpoint ep1a = new Endpoint("a", "localhost", 80);
+ // Endpoint can only be added once
+ assertThat(data.addEndpoint(ep1), is(true));
+ assertThat(data.addEndpoint(ep1), is(false));
+ // Endpoints must be unique
+ assertThat(data.addEndpoint(ep1a), is(false));
+
+ // Another endpoint can be added
+ final Endpoint ep2 = new Endpoint("b", "localhost", 80);
+ final Endpoint ep2a = new Endpoint("b", "localhost", 80);
+ assertThat(data.addEndpoint(ep2), is(true));
+ // But the same rules applies
+ assertThat(data.addEndpoint(ep2), is(false));
+ assertThat(data.addEndpoint(ep2a), is(false));
+
+ // Data now contains both endpoints
+ assertThat(data.getEndpoint("a"), is(equalTo(ep1)));
+ assertThat(data.getEndpoint("b"), is(equalTo(ep2)));
+
+ assertThat(data.removeEndpoint(ep1), is(true));
+ assertThat(data.removeEndpoint(ep1a), is(false));
+
+ // ...ditto for next endpoint
+ assertThat(data.removeEndpoint(ep2), is(true));
+ assertThat(data.removeEndpoint(ep2), is(false));
+
+ // The endpoints with identical names can be added
+ assertThat(data.addEndpoint(ep1a), is(true));
+ assertThat(data.addEndpoint(ep2a), is(true));
+ }
+
+ @Test
+ public void testConversionToFromJson() {
+ final Endpoint endpointA = new Endpoint("foo", "bar", 80);
+ final Endpoint endpointB = new Endpoint("baz", "bar", 81);
+ final ServiceData dataA = new ServiceData(
+ Arrays.asList(endpointA, endpointB));
+
+ final String jsonString = dataA.toJsonString();
+
+ final ServiceData dataB = ServiceData.fromJsonString(jsonString);
+
+ assertThat(dataB.getEndpoint("foo"), is(endpointA));
+ assertThat(dataB.getEndpoint("baz"), is(endpointB));
+ }
+
+ @Test
+ public void uniqueNamesAreRequired() {
+ final Endpoint endpointA = new Endpoint("foo", "bar", 80);
+ final Endpoint endpointB = new Endpoint("foo", "baz", 82);
+ final Endpoint endpointC = new Endpoint("foo", "localhost", 80);
+ final Endpoint endpointD = new Endpoint("foobar", "localhost", 80);
+
+ final ServiceData serviceData = new ServiceData(new ArrayList<Endpoint>());
+ assertThat(serviceData.addEndpoint(endpointA), is(true));
+ assertThat(serviceData.addEndpoint(endpointB), is(false));
+ assertThat(serviceData.addEndpoint(endpointC), is(false));
+ assertThat(serviceData.addEndpoint(endpointD), is(true));
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testInvalidJson1() {
+ final String nullStr = null;
+ ServiceData.fromJsonString(nullStr);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testInvalidJson2() {
+ ServiceData.fromJsonString("");
+ }
+
+ @Test (expected = org.json.JSONException.class)
+ public void testInvalidJson3() {
+ ServiceData.fromJsonString("}{");
+ }
+
+ @Test (expected = org.json.JSONException.class)
+ public void testInvalidJson4() {
+ ServiceData.fromJsonString("{ \"foo\": 12 }");
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void addNullEndpoint() {
+ final ServiceData data = new ServiceData();
+ data.addEndpoint(null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void removeNullEndpoint() {
+ final ServiceData data = new ServiceData();
+ data.removeEndpoint(null);
+ }
+}
diff --git a/cn-service/src/test/java/org/cloudname/service/ServiceHandleTest.java b/cn-service/src/test/java/org/cloudname/service/ServiceHandleTest.java
new file mode 100644
index 00000000..5b43e37c
--- /dev/null
+++ b/cn-service/src/test/java/org/cloudname/service/ServiceHandleTest.java
@@ -0,0 +1,104 @@
+package org.cloudname.service;
+
+import org.cloudname.core.CloudnamePath;
+import org.cloudname.core.LeaseHandle;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class ServiceHandleTest {
+
+ @Test
+ public void testCreation() {
+ final InstanceCoordinate instanceCoordinate
+ = InstanceCoordinate.parse("instance.service.tag.region");
+ final ServiceData serviceData = new ServiceData(new ArrayList<Endpoint>());
+ final LeaseHandle handle = new LeaseHandle() {
+ @Override
+ public boolean writeLeaseData(String data) {
+ return true;
+ }
+
+ @Override
+ public CloudnamePath getLeasePath() {
+ return instanceCoordinate.toCloudnamePath();
+ }
+
+ @Override
+ public void close() throws IOException {
+ // nothing
+ }
+ };
+
+ final ServiceHandle serviceHandle
+ = new ServiceHandle(instanceCoordinate, serviceData, handle);
+
+ final Endpoint ep1 = new Endpoint("foo", "bar", 80);
+ assertThat(serviceHandle.registerEndpoint(ep1), is(true));
+ assertThat(serviceHandle.registerEndpoint(ep1), is(false));
+
+ assertThat(serviceHandle.removeEndpoint(ep1), is(true));
+ assertThat(serviceHandle.removeEndpoint(ep1), is(false));
+
+ serviceHandle.close();
+ }
+
+ @Test
+ public void testFailingHandle() {
+ final InstanceCoordinate instanceCoordinate
+ = InstanceCoordinate.parse("instance.service.tag.region");
+ final Endpoint ep1 = new Endpoint("foo", "bar", 80);
+
+ final ServiceData serviceData = new ServiceData(Arrays.asList(ep1));
+ final LeaseHandle handle = new LeaseHandle() {
+ @Override
+ public boolean writeLeaseData(String data) {
+ return false;
+ }
+
+ @Override
+ public CloudnamePath getLeasePath() {
+ return instanceCoordinate.toCloudnamePath();
+ }
+
+ @Override
+ public void close() throws IOException {
+ throw new IOException("I broke");
+ }
+ };
+
+ final ServiceHandle serviceHandle
+ = new ServiceHandle(instanceCoordinate, serviceData, handle);
+
+ final Endpoint ep2 = new Endpoint("bar", "baz", 81);
+ assertThat(serviceHandle.registerEndpoint(ep2), is(false));
+
+ assertThat(serviceHandle.removeEndpoint(ep1), is(false));
+ assertThat(serviceHandle.removeEndpoint(ep2), is(false));
+
+ serviceHandle.close();
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testWithNullParameters1() {
+ new ServiceHandle(null, null, null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testWithNullParameters2() {
+ new ServiceHandle(InstanceCoordinate.parse("a.b.c.d"), null, null);
+ }
+
+ @Test (expected = IllegalArgumentException.class)
+ public void testWithNullParameters3() {
+ new ServiceHandle(
+ InstanceCoordinate.parse("a.b.c.d"),
+ new ServiceData(new ArrayList<Endpoint>()),
+ null);
+ }
+}
diff --git a/cn-zookeeper/README.md b/cn-zookeeper/README.md
new file mode 100644
index 00000000..3ce1e123
--- /dev/null
+++ b/cn-zookeeper/README.md
@@ -0,0 +1,4 @@
+# ZooKeeper backend
+
+# Node structure
+The root path is set to `/cn` and the leases are stored in `/cn/temporary` and `/cn/permanent`. Temporary leases use ephemeral nodes with a randomly assigned 4-byte long ID. Permanent leases are named by the client. The Curator library is used for the majority of ZooKeeper access. The containing nodes have the `CONTAINER` bit set, i.e. they will be cleaned up by ZooKeeper when there's no more child nodes inside each of the containers. Note that this feature is slated for ZooKeeper 3.5 which is currently in Alpha (as of November 2015). Until then the Curator library uses regular nodes so if it is deployed on a ZooKeeper 3.4 or lower manual cleanups of nodes is necessary.
diff --git a/cn-zookeeper/pom.xml b/cn-zookeeper/pom.xml
new file mode 100644
index 00000000..4d33d081
--- /dev/null
+++ b/cn-zookeeper/pom.xml
@@ -0,0 +1,81 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cloudname-parent</artifactId>
+ <version>3.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>cn-zookeeper</artifactId>
+ <packaging>jar</packaging>
+
+ <name>Cloudname ZooKeeper backend</name>
+ <description>ZooKeeper backend for cloudname</description>
+ <url>https://github.com/Cloudname/cloudname</url>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cn-core</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-all</artifactId>
+ <version>1.3</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-framework</artifactId>
+ <version>2.9.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-recipes</artifactId>
+ <version>2.9.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-test</artifactId>
+ <version>2.9.0</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-nop</artifactId>
+ <version>1.7.6</version>
+ </dependency>
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>testtools</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+
+ </plugins>
+ </build>
+</project>
diff --git a/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeCollectionWatcher.java b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeCollectionWatcher.java
new file mode 100644
index 00000000..e8ccf998
--- /dev/null
+++ b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeCollectionWatcher.java
@@ -0,0 +1,257 @@
+package org.cloudname.backends.zookeeper;
+
+import com.google.common.base.Charsets;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.data.Stat;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Monitor a set of child nodes for changes. Needs to do this with the ZooKeeper API since
+ * Curator doesn't provide the necessary interface and the PathChildrenCache is best effort
+ * (and not even a very good effort)
+ *
+ * Watches are kept as usual and the mzxid for each node is kept. If that changes between
+ * watches it mens we've missed an event and the appropriate event is generated to the
+ * listener.
+ *
+ * Note that this class only watches for changes one level down. Changes in children aren't
+ * monitored. The path must exist beforehand.
+ *
+ * @author [email protected]
+ */
+public class NodeCollectionWatcher {
+ private static final Logger LOG = Logger.getLogger(NodeCollectionWatcher.class.getName());
+
+ private final Map<String, Long> childMzxid = new HashMap<>();
+ private final Object syncObject = new Object();
+
+ private final ZooKeeper zk;
+ private final String pathToWatch;
+ private final AtomicBoolean shuttingDown = new AtomicBoolean(false);
+ private final NodeWatcherListener listener;
+
+
+ /**
+ * @param zk ZooKeeper instance to use
+ * @param pathToWatch Path to observe
+ * @param listener Listener for callbacks
+ */
+ public NodeCollectionWatcher(
+ final ZooKeeper zk, final String pathToWatch, final NodeWatcherListener listener) {
+ this.pathToWatch = pathToWatch;
+ this.zk = zk;
+ this.listener = listener;
+ readChildNodes();
+ }
+
+ /**
+ * Shut down watchers. The listener won't get notified of changes after it has been shut down.
+ */
+ public void shutdown() {
+ shuttingDown.set(true);
+ }
+
+ /**
+ * Watcher for node collections. Set by getChildren()
+ */
+ private final Watcher nodeCollectionWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent watchedEvent) {
+ switch (watchedEvent.getType()) {
+ case NodeChildrenChanged:
+ // Child values have changed, read children, generate events
+ readChildNodes();
+ break;
+ case None:
+ // Some zookeeper event. Watches might not apply anymore. Reapply.
+ switch (watchedEvent.getState()) {
+ case ConnectedReadOnly:
+ LOG.severe("Connected to readonly cluster");
+ // Connected to a cluster without quorum. Nodes might not be
+ // correct but re-read the nodes.
+ readChildNodes();
+ break;
+ case SyncConnected:
+ LOG.info("Connected to cluster");
+ // (re-)Connected to the cluster. Nodes must be re-read. Discard
+ // those that aren't found, keep unchanged ones.
+ readChildNodes();
+ break;
+ case Disconnected:
+ // Disconnected from the cluster. The nodes might not be
+ // up to date (but a reconnect might solve the issue)
+ LOG.log(Level.WARNING, "Disconnected from zk cluster");
+ break;
+ case Expired:
+ // Session has expired. Nodes are no longer available
+ removeAllChildNodes();
+ break;
+ default:
+ break;
+ }
+ }
+
+ }
+ };
+
+ /**
+ * A watcher for the child nodes (set via getData()
+ */
+ private final Watcher changeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent watchedEvent) {
+ if (shuttingDown.get()) {
+ return;
+ }
+ switch (watchedEvent.getType()) {
+ case NodeDeleted:
+ removeChildNode(watchedEvent.getPath());
+ break;
+ case NodeDataChanged:
+ processNode(watchedEvent.getPath());
+ break;
+
+ }
+ }
+ };
+
+ /**
+ * Remove all nodes.
+ */
+ private void removeAllChildNodes() {
+ System.out.println("Remove all child nodes");
+ final Set<String> nodesToRemove = new HashSet<>();
+ synchronized (syncObject) {
+ nodesToRemove.addAll(childMzxid.keySet());
+ }
+ for (final String node : nodesToRemove) {
+ removeChildNode(node);
+ }
+ }
+
+ /**
+ * Read nodes from ZooKeeper, generating events as necessary. If a node is missing from the
+ * result it will generate a remove notification, ditto with new nodes and changes in nodes.
+ */
+ private void readChildNodes() {
+ try {
+ final List<String> childNodes = zk.getChildren(pathToWatch, nodeCollectionWatcher);
+ final Set<String> childrenToDelete = new HashSet<>();
+ synchronized (syncObject) {
+ childrenToDelete.addAll(childMzxid.keySet());
+ }
+ for (final String nodeName : childNodes) {
+ processNode(pathToWatch + "/" + nodeName);
+ childrenToDelete.remove(pathToWatch + "/" + nodeName);
+ }
+ for (final String nodePath : childrenToDelete) {
+ removeChildNode(nodePath);
+ }
+ } catch (final KeeperException.ConnectionLossException e) {
+ // We've been disconnected. Let the watcher deal with it
+ if (!shuttingDown.get()) {
+ LOG.info("Lost connection to ZooKeeper while reading child nodes.");
+ }
+ } catch (final KeeperException.NoNodeException e) {
+ // Node has been removed. Ignore the error?
+ removeChildNode(e.getPath());
+ } catch (final KeeperException|InterruptedException e) {
+ LOG.log(Level.WARNING, "Got exception reading child nodes", e);
+ }
+ }
+
+ /**
+ * Add a node, generate create or data change notification if needed.
+ */
+ private void processNode(final String nodePath) {
+ if (shuttingDown.get()) {
+ return;
+ }
+ try {
+ final Stat stat = new Stat();
+ final byte[] nodeData = zk.getData(nodePath, changeWatcher, stat);
+ final String data = new String(nodeData, Charsets.UTF_8);
+ synchronized (syncObject) {
+ if (!childMzxid.containsKey(nodePath)) {
+ childMzxid.put(nodePath, stat.getMzxid());
+ generateCreateEvent(nodePath, data);
+ return;
+ }
+ final Long zxid = childMzxid.get(nodePath);
+ if (zxid != stat.getMzxid()) {
+ // the data have changed. Generate event
+ childMzxid.put(nodePath, stat.getMzxid());
+ generateDataChangeEvent(nodePath, data);
+ }
+ }
+ } catch (final KeeperException.ConnectionLossException e) {
+ // We've been disconnected. Let the watcher deal with it
+ if (!shuttingDown.get()) {
+ LOG.info("Lost connection to ZooKeeper while reading child nodes.");
+ }
+ } catch (final KeeperException.NoNodeException e) {
+ removeChildNode(e.getPath());
+ // Node has been removed before we got to do anything. Ignore error?
+ } catch (final KeeperException|InterruptedException e) {
+ LOG.log(Level.WARNING, "Got exception adding child node with path " + nodePath, e);
+ } catch (Exception ex) {
+ LOG.log(Level.SEVERE, "Pooop!", ex);
+ }
+ }
+
+ /**
+ * Remove node. Generate remove event if needed.
+ */
+ private void removeChildNode(final String nodePath) {
+ synchronized (syncObject) {
+ if (childMzxid.containsKey(nodePath)) {
+ childMzxid.remove(nodePath);
+ generateRemoveEvent(nodePath);
+ }
+ }
+ }
+
+ /**
+ * Invoke nodeCreated on listener
+ */
+ private void generateCreateEvent(final String nodePath, final String data) {
+ try {
+ listener.nodeCreated(nodePath, data);
+ } catch (final Exception exception) {
+ LOG.log(Level.WARNING, "Got exception calling listener.nodeCreated", exception);
+ }
+ }
+
+ /**
+ * Invoke dataChanged on listener
+ */
+ private void generateDataChangeEvent(final String nodePath, final String data) {
+ try {
+ listener.dataChanged(nodePath, data);
+ } catch (final Exception exception) {
+ LOG.log(Level.WARNING, "Got exception calling listener.dataChanged", exception);
+ }
+ }
+
+ /**
+ * Invoke nodeRemoved on listener
+ */
+ private void generateRemoveEvent(final String nodePath) {
+ try {
+ listener.nodeRemoved(nodePath);
+ } catch (final Exception exception) {
+ LOG.log(Level.WARNING, "Got exception calling listener.nodeRemoved", exception);
+ }
+ }
+}
diff --git a/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeWatcherListener.java b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeWatcherListener.java
new file mode 100644
index 00000000..91e6a77c
--- /dev/null
+++ b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeWatcherListener.java
@@ -0,0 +1,38 @@
+package org.cloudname.backends.zookeeper;
+
+/**
+ * Listener interface for node change events
+ *
+ * @author [email protected]
+ */
+public interface NodeWatcherListener {
+ /**
+ * A node is created. Note that rapid changes with create, data update (and even
+ * create + delete + create + data change might yield just one create notification.
+ *
+ * @param zkPath path to node
+ * @param data data of node
+ */
+ void nodeCreated(final String zkPath, final String data);
+
+ /**
+ * Data on a node is changed. Note that you might not get data change notifications
+ * for nodes that are created and updated within a short time span, only a create
+ * notification.
+ * Nodes that are created, deleted, then recreated will also generate this event, even if
+ * the data is unchanged.
+ *
+ * @param zkPath path of node
+ * @param data data of node
+ */
+ void dataChanged(final String zkPath, final String data);
+
+ /**
+ * Node is removed.
+ *
+ * @param zkPath Path of the node that is removed.
+ */
+ void nodeRemoved(final String zkPath);
+}
+
+
diff --git a/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/ZooKeeperBackend.java b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/ZooKeeperBackend.java
new file mode 100644
index 00000000..d51632d8
--- /dev/null
+++ b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/ZooKeeperBackend.java
@@ -0,0 +1,342 @@
+package org.cloudname.backends.zookeeper;
+import com.google.common.base.Charsets;
+import org.apache.curator.RetryPolicy;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.ExponentialBackoffRetry;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.data.Stat;
+import org.cloudname.core.CloudnameBackend;
+import org.cloudname.core.CloudnamePath;
+import org.cloudname.core.LeaseHandle;
+import org.cloudname.core.LeaseListener;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * A ZooKeeper backend for Cloudname. Leases are represented as nodes; client leases are ephemeral
+ * nodes inside container nodes and permanent leases are container nodes.
+ *
+ * @author [email protected]
+ */
+public class ZooKeeperBackend implements CloudnameBackend {
+ private static final Logger LOG = Logger.getLogger(ZooKeeperBackend.class.getName());
+ private static final String TEMPORARY_ROOT = "/cn/temporary/";
+ private static final String PERMANENT_ROOT = "/cn/permanent/";
+ private static final int CONNECTION_TIMEOUT_SECONDS = 30;
+
+ // PRNG for instance names. These will be "random enough" for instance identifiers
+ private final Random random = new Random();
+ private final CuratorFramework curator;
+ private final Map<LeaseListener, NodeCollectionWatcher> clientListeners = new HashMap<>();
+ private final Map<LeaseListener, NodeCollectionWatcher> permanentListeners = new HashMap<>();
+ private final Object syncObject = new Object();
+ /**
+ * @param connectionString ZooKeeper connection string
+ * @throws IllegalStateException if the cluster isn't available.
+ */
+ public ZooKeeperBackend(final String connectionString) {
+ final RetryPolicy retryPolicy = new ExponentialBackoffRetry(200, 10);
+ curator = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
+ curator.start();
+
+ try {
+ curator.blockUntilConnected(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ LOG.info("Connected to zk cluster @ " + connectionString);
+ } catch (final InterruptedException ie) {
+ throw new IllegalStateException("Could not connect to ZooKeeper", ie);
+ }
+ }
+
+ @Override
+ public LeaseHandle createTemporaryLease(final CloudnamePath path, final String data) {
+ boolean created = false;
+ CloudnamePath tempInstancePath = null;
+ String tempZkPath = null;
+ while (!created) {
+ final long instanceId = random.nextLong();
+ tempInstancePath = new CloudnamePath(path, Long.toHexString(instanceId));
+ tempZkPath = TEMPORARY_ROOT + tempInstancePath.join('/');
+ try {
+
+ curator.create()
+ .creatingParentContainersIfNeeded()
+ .withMode(CreateMode.EPHEMERAL)
+ .forPath(tempZkPath, data.getBytes(Charsets.UTF_8));
+ created = true;
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Could not create client node at " + tempInstancePath, ex);
+ }
+ }
+ final CloudnamePath instancePath = tempInstancePath;
+ final String zkInstancePath = tempZkPath;
+ return new LeaseHandle() {
+ private AtomicBoolean closed = new AtomicBoolean(false);
+
+ @Override
+ public boolean writeLeaseData(final String data) {
+ if (closed.get()) {
+ LOG.info("Attempt to write data to closed leased handle " + data);
+ return false;
+ }
+ return writeTemporaryLeaseData(instancePath, data);
+ }
+
+ @Override
+ public CloudnamePath getLeasePath() {
+ if (closed.get()) {
+ return null;
+ }
+ return instancePath;
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (closed.get()) {
+ return;
+ }
+ try {
+ curator.delete().forPath(zkInstancePath);
+ closed.set(true);
+ } catch (final Exception ex) {
+ throw new IOException(ex);
+ }
+ }
+ };
+ }
+
+ @Override
+ public boolean writeTemporaryLeaseData(final CloudnamePath path, final String data) {
+ final String zkPath = TEMPORARY_ROOT + path.join('/');
+ try {
+ final Stat nodeStat = curator.checkExists().forPath(zkPath);
+ if (nodeStat == null) {
+ LOG.log(Level.WARNING, "Could not write client lease data for " + path
+ + " with data since the path does not exist. Data = " + data);
+ }
+ curator.setData().forPath(zkPath, data.getBytes(Charsets.UTF_8));
+ return true;
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Got exception writing lease data to " + path
+ + " with data " + data);
+ return false;
+ }
+ }
+
+ @Override
+ public String readTemporaryLeaseData(final CloudnamePath path) {
+ if (path == null) {
+ return null;
+ }
+ final String zkPath = TEMPORARY_ROOT + path.join('/');
+ try {
+ curator.sync().forPath(zkPath);
+ final byte[] bytes = curator.getData().forPath(zkPath);
+ return new String(bytes, Charsets.UTF_8);
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Got exception reading client lease data at " + path, ex);
+ }
+ return null;
+ }
+
+ private CloudnamePath toCloudnamePath(final String zkPath, final String pathPrefix) {
+ final String clientPath = zkPath.substring(pathPrefix.length());
+ final String[] elements = clientPath.split("/");
+ return new CloudnamePath(elements);
+ }
+
+ @Override
+ public void addTemporaryLeaseListener(
+ final CloudnamePath pathToObserve, final LeaseListener listener) {
+ // Ideally the PathChildrenCache class in Curator would be used here to keep track of the
+ // changes but it is ever so slightly broken and misses most of the watches that ZooKeeper
+ // triggers, ignores the mzxid on the nodes and generally makes a mess of things. Enter
+ // custom code.
+ final String zkPath = TEMPORARY_ROOT + pathToObserve.join('/');
+ try {
+ curator.createContainers(zkPath);
+ final NodeCollectionWatcher watcher = new NodeCollectionWatcher(curator.getZookeeperClient().getZooKeeper(),
+ zkPath,
+ new NodeWatcherListener() {
+ @Override
+ public void nodeCreated(final String path, final String data) {
+ listener.leaseCreated(toCloudnamePath(path, TEMPORARY_ROOT), data);
+ }
+ @Override
+ public void dataChanged(final String path, final String data) {
+ listener.dataChanged(toCloudnamePath(path, TEMPORARY_ROOT), data);
+ }
+ @Override
+ public void nodeRemoved(final String path) {
+ listener.leaseRemoved(toCloudnamePath(path, TEMPORARY_ROOT));
+ }
+ });
+
+ synchronized (syncObject) {
+ clientListeners.put(listener, watcher);
+ }
+ } catch (final Exception exception) {
+ LOG.log(Level.WARNING, "Got exception when creating node watcher", exception);
+ }
+ }
+
+ @Override
+ public void removeTemporaryLeaseListener(final LeaseListener listener) {
+ synchronized (syncObject) {
+ final NodeCollectionWatcher watcher = clientListeners.get(listener);
+ if (watcher != null) {
+ clientListeners.remove(listener);
+ watcher.shutdown();
+ }
+ }
+ }
+
+ @Override
+ public boolean createPermanantLease(final CloudnamePath path, final String data) {
+ final String zkPath = PERMANENT_ROOT + path.join('/');
+ try {
+ curator.sync().forPath(zkPath);
+ final Stat nodeStat = curator.checkExists().forPath(zkPath);
+ if (nodeStat == null) {
+ curator.create()
+ .creatingParentContainersIfNeeded()
+ .forPath(zkPath, data.getBytes(Charsets.UTF_8));
+ return true;
+ }
+ LOG.log(Level.INFO, "Attempt to create permanent node at " + path
+ + " with data " + data + " but it already exists");
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Got exception creating parent container for permanent lease"
+ + " for lease " + path + " with data " + data, ex);
+ }
+ return false;
+ }
+
+ @Override
+ public boolean removePermanentLease(final CloudnamePath path) {
+ final String zkPath = PERMANENT_ROOT + path.join('/');
+ try {
+ final Stat nodeStat = curator.checkExists().forPath(zkPath);
+ if (nodeStat != null) {
+ curator.delete()
+ .withVersion(nodeStat.getVersion())
+ .forPath(zkPath);
+ return true;
+ }
+ return false;
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Got error removing permanent lease for lease " + path, ex);
+ return false;
+ }
+ }
+
+ @Override
+ public boolean writePermanentLeaseData(final CloudnamePath path, final String data) {
+ final String zkPath = PERMANENT_ROOT + path.join('/');
+ try {
+ curator.sync().forPath(zkPath);
+ final Stat nodeStat = curator.checkExists().forPath(zkPath);
+ if (nodeStat == null) {
+ LOG.log(Level.WARNING, "Can't write permanent lease data for lease " + path
+ + " with data " + data + " since the lease doesn't exist");
+ return false;
+ }
+ curator.setData()
+ .withVersion(nodeStat.getVersion())
+ .forPath(zkPath, data.getBytes(Charsets.UTF_8));
+ } catch (final Exception ex) {
+ LOG.log(Level.WARNING, "Got exception writing permanent lease data for " + path
+ + " with data " + data, ex);
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String readPermanentLeaseData(final CloudnamePath path) {
+ final String zkPath = PERMANENT_ROOT + path.join('/');
+ try {
+ curator.sync().forPath(zkPath);
+ final byte[] bytes = curator.getData().forPath(zkPath);
+ return new String(bytes, Charsets.UTF_8);
+ } catch (final Exception ex) {
+ if (ex instanceof KeeperException.NoNodeException) {
+ // OK - nothing to worry about
+ return null;
+ }
+ LOG.log(Level.WARNING, "Got exception reading permanent lease data for " + path, ex);
+ return null;
+ }
+ }
+
+ @Override
+ public void addPermanentLeaseListener(final CloudnamePath pathToObserve, final LeaseListener listener) {
+ try {
+
+ final String parentPath = PERMANENT_ROOT + pathToObserve.getParent().join('/');
+ final String fullPath = PERMANENT_ROOT + pathToObserve.join('/');
+ curator.createContainers(parentPath);
+ final NodeCollectionWatcher watcher = new NodeCollectionWatcher(curator.getZookeeperClient().getZooKeeper(),
+ parentPath,
+ new NodeWatcherListener() {
+ @Override
+ public void nodeCreated(final String path, final String data) {
+ if (path.equals(fullPath)) {
+ listener.leaseCreated(toCloudnamePath(path, PERMANENT_ROOT), data);
+ }
+ }
+ @Override
+ public void dataChanged(final String path, final String data) {
+ if (path.equals(fullPath)) {
+ listener.dataChanged(toCloudnamePath(path, PERMANENT_ROOT), data);
+ }
+ }
+ @Override
+ public void nodeRemoved(final String path) {
+ if (path.equals(fullPath)) {
+ listener.leaseRemoved(toCloudnamePath(path, PERMANENT_ROOT));
+ }
+ }
+ });
+
+ synchronized (syncObject) {
+ permanentListeners.put(listener, watcher);
+ }
+ } catch (final Exception exception) {
+ LOG.log(Level.WARNING, "Got exception when creating node watcher", exception);
+ }
+ }
+
+ @Override
+ public void removePermanentLeaseListener(final LeaseListener listener) {
+ synchronized (syncObject) {
+ final NodeCollectionWatcher watcher = permanentListeners.get(listener);
+ if (watcher != null) {
+ permanentListeners.remove(listener);
+ watcher.shutdown();
+ }
+ }
+ }
+
+ @Override
+ public void close() {
+ synchronized (syncObject) {
+ for (final NodeCollectionWatcher watcher : clientListeners.values()) {
+ watcher.shutdown();
+ }
+ clientListeners.clear();
+ for (final NodeCollectionWatcher watcher : permanentListeners.values()) {
+ watcher.shutdown();
+ }
+ permanentListeners.clear();
+ }
+ }
+}
diff --git a/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/NodeCollectionWatcherTest.java b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/NodeCollectionWatcherTest.java
new file mode 100644
index 00000000..adb41310
--- /dev/null
+++ b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/NodeCollectionWatcherTest.java
@@ -0,0 +1,367 @@
+package org.cloudname.backends.zookeeper;
+
+import org.apache.curator.CuratorConnectionLossException;
+import org.apache.curator.RetryPolicy;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.RetryUntilElapsed;
+import org.apache.curator.test.InstanceSpec;
+import org.apache.curator.test.TestingCluster;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.data.Stat;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.nio.charset.Charset;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeThat;
+
+/**
+ * Test the node watching mechanism.
+ */
+public class NodeCollectionWatcherTest {
+ private static TestingCluster zkServer;
+ private static CuratorFramework curator;
+ private static ZooKeeper zooKeeper;
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ zkServer = new TestingCluster(3);
+ zkServer.start();
+ final RetryPolicy retryPolicy = new RetryUntilElapsed(60000, 100);
+ curator = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), retryPolicy);
+ curator.start();
+ curator.blockUntilConnected(10, TimeUnit.SECONDS);
+ zooKeeper = curator.getZookeeperClient().getZooKeeper();
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ zkServer.close();
+ }
+
+ private final AtomicInteger counter = new AtomicInteger(0);
+
+ private byte[] getData() {
+ return ("" + counter.incrementAndGet()).getBytes(Charset.defaultCharset());
+ }
+
+ /**
+ * A custom listener that counts and counts down notifications.
+ */
+ private class ListenerCounter implements NodeWatcherListener {
+ // Then a few counters to check the number of events
+ public AtomicInteger createCount = new AtomicInteger(0);
+ public AtomicInteger dataCount = new AtomicInteger(0);
+ public AtomicInteger removeCount = new AtomicInteger(0);
+ public CountDownLatch createLatch;
+ public CountDownLatch dataLatch;
+ public CountDownLatch removeLatch;
+
+ public ListenerCounter(final int createLatchCount, final int dataLatchCount, final int removeLatchCount) {
+ createLatch = new CountDownLatch(createLatchCount);
+ dataLatch = new CountDownLatch(dataLatchCount);
+ removeLatch = new CountDownLatch(removeLatchCount);
+ }
+
+ @Override
+ public void nodeCreated(String zkPath, String data) {
+ createCount.incrementAndGet();
+ createLatch.countDown();
+ }
+
+ @Override
+ public void dataChanged(String zkPath, String data) {
+ dataCount.incrementAndGet();
+ dataLatch.countDown();
+ }
+
+ @Override
+ public void nodeRemoved(String zkPath) {
+ removeCount.incrementAndGet();
+ removeLatch.countDown();
+ }
+ }
+
+ @Test
+ public void sequentialNotifications() throws Exception {
+ final int maxPropagationTime = 4;
+
+ final String pathPrefix = "/foo/slow";
+ curator.create().creatingParentsIfNeeded().forPath(pathPrefix);
+
+ final ListenerCounter listener = new ListenerCounter(1, 1, 1);
+
+ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener);
+
+ // Create should trigger create notification (and no other notification)
+ curator.create().forPath(pathPrefix + "/node1", getData());
+ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(1));
+ assertThat(listener.dataCount.get(), is(0));
+ assertThat(listener.removeCount.get(), is(0));
+
+ // Data change should trigger the data notification (and no other notification)
+ curator.setData().forPath(pathPrefix + "/node1", getData());
+ assertTrue(listener.dataLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(1));
+ assertThat(listener.dataCount.get(), is(1));
+ assertThat(listener.removeCount.get(), is(0));
+
+ // Delete should trigger the remove notification (and no other notification)
+ curator.delete().forPath(pathPrefix + "/node1");
+ assertTrue(listener.removeLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(1));
+ assertThat(listener.dataCount.get(), is(1));
+ assertThat(listener.removeCount.get(), is(1));
+
+ nodeCollectionWatcher.shutdown();
+
+ // Ensure that there are no notifications when the watcher shuts down
+ curator.create().forPath(pathPrefix + "node_9", getData());
+ Thread.sleep(maxPropagationTime);
+ assertThat(listener.createCount.get(), is(1));
+ assertThat(listener.dataCount.get(), is(1));
+ assertThat(listener.removeCount.get(), is(1));
+
+ curator.setData().forPath(pathPrefix + "node_9", getData());
+ Thread.sleep(maxPropagationTime);
+ assertThat(listener.createCount.get(), is(1));
+ assertThat(listener.dataCount.get(), is(1));
+ assertThat(listener.removeCount.get(), is(1));
+
+ curator.delete().forPath(pathPrefix + "node_9");
+ Thread.sleep(maxPropagationTime);
+ assertThat(listener.createCount.get(), is(1));
+ assertThat(listener.dataCount.get(), is(1));
+ assertThat(listener.removeCount.get(), is(1));
+ }
+
+ /**
+ * Make rapid changes to ZooKeeper. The changes (most likely) won't be caught by the
+ * watcher events but must be generated by the class itself. Ensure the correct number
+ * of notifications is generated.
+ */
+ @Test
+ public void rapidChanges() throws Exception {
+ final int maxPropagationTime = 100;
+
+ final String pathPrefix = "/foo/rapido";
+
+ curator.create().creatingParentsIfNeeded().forPath(pathPrefix);
+
+ final int numNodes = 50;
+ final ListenerCounter listener = new ListenerCounter(numNodes, 0, numNodes);
+
+ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener);
+ // Create all of the nodes at once
+ for (int i = 0; i < numNodes; i++) {
+ curator.create().forPath(pathPrefix + "/node" + i, getData());
+ }
+ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(numNodes));
+ assertThat(listener.dataCount.get(), is(0));
+ assertThat(listener.removeCount.get(), is(0));
+
+ // Repeat data test multiple times to ensure data changes are detected
+ // repeatedly on the same nodes
+ int total = 0;
+ for (int j = 0; j < 5; j++) {
+ listener.dataLatch = new CountDownLatch(numNodes);
+ // Since there's a watch for every node all of the data changes should be detected
+ for (int i = 0; i < numNodes; i++) {
+ curator.setData().forPath(pathPrefix + "/node" + i, getData());
+ }
+ total += numNodes;
+ assertTrue(listener.dataLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(numNodes));
+ assertThat(listener.dataCount.get(), is(total));
+ assertThat(listener.removeCount.get(), is(0));
+ }
+
+ // Finally, remove everything in rapid succession
+ // Create all of the nodes at once
+ for (int i = 0; i < numNodes; i++) {
+ curator.delete().forPath(pathPrefix + "/node" + i);
+ }
+
+ assertTrue(listener.removeLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(numNodes));
+ assertThat(listener.dataCount.get(), is(total));
+ assertThat(listener.removeCount.get(), is(numNodes));
+
+ nodeCollectionWatcher.shutdown();
+ }
+
+ /**
+ * Emulate a network partition by killing off two out of three ZooKeeper instances
+ * and check the output. Set the system property NodeWatcher.SlowTests to "ok" to enable
+ * it. The test itself can be quite slow depending on what Curator is connected to. If
+ * Curator uses one of the servers that are killed it will try a reconnect and the whole
+ * test might take up to 120-180 seconds to complete.
+ */
+ @Test
+ public void networkPartitionTest() throws Exception {
+ assumeThat(System.getProperty("NodeCollectionWatcher.SlowTests"), is("ok"));
+
+ final int maxPropagationTime = 10;
+
+ final String pathPrefix = "/foo/partition";
+ curator.create().creatingParentsIfNeeded().forPath(pathPrefix);
+
+ final int nodeCount = 10;
+
+ final ListenerCounter listener = new ListenerCounter(nodeCount, nodeCount, nodeCount);
+
+ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener);
+
+ // Create a few nodes to set the initial state
+ for (int i = 0; i < nodeCount; i++) {
+ curator.create().forPath(pathPrefix + "/node" + i, getData());
+ }
+ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(nodeCount));
+ assertThat(listener.removeCount.get(), is(0));
+ assertThat(listener.dataCount.get(), is(0));
+
+ final InstanceSpec firstInstance = zkServer.findConnectionInstance(zooKeeper);
+ zkServer.killServer(firstInstance);
+
+ listener.createLatch = new CountDownLatch(1);
+ // Client should reconnect to one of the two remaining
+ curator.create().forPath(pathPrefix + "/stillalive", getData());
+ // Wait for the notification to go through. This could take some time since there's
+ // reconnects and all sorts of magic happening under the hood
+ assertTrue(listener.createLatch.await(10, TimeUnit.SECONDS));
+ assertThat(listener.createCount.get(), is(nodeCount + 1));
+ assertThat(listener.removeCount.get(), is(0));
+ assertThat(listener.dataCount.get(), is(0));
+
+ // Kill the 2nd server. The cluster won't have a quorum now
+ final InstanceSpec secondInstance = zkServer.findConnectionInstance(zooKeeper);
+ assertThat(firstInstance, is(not(secondInstance)));
+ zkServer.killServer(secondInstance);
+
+ boolean retry;
+ do {
+ System.out.println("Checking node with Curator... This might take a while...");
+ try {
+ final Stat stat = curator.checkExists().forPath(pathPrefix);
+ retry = false;
+ assertThat(stat, is(notNullValue()));
+ } catch (CuratorConnectionLossException ex) {
+ System.out.println("Missing connection. Retrying");
+ retry = true;
+ }
+ } while (retry);
+
+ zkServer.restartServer(firstInstance);
+ zkServer.restartServer(secondInstance);
+ listener.createLatch = new CountDownLatch(1);
+
+ System.out.println("Creating node via Curator... This might take a while...");
+ curator.create().forPath(pathPrefix + "/imback", getData());
+
+ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(nodeCount + 2));
+ assertThat(listener.removeCount.get(), is(0));
+ assertThat(listener.dataCount.get(), is(0));
+
+ // Ensure data notifications are propagated after a failure
+ for (int i = 0; i < nodeCount; i++) {
+ final Stat stat = curator.setData().forPath(pathPrefix + "/node" + i, getData());
+ assertThat(stat, is(notNullValue()));
+ }
+ assertTrue(listener.dataLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(nodeCount + 2));
+ assertThat(listener.removeCount.get(), is(0));
+ assertThat(listener.dataCount.get(), is(nodeCount));
+
+ // ..and remove notifications are sent
+ for (int i = 0; i < nodeCount; i++) {
+ curator.delete().forPath(pathPrefix + "/node" + i);
+ }
+ assertTrue(listener.removeLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS));
+ assertThat(listener.createCount.get(), is(nodeCount + 2));
+ assertThat(listener.removeCount.get(), is(nodeCount));
+ assertThat(listener.dataCount.get(), is(nodeCount));
+
+ nodeCollectionWatcher.shutdown();
+
+ }
+
+ /**
+ * Be a misbehaving client and throw exceptions in the listners. Ensure the watcher still works
+ * afterwards.
+ */
+ @Test
+ public void misbehavingClient() throws Exception {
+ final int propagationTime = 5;
+
+ final AtomicBoolean triggerExceptions = new AtomicBoolean(false);
+ final CountDownLatch createLatch = new CountDownLatch(1);
+ final CountDownLatch dataLatch = new CountDownLatch(1);
+ final CountDownLatch removeLatch = new CountDownLatch(1);
+
+ final NodeWatcherListener listener = new NodeWatcherListener() {
+ @Override
+ public void nodeCreated(String zkPath, String data) {
+ if (triggerExceptions.get()) {
+ throw new RuntimeException("boo!");
+ }
+ createLatch.countDown();
+ }
+
+ @Override
+ public void dataChanged(String zkPath, String data) {
+ if (triggerExceptions.get()) {
+ throw new RuntimeException("boo!");
+ }
+ dataLatch.countDown();
+ }
+
+ @Override
+ public void nodeRemoved(String zkPath) {
+ if (triggerExceptions.get()) {
+ throw new RuntimeException("boo!");
+ }
+ removeLatch.countDown();
+ }
+ };
+
+ final String pathPrefix = "/foo/misbehaving";
+
+ curator.create().creatingParentsIfNeeded().forPath(pathPrefix);
+
+ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener);
+
+ triggerExceptions.set(true);
+ curator.create().forPath(pathPrefix + "/first", getData());
+ Thread.sleep(propagationTime);
+ curator.setData().forPath(pathPrefix + "/first", getData());
+ Thread.sleep(propagationTime);
+ curator.delete().forPath(pathPrefix + "/first");
+ Thread.sleep(propagationTime);
+
+ // Now create a node but without setting the data field.
+ triggerExceptions.set(false);
+ curator.create().forPath(pathPrefix + "/second");
+ assertTrue(createLatch.await(propagationTime, TimeUnit.MILLISECONDS));
+ curator.setData().forPath(pathPrefix + "/second", getData());
+ assertTrue(dataLatch.await(propagationTime, TimeUnit.MILLISECONDS));
+ curator.delete().forPath(pathPrefix + "/second");
+ assertTrue(removeLatch.await(propagationTime, TimeUnit.MILLISECONDS));
+
+ nodeCollectionWatcher.shutdown();
+ }
+}
diff --git a/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/ZooKeeperBackendTest.java b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/ZooKeeperBackendTest.java
new file mode 100644
index 00000000..393b78b4
--- /dev/null
+++ b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/ZooKeeperBackendTest.java
@@ -0,0 +1,36 @@
+package org.cloudname.backends.zookeeper;
+
+import org.apache.curator.test.TestingCluster;
+import org.cloudname.core.CloudnameBackend;
+import org.cloudname.testtools.backend.CoreBackendTest;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Test the ZooKeeper backend.
+ */
+public class ZooKeeperBackendTest extends CoreBackendTest {
+ private static TestingCluster testCluster;
+ private AtomicReference<ZooKeeperBackend> backend = new AtomicReference<>(null);
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ testCluster = new TestingCluster(3);
+ testCluster.start();
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ testCluster.stop();
+ }
+
+ protected CloudnameBackend getBackend() {
+ if (backend.get() == null) {
+ backend.compareAndSet(null, new ZooKeeperBackend(testCluster.getConnectString()));
+ }
+ return backend.get();
+
+ }
+}
diff --git a/cn/pom.xml b/cn/pom.xml
deleted file mode 100644
index f46d83ff..00000000
--- a/cn/pom.xml
+++ /dev/null
@@ -1,93 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.cloudname</groupId>
- <artifactId>cloudname-parent</artifactId>
- <version>3.0-SNAPSHOT</version>
- </parent>
-
- <artifactId>cn</artifactId>
- <packaging>jar</packaging>
-
- <name>Cloudname Library</name>
- <description>Simple library for managing resources using ZooKeeper.</description>
- <url>https://github.com/Cloudname/cloudname</url>
-
- <dependencies>
- <dependency>
- <groupId>org.cloudname</groupId>
- <artifactId>testtools</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.zookeeper</groupId>
- <artifactId>zookeeper</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.cloudname</groupId>
- <artifactId>flags</artifactId>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit-dep</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-all</artifactId>
- <version>1.3</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.dstovall</groupId>
- <artifactId>onejar-maven-plugin</artifactId>
- <version>1.4.4</version>
- <executions>
- <execution>
- <configuration>
- <!-- Optional, default is false -->
- <attachToBuild>true</attachToBuild>
- <mainClass>org.cloudname.zk.ZkTool</mainClass>
- <filename>ZkTool.jar</filename>
- </configuration>
- <goals>
- <goal>one-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- </plugin>
- <plugin>
- <artifactId>maven-failsafe-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/cn/src/integrationtest/java/org/cloudname/zk/ZkCloudnameIntegrationTest.java b/cn/src/integrationtest/java/org/cloudname/zk/ZkCloudnameIntegrationTest.java
deleted file mode 100644
index b5d7daaa..00000000
--- a/cn/src/integrationtest/java/org/cloudname/zk/ZkCloudnameIntegrationTest.java
+++ /dev/null
@@ -1,480 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.cloudname.Cloudname;
-import org.cloudname.CloudnameException;
-import org.cloudname.Coordinate;
-import org.cloudname.CoordinateException;
-import org.cloudname.CoordinateExistsException;
-import org.cloudname.CoordinateListener;
-import org.cloudname.ServiceHandle;
-import org.cloudname.ServiceState;
-import org.cloudname.ServiceStatus;
-import org.cloudname.testtools.Net;
-import org.cloudname.testtools.network.PortForwarder;
-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Logger;
-
-import static org.junit.Assert.*;
-
-/**
- * Integration tests for testing ZkCloudname.
- * Contains mostly heavy tests containing sleep calls not fit as a unit test.
- */
-public class ZkCloudnameIntegrationTest {
- private static final Logger LOG = Logger.getLogger(ZkCloudnameIntegrationTest.class.getName());
-
- private EmbeddedZooKeeper ezk;
- private ZooKeeper zk;
- private int zkport;
- private PortForwarder forwarder = null;
- private int forwarderPort;
- private ZkCloudname cn = null;
-
- @Rule
- public TemporaryFolder temp = new TemporaryFolder();
-
- /**
- * Set up an embedded ZooKeeper instance backed by a temporary
- * directory. The setup procedure also allocates a port that is
- * free for the ZooKeeper server so that you should be able to run
- * multiple instances of this test.
- */
- @Before
- public void setup() throws Exception {
- File rootDir = temp.newFolder("zk-test");
- zkport = Net.getFreePort();
-
- LOG.info("EmbeddedZooKeeper rootDir=" + rootDir.getCanonicalPath() + ", port=" + zkport);
-
- // Set up and initialize the embedded ZooKeeper
- ezk = new EmbeddedZooKeeper(rootDir, zkport);
- ezk.init();
-
- // Set up a zookeeper client that we can use for inspection
- final CountDownLatch connectedLatch = new CountDownLatch(1);
-
- zk = new ZooKeeper("localhost:" + zkport, 1000, new Watcher() {
- @Override
- public void process(WatchedEvent event) {
- if (event.getState() == Event.KeeperState.SyncConnected) {
- connectedLatch.countDown();
- }
- }
- });
- connectedLatch.await();
-
- LOG.info("ZooKeeper port is " + zkport);
- }
-
- @After
- public void tearDown() throws Exception {
- zk.close();
- if (forwarder != null) {
- forwarder.close();
- }
- ezk.shutdown();
- }
-
- /**
- * A coordinate listener that stores events and calls a latch.
- */
- class TestCoordinateListener implements CoordinateListener {
- private final List<Event> events = new CopyOnWriteArrayList<Event>();
-
- private final Set<CountDownLatch> listenerLatches;
-
- private final List<Event> waitForEvent = new ArrayList<Event>();
- private final Object eventMonitor = new Object();
- private final List<CountDownLatch> waitForLatch = new ArrayList<CountDownLatch>();
-
- public boolean failOnWrongEvent = false;
- private CountDownLatch latestLatch = null;
-
- void waitForExpected() throws InterruptedException {
- final CountDownLatch latch;
- synchronized (eventMonitor) {
- if (waitForEvent.size() > 0) {
- LOG.info("Waiting for event " + waitForEvent.get(waitForEvent.size() - 1));
- latch = latestLatch;
- } else {
- return;
- }
- }
- assert(latch.await(25, TimeUnit.SECONDS));
- LOG.info("Event happened.");
- }
-
- public TestCoordinateListener(final Set<CountDownLatch> listenerLatches) {
- this.listenerLatches = listenerLatches;
- }
-
- public void expectEvent(final Event event) {
- LOG.info("Expecting event " + event.name());
- synchronized (eventMonitor) {
- waitForEvent.add(event);
- latestLatch = new CountDownLatch(1);
- waitForLatch.add(latestLatch);
- }
- }
-
- @Override
- public void onCoordinateEvent(Event event, String message) {
- LOG.info("I got event ..." + event.name() + " " + message);
- synchronized (eventMonitor) {
- if (waitForEvent.size() > 0) {
- LOG.info("Waiting for event " + waitForEvent.get(0));
- } else {
- LOG.info("not expecting any specific events");
- }
- events.add(event);
- for (CountDownLatch countDownLatch :listenerLatches) {
- countDownLatch.countDown();
- }
- if (waitForEvent.size() > 0 && waitForEvent.get(0) == event) {
- waitForLatch.remove(0).countDown();
- waitForEvent.remove(0);
- } else {
- assertFalse(failOnWrongEvent);
- }
- }
- }
- }
-
- private TestCoordinateListener setUpListenerEnvironment(
- final CountDownLatch latch) throws Exception {
- Set<CountDownLatch> latches = new HashSet<CountDownLatch>();
- latches.add(latch);
- return setUpListenerEnvironment(latches);
- }
-
- private TestCoordinateListener setUpListenerEnvironment(
- final Set<CountDownLatch> listenerLatches) throws Exception {
- forwarderPort = Net.getFreePort();
- forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);
- final Coordinate c = Coordinate.parse("1.service.user.cell");
-
- cn = makeLocalZkCloudname(forwarderPort);
- try {
- cn.createCoordinate(c);
- } catch (CoordinateException e) {
- fail(e.toString());
- }
- final TestCoordinateListener listener = new TestCoordinateListener(listenerLatches);
- ServiceHandle serviceHandle = cn.claim(c);
- assert(serviceHandle.waitForCoordinateOkSeconds(3 /* secs */));
- serviceHandle.registerCoordinateListener(listener);
-
- return listener;
- }
-
- @Test
- public void testCoordinateListenerInitialEvent() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(15, TimeUnit.SECONDS));
- assertEquals(1, listener.events.size());
- assertEquals(CoordinateListener.Event.COORDINATE_OK, listener.events.get(0));
- }
-
- @Test
- public void testCoordinateListenerConnectionDies() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
-
- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE);
- forwarder.close();
- forwarder = null;
- listener.waitForExpected();
- }
-
- @Test
- public void testCoordinateListenerCoordinateCorrupted() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
-
- listener.expectEvent(CoordinateListener.Event.NOT_OWNER);
-
- byte[] garbageBytes = "sdfgsdfgsfgdsdfgsdfgsdfg".getBytes("UTF-16LE");
-
- zk.setData("/cn/cell/user/service/1/status", garbageBytes, -1);
- listener.waitForExpected();
- }
-
- @Test
- public void testCoordinateListenerCoordinateOutOfSync() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
-
- listener.expectEvent(CoordinateListener.Event.NOT_OWNER);
-
- String source = "\"{\\\"state\\\":\\\"STARTING\\\",\\\"message\\\":\\\"Lost hamster.\\\"}\" {}";
- byte[] byteArray = source.getBytes(Util.CHARSET_NAME);
-
- zk.setData("/cn/cell/user/service/1/status", byteArray, -1);
-
- listener.waitForExpected();
- }
-
- @Test
- public void testCoordinateListenerCoordinateLost() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE);
- listener.expectEvent(CoordinateListener.Event.NOT_OWNER);
-
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
- LOG.info("Deleting coordinate");
- forwarder.pause();
- zk.delete("/cn/cell/user/service/1/status", -1);
- zk.delete("/cn/cell/user/service/1/config", -1);
- zk.delete("/cn/cell/user/service/1", -1);
- forwarder.unpause();
-
- listener.waitForExpected();
-
- }
-
- @Test
- public void testCoordinateListenerStolenCoordinate() throws Exception {
-
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
- LOG.info("Killing zookeeper");
- assertTrue(zk.getState() == ZooKeeper.States.CONNECTED);
-
- LOG.info("Killing connection");
- forwarder.pause();
-
- zk.delete("/cn/cell/user/service/1/status", -1);
- Util.mkdir(zk, "/cn/cell/user/service/1/status" , ZooDefs.Ids.OPEN_ACL_UNSAFE);
-
- forwarder.unpause();
-
- listener.expectEvent(CoordinateListener.Event.NOT_OWNER);
- listener.waitForExpected();
- }
-
-
- @Test
- public void testCoordinateListenerConnectionDiesReconnect() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
-
- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE);
-
- forwarder.pause();
- listener.waitForExpected();
-
- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK);
- forwarder.unpause();
- listener.waitForExpected();
- }
-
- /**
- * In this test the ZK server thinks the client is connected, but the client wants to reconnect
- * due to a disconnect. To trig this condition the connection needs to be down for
- * a specific time. This test does not fail even if it does not manage to create this
- * state. It will write the result to the log. The test is useful for development and
- * should not fail.
- */
- @Test
- public void testCoordinateListenerConnectionDiesReconnectAfterTimeoutClient()
- throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
- assertEquals(CoordinateListener.Event.COORDINATE_OK,
- listener.events.get(listener.events.size() -1 ));
-
- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE);
- LOG.info("Killing connection");
- forwarder.pause();
-
- LOG.info("Connection down.");
- listener.waitForExpected();
-
- // Client sees problem, server not.
- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK);
-
- // 3400 is a magic number for getting zookeeper and local client in a specific state.
- Thread.sleep(2400);
- LOG.info("Recreating connection soon" + forwarderPort + "->" + zkport);
-
-
- forwarder.unpause();
- listener.waitForExpected(); // COORDINATE_OK
-
- // If the previous event is NOT_OWNER, the wanted situation was created by the test.
- if (listener.events.get(listener.events.size() - 2) ==
- CoordinateListener.Event.NOT_OWNER) {
- LOG.info("Manage to trig event inn ZooKeeper, true positive.");
- } else {
- LOG.info("Did NOT manage to trig event in ZooKeeper. This depends on timing, so " +
- "ignoring this problem");
- }
- }
-
- @Test
- public void testCoordinateListenerConnectionDiesReconnectAfterTimeout() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
- assertEquals(CoordinateListener.Event.COORDINATE_OK,
- listener.events.get(listener.events.size() -1 ));
-
- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE);
-
- forwarder.close();
- forwarder = null;
- listener.waitForExpected();
- // We do not want NOT OWNER event from ZooKeeper. Therefore this long time out.
- LOG.info("Going into sleep, waiting for zookeeper to loose node");
- Thread.sleep(10000);
-
- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK);
- forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);
-
- // We need to re-instantiate the forwarder, or zookeeper thinks
- // the connection is good and will not kill the ephemeral node.
- // This is probably because we keep the server socket against zookeeper open
- // in pause mode.
-
- listener.waitForExpected();
- }
-
-
- /**
- * Tests the behavior of Zookeeper upon a restart. ZK should clean up old coordinates.
- * @throws Exception
- */
- @Test
- public void testZookeeperRestarts() throws Exception {
- final CountDownLatch connectedLatch1 = new CountDownLatch(1);
- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1);
- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
-
-
- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE);
- forwarder.pause();
- listener.waitForExpected();
-
- ezk.shutdown();
- ezk.del();
- ezk.init();
-
- listener.expectEvent(CoordinateListener.Event.NOT_OWNER);
-
- forwarder.unpause();
- listener.waitForExpected();
-
- createCoordinateWithRetries();
-
- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK);
- listener.waitForExpected();
- }
-
- private void createCoordinateWithRetries() throws CoordinateExistsException,
- InterruptedException, CloudnameException {
- Coordinate c = Coordinate.parse("1.service.user.cell");
- int retries = 10;
- for (;;) {
- try {
- cn.createCoordinate(c);
- break;
- } catch (CloudnameException e) {
- /*
- * CloudnameException indicates that the connection with
- * ZooKeeper isn't back up yet. Retry a few times.
- */
- if (retries-- > 0) {
- LOG.info("Failed to create coordinate: " + e
- + ", retrying in 1 second");
- Thread.sleep(1000);
- } else {
- throw e;
- }
- }
- }
- }
-
- /**
- * Tests that one process claims a coordinate, then another process tries to claim the same coordinate.
- * The first coordinate looses connection to ZooKeeper and the other process gets the coordinate.
- * @throws Exception
- */
- @Test
- public void testFastHardRestart() throws Exception {
- final Coordinate c = Coordinate.parse("1.service.user.cell");
- final CountDownLatch claimLatch1 = new CountDownLatch(1);
- forwarderPort = Net.getFreePort();
- forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);
- final Cloudname cn1 = new ZkCloudname.Builder().setConnectString(
- "localhost:" + forwarderPort).build().connect();
- cn1.createCoordinate(c);
-
- ServiceHandle handle1 = cn1.claim(c);
- handle1.registerCoordinateListener(new CoordinateListener() {
-
- @Override
- public void onCoordinateEvent(Event event, String message) {
- if (event == Event.COORDINATE_OK) {
- claimLatch1.countDown();
- }
- }
- });
- assertTrue(claimLatch1.await(5, TimeUnit.SECONDS));
-
- final Cloudname cn2 = new ZkCloudname.Builder().setConnectString(
- "localhost:" + zkport).build().connect();
-
- ServiceHandle handle2 = cn2.claim(c);
-
- forwarder.close();
- forwarder = null;
-
- assertTrue(handle2.waitForCoordinateOkSeconds(20));
-
- ServiceStatus status = new ServiceStatus(ServiceState.RUNNING, "updated status");
- handle2.setStatus(status);
-
- final Cloudname cn3 = new ZkCloudname.Builder().setConnectString("localhost:" + zkport)
- .build().connect();
- ServiceStatus statusRetrieved = cn3.getStatus(c);
- assertEquals("updated status", statusRetrieved.getMessage());
-
- cn1.close();
- cn2.close();
- cn3.close();
- }
-
- /**
- * Makes a local ZkCloudname instance with the port given by zkPort.
- * Then it connects to ZK.
- */
- private ZkCloudname makeLocalZkCloudname(int port) throws CloudnameException {
- return new ZkCloudname.Builder().setConnectString("localhost:" + port).build().connect();
- }
-}
diff --git a/cn/src/integrationtest/java/org/cloudname/zk/ZkResolverIntegrationTest.java b/cn/src/integrationtest/java/org/cloudname/zk/ZkResolverIntegrationTest.java
deleted file mode 100644
index b0a01517..00000000
--- a/cn/src/integrationtest/java/org/cloudname/zk/ZkResolverIntegrationTest.java
+++ /dev/null
@@ -1,420 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.*;
-import org.cloudname.*;
-import org.cloudname.testtools.Net;
-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
-
-/**
- * Integration tests for the ZkResolver class.
- * This test class contains tests dependent on timing or
- * tests depending on other modules, or both.
- */
-public class ZkResolverIntegrationTest {
- private ZooKeeper zk;
- private Cloudname cn;
- private Coordinate coordinateRunning;
- private Coordinate coordinateDraining;
- @Rule
- public TemporaryFolder temp = new TemporaryFolder();
- private ServiceHandle handleDraining;
-
-
- /**
- * Set up an embedded ZooKeeper instance backed by a temporary
- * directory. The setup procedure also allocates a port that is
- * free for the ZooKeeper server so that you should be able to run
- * multiple instances of this test.
- */
- @Before
- public void setup() throws Exception {
-
- // Speed up tests waiting for this event to happen.
- DynamicExpression.TIME_BETWEEN_NODE_SCANNING_MS = 200;
-
- File rootDir = temp.newFolder("zk-test");
- final int zkport = Net.getFreePort();
-
- // Set up and initialize the embedded ZooKeeper
- final EmbeddedZooKeeper ezk = new EmbeddedZooKeeper(rootDir, zkport);
- ezk.init();
-
- // Set up a zookeeper client that we can use for inspection
- final CountDownLatch connectedLatch = new CountDownLatch(1);
- zk = new ZooKeeper("localhost:" + zkport, 1000, new Watcher() {
- public void process(WatchedEvent event) {
- if (event.getState() == Event.KeeperState.SyncConnected) {
- connectedLatch.countDown();
- }
- }
- });
- connectedLatch.await();
- coordinateRunning = Coordinate.parse("1.service.user.cell");
- cn = new ZkCloudname.Builder().setConnectString("localhost:" + zkport).build().connect();
- cn.createCoordinate(coordinateRunning);
- ServiceHandle handleRunning = cn.claim(coordinateRunning);
- assertTrue(handleRunning.waitForCoordinateOkSeconds(30));
-
- handleRunning.putEndpoint(new Endpoint(
- coordinateRunning, "foo", "localhost", 1234, "http", "data"));
- handleRunning.putEndpoint(new Endpoint(
- coordinateRunning, "bar", "localhost", 1235, "http", null));
- ServiceStatus statusRunning = new ServiceStatus(ServiceState.RUNNING, "Running message");
- handleRunning.setStatus(statusRunning);
-
- coordinateDraining = Coordinate.parse("0.service.user.cell");
- cn.createCoordinate(coordinateDraining);
- handleDraining = cn.claim(coordinateDraining);
- assertTrue(handleDraining.waitForCoordinateOkSeconds(10));
- handleDraining.putEndpoint(new Endpoint(
- coordinateDraining, "foo", "localhost", 5555, "http", "data"));
- handleDraining.putEndpoint(new Endpoint(
- coordinateDraining, "bar", "localhost", 5556, "http", null));
-
- ServiceStatus statusDraining = new ServiceStatus(ServiceState.DRAINING, "Draining message");
- handleDraining.setStatus(statusDraining);
- }
-
- @After
- public void tearDown() throws Exception {
- zk.close();
- }
-
-
- public void undrain() throws CoordinateMissingException, CloudnameException {
- ServiceStatus statusDraining = new ServiceStatus(ServiceState.RUNNING, "alive");
- handleDraining.setStatus(statusDraining);
- }
-
- public void drain() throws CoordinateMissingException, CloudnameException {
- ServiceStatus statusDraining = new ServiceStatus(ServiceState.DRAINING, "dead");
- handleDraining.setStatus(statusDraining);
- }
-
- public void changeEndpointData() throws CoordinateMissingException, CloudnameException {
- handleDraining.putEndpoint(new Endpoint(
- coordinateDraining, "foo", "localhost", 5555, "http", "dataChanged"));
- }
-
- public void changeEndpointPort() throws CoordinateMissingException, CloudnameException {
- handleDraining.putEndpoint(new Endpoint(
- coordinateDraining, "foo", "localhost", 5551, "http", "dataChanged"));
- }
-
- @Test
- public void testStatus() throws Exception {
- ServiceStatus status = cn.getStatus(coordinateRunning);
- assertEquals(ServiceState.RUNNING, status.getState());
- assertEquals("Running message", status.getMessage());
- }
-
- @Test
- public void testBasicSyncResolving() throws Exception {
- List<Endpoint> endpoints = cn.getResolver().resolve("foo.1.service.user.cell");
- assertEquals(1, endpoints.size());
- assertEquals("foo", endpoints.get(0).getName());
- assertEquals("localhost", endpoints.get(0).getHost());
- assertEquals("1.service.user.cell", endpoints.get(0).getCoordinate().toString());
- assertEquals("data", endpoints.get(0).getEndpointData());
- assertEquals("http", endpoints.get(0).getProtocol());
- }
-
-
- @Test
- public void testAnyResolving() throws Exception {
- List<Endpoint> endpoints = cn.getResolver().resolve("foo.any.service.user.cell");
- assertEquals(1, endpoints.size());
- assertEquals("foo", endpoints.get(0).getName());
- assertEquals("localhost", endpoints.get(0).getHost());
- assertEquals("1.service.user.cell", endpoints.get(0).getCoordinate().toString());
- }
-
- @Test
- public void testAllResolving() throws Exception {
- List<Endpoint> endpoints = cn.getResolver().resolve("all.service.user.cell");
- assertEquals(2, endpoints.size());
- assertEquals("foo", endpoints.get(0).getName());
- assertEquals("bar", endpoints.get(1).getName());
- }
-
- /**
- * Tests that all registered endpoints are returned.
- */
- @Test
- public void testGetCoordinateDataAll() throws Exception {
- Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter();
- Set<Endpoint> endpoints = cn.getResolver().getEndpoints(filter);
- assertEquals(4, endpoints.size());
- }
-
- /**
- * Tests that all methods of the filters are called and some basic filtering are functional.
- */
- @Test
- public void testGetCoordinateDataFilterOptions() throws Exception {
- final StringBuilder filterCalls = new StringBuilder();
-
- Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter() {
- @Override
- public boolean includeCell(final String datacenter) {
- filterCalls.append(datacenter).append(":");
- return true;
- }
- @Override
- public boolean includeUser(final String user) {
- filterCalls.append(user).append(":");
- return true;
- }
- @Override
- public boolean includeService(final String service) {
- filterCalls.append(service).append(":");
- return true;
- }
- @Override
- public boolean includeEndpointname(final String endpointName) {
- return endpointName.equals("foo");
- }
- @Override
- public boolean includeServiceState(final ServiceState state) {
- return state == ServiceState.RUNNING;
- }
- };
- Set<Endpoint> endpoints = cn.getResolver().getEndpoints(filter);
- assertEquals(1, endpoints.size());
- Endpoint selectedEndpoint = endpoints.iterator().next();
-
- assertEquals("foo", selectedEndpoint.getName());
- assertEquals("cell:user:service:", filterCalls.toString());
- }
-
-
- /**
- * Test an unclaimed coordinate and a path that is not complete.
- * Number of endpoints should not increase when inputting bad data.
- * @throws Exception
- */
- @Test
- public void testGetCoordinateDataAllNoClaimedCoordinate() throws Exception {
- // Create unclaimned coordinate.
- Coordinate coordinateNoStatus = Coordinate.parse("4.service.user.cell");
- cn.createCoordinate(coordinateNoStatus);
-
- // Throw in a incomplete path.
- zk.create("/cn/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-
- Resolver resolver = cn.getResolver();
-
- Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter();
- Set<Endpoint> endpoints = resolver.getEndpoints(filter);
- assertEquals(4, endpoints.size());
- }
-
- @Test
- public void testBasicAsyncResolving() throws Exception {
- Resolver resolver = cn.getResolver();
-
- final List<Endpoint> endpointListNew = new ArrayList<Endpoint>();
- final List<Endpoint> endpointListRemoved = new ArrayList<Endpoint>();
- final List<Endpoint> endpointListModified = new ArrayList<Endpoint>();
-
- // This class is needed since the abstract resolver listener class can only access final variables.
- class LatchWrapper {
- public CountDownLatch latch;
- }
- final LatchWrapper latchWrapper = new LatchWrapper();
-
- latchWrapper.latch = new CountDownLatch(1);
-
- resolver.addResolverListener(
- "foo.all.service.user.cell", new Resolver.ResolverListener() {
-
- @Override
- public void endpointEvent(Event event, Endpoint endpoint) {
- switch (event) {
- case NEW_ENDPOINT:
- endpointListNew.add(endpoint);
- latchWrapper.latch.countDown();
- break;
- case REMOVED_ENDPOINT:
- endpointListRemoved.add(endpoint);
- latchWrapper.latch.countDown();
- break;
- case MODIFIED_ENDPOINT_DATA:
- endpointListModified.add(endpoint);
- latchWrapper.latch.countDown();
- break;
- }
- }
- });
- assertTrue(latchWrapper.latch.await(24000, TimeUnit.MILLISECONDS));
- assertEquals(1, endpointListNew.size());
- assertEquals("foo", endpointListNew.get(0).getName());
- assertEquals("1.service.user.cell", endpointListNew.get(0).getCoordinate().toString());
- endpointListNew.clear();
- latchWrapper.latch = new CountDownLatch(1);
-
- undrain();
-
-
- assertTrue(latchWrapper.latch.await(125000, TimeUnit.MILLISECONDS));
-
- assertEquals(1, endpointListNew.size());
-
- assertEquals("foo", endpointListNew.get(0).getName());
- assertEquals("0.service.user.cell", endpointListNew.get(0).getCoordinate().toString());
-
- latchWrapper.latch = new CountDownLatch(1);
- endpointListNew.clear();
-
- changeEndpointData();
-
- assertTrue(latchWrapper.latch.await(26000, TimeUnit.MILLISECONDS));
-
- assertEquals(1, endpointListModified.size());
-
- assertEquals("0.service.user.cell", endpointListModified.get(0).getCoordinate().toString());
- assertEquals("foo", endpointListModified.get(0).getName());
- assertEquals("dataChanged", endpointListModified.get(0).getEndpointData());
-
- endpointListModified.clear();
-
- latchWrapper.latch = new CountDownLatch(2);
-
- changeEndpointPort();
-
- assertTrue(latchWrapper.latch.await(27000, TimeUnit.MILLISECONDS));
-
- assertEquals(1, endpointListNew.size());
- assertEquals(1, endpointListRemoved.size());
-
- endpointListNew.clear();
- endpointListRemoved.clear();
-
-
-
- latchWrapper.latch = new CountDownLatch(1);
-
- drain();
-
- assertTrue(latchWrapper.latch.await(27000, TimeUnit.MILLISECONDS));
-
- assertEquals(1, endpointListRemoved.size());
-
- assertEquals("0.service.user.cell", endpointListRemoved.get(0).getCoordinate().toString());
- assertEquals("foo", endpointListRemoved.get(0).getName());
- }
-
- @Test
- public void testBasicAsyncResolvingAnyStrategy() throws Exception {
- Resolver resolver = cn.getResolver();
-
- final List<Endpoint> endpointListNew = new ArrayList<Endpoint>();
-
- // This class is needed since the abstract resolver listener class can only access
- // final variables.
- class LatchWrapper {
- public CountDownLatch latch;
- }
- final LatchWrapper latchWrapper = new LatchWrapper();
-
- latchWrapper.latch = new CountDownLatch(1);
-
- resolver.addResolverListener(
- "foo.any.service.user.cell", new Resolver.ResolverListener() {
-
- @Override
- public void endpointEvent(Event event, Endpoint endpoint) {
- switch (event) {
- case NEW_ENDPOINT:
- endpointListNew.add(endpoint);
- latchWrapper.latch.countDown();
- break;
- case REMOVED_ENDPOINT:
- latchWrapper.latch.countDown();
- break;
- }
- }
- });
- assertTrue(latchWrapper.latch.await(5000, TimeUnit.MILLISECONDS));
- assertEquals(1, endpointListNew.size());
- assertEquals("foo", endpointListNew.get(0).getName());
- assertEquals("1.service.user.cell", endpointListNew.get(0).getCoordinate().toString());
- endpointListNew.clear();
-
- latchWrapper.latch = new CountDownLatch(1);
-
- undrain();
-
- assertFalse(latchWrapper.latch.await(3000, TimeUnit.MILLISECONDS));
- }
-
- @Test
- public void testStopAsyncResolving() throws Exception {
- Resolver resolver = cn.getResolver();
-
- final List<Endpoint> endpointListNew = new ArrayList<Endpoint>();
-
- // This class is needed since the abstract resolver listener class can only access
- // final variables.
- class LatchWrapper {
- public CountDownLatch latch;
- }
- final LatchWrapper latchWrapper = new LatchWrapper();
-
- latchWrapper.latch = new CountDownLatch(1);
-
-
- Resolver.ResolverListener resolverListener = new Resolver.ResolverListener() {
- @Override
- public void endpointEvent(Event event, Endpoint endpoint) {
- switch (event) {
-
- case NEW_ENDPOINT:
- endpointListNew.add(endpoint);
- latchWrapper.latch.countDown();
- break;
- case REMOVED_ENDPOINT:
- latchWrapper.latch.countDown();
- break;
- }
- }
- };
- resolver.addResolverListener("foo.all.service.user.cell", resolverListener);
- assertTrue(latchWrapper.latch.await(5000, TimeUnit.MILLISECONDS));
- assertEquals(1, endpointListNew.size());
- assertEquals("foo", endpointListNew.get(0).getName());
- assertEquals("1.service.user.cell", endpointListNew.get(0).getCoordinate().toString());
- endpointListNew.clear();
-
- latchWrapper.latch = new CountDownLatch(1);
-
- resolver.removeResolverListener(resolverListener);
-
- undrain();
-
- assertFalse(latchWrapper.latch.await(100, TimeUnit.MILLISECONDS));
-
- try {
- resolver.removeResolverListener(resolverListener);
- } catch (IllegalArgumentException e) {
- // This is expected.
- return;
- }
- fail("Did not throw an exception on deleting a non existing listener.");
- }
-}
diff --git a/cn/src/main/java/org/cloudname/Cloudname.java b/cn/src/main/java/org/cloudname/Cloudname.java
deleted file mode 100644
index d1fbb729..00000000
--- a/cn/src/main/java/org/cloudname/Cloudname.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.cloudname;
-
-/**
- * The main interface for interacting with Cloudname.
- *
- * @author borud
- * @author dybdahl
- */
-public interface Cloudname {
- /**
- * Claim a coordinate returning a {@link ServiceHandle} through
- * which the service can interact with the system. This is an asynchronous operation, to check result
- * use the returned Servicehandle. E.g. for waiting up to ten seconds for a claim to happen:
- *
- * Cloudname cn = ...
- * Coordinate coordinate = ...
- * ServiceHandle serviceHandle = cn.claim(coordinate);
- * boolean claimSuccess = serviceHandle.waitForCoordinateOkSeconds(10);
- *
- * @param coordinate of the service we wish to claim.
- * @return a ServiceHandle that can wait for the claim to be successful and listen to the state of the claim.
- */
- ServiceHandle claim(Coordinate coordinate);
-
- /**
- * Get a resolver instance.
- */
- Resolver getResolver();
-
- /**
- * Create a coordinate in the persistent service store. Must
- * throw an exception if the coordinate has already been defined.
- *
- *
- * @param coordinate the coordinate we wish to create
- * @throws CoordinateExistsException if coordinate already exists.
- * @throws CloudnameException if problems with talking with storage.
- */
- void createCoordinate(Coordinate coordinate)
- throws CloudnameException, CoordinateExistsException;
-
- /**
- * Deletes a coordinate in the persistent service store. It will throw an exception if the coordinate is claimed.
- * @param coordinate the coordinate we wish to destroy.
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CloudnameException if problems talking with storage.
- * @throws CoordinateDeletionException if problems occurred during deletion.
- */
- void destroyCoordinate(Coordinate coordinate)
- throws CoordinateDeletionException, CoordinateMissingException, CloudnameException;
-
- /**
- * Get the ServiceStatus for a given Coordinate.
- *
- * @param coordinate the coordinate we want to get the status of
- * @return a ServiceStatus instance.
- * @throws CloudnameException if problems with talking with storage.
- */
- ServiceStatus getStatus(Coordinate coordinate)
- throws CloudnameException;
-
- /**
- * Updates the config for a coordinate. If the oldConfig is set (not null) it will require that the old config
- * matches otherwise it will throw an exception
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CloudnameException if problems including oldConfig does not match old config.
- */
- void setConfig(final Coordinate coordinate, final String newConfig, final String oldConfig)
- throws CoordinateMissingException, CloudnameException;
-
- /**
- * Get config for a coordinate.
- * @return the new config.
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CloudnameException
- */
- String getConfig(final Coordinate coordinate)
- throws CoordinateMissingException, CloudnameException;
-
- /**
- * Close down connection to storage.
- */
- void close();
-}
diff --git a/cn/src/main/java/org/cloudname/CloudnameException.java b/cn/src/main/java/org/cloudname/CloudnameException.java
deleted file mode 100644
index 66da94f7..00000000
--- a/cn/src/main/java/org/cloudname/CloudnameException.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.cloudname;
-
-/**
- * Exceptions for Cloudname caused by problems talking to storage.
- *
- * @author borud
- */
-public class CloudnameException extends Exception {
-
- public CloudnameException(Throwable t) {
- super(t);
- }
-
- public CloudnameException(String message) {
- super(message);
- }
-
- public CloudnameException(String message, Throwable t) {
- super(message, t);
- }
-}
diff --git a/cn/src/main/java/org/cloudname/CloudnameTestBootstrapper.java b/cn/src/main/java/org/cloudname/CloudnameTestBootstrapper.java
deleted file mode 100644
index 5b29aae6..00000000
--- a/cn/src/main/java/org/cloudname/CloudnameTestBootstrapper.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.cloudname;
-
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-
-import java.io.File;
-import java.util.concurrent.CountDownLatch;
-import java.util.logging.Logger;
-
-import org.apache.zookeeper.ZooKeeper;
-import org.cloudname.testtools.Net;
-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper;
-import org.cloudname.zk.ZkCloudname;
-
-
-/**
- * Helper class for bootstrapping cloudname for unit-tests. It also exposes the ZooKeeper instance.
- * @author @author dybdahl
- */
-public class CloudnameTestBootstrapper {
-
- private static final Logger LOGGER = Logger.getLogger(CloudnameTestBootstrapper.class.getName());
- private EmbeddedZooKeeper embeddedZooKeeper;
- private ZooKeeper zooKeeper;
- private Cloudname cloudname;
- private File rootDir;
-
- public CloudnameTestBootstrapper(File rootDir) {
- this.rootDir = rootDir;
- }
-
- public void init() throws Exception, CloudnameException {
- int zookeeperPort = Net.getFreePort();
-
- LOGGER.info("EmbeddedZooKeeper rootDir=" + rootDir.getCanonicalPath()
- + ", port=" + zookeeperPort
- );
-
- // Set up and initialize the embedded ZooKeeper
- embeddedZooKeeper = new EmbeddedZooKeeper(rootDir, zookeeperPort);
- embeddedZooKeeper.init();
-
- // Set up a zookeeper client that we can use for inspection
- final CountDownLatch connectedLatch = new CountDownLatch(1);
- zooKeeper = new ZooKeeper("localhost:" + zookeeperPort, 1000, new Watcher() {
- public void process(WatchedEvent event) {
- if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
- connectedLatch.countDown();
- }
- }
- });
- connectedLatch.await();
- cloudname = new ZkCloudname.Builder().setConnectString("localhost:" + zookeeperPort).build().connect();
- }
-
- public ZooKeeper getZooKeeper() {
- return zooKeeper;
- }
-
- public Cloudname getCloudname() {
- return cloudname;
- }
-}
diff --git a/cn/src/main/java/org/cloudname/ConfigListener.java b/cn/src/main/java/org/cloudname/ConfigListener.java
deleted file mode 100644
index 04f3c5d8..00000000
--- a/cn/src/main/java/org/cloudname/ConfigListener.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package org.cloudname;
-
-/**
- * This interface defines the callback interface used to notify of
- * config node changes.
- *
- * @author borud
- */
-
-public interface ConfigListener {
- public enum Event {
- CREATE,
- UPDATED,
- DELETED,
- }
-
- /**
- * This method is called whenever the application needs to be
- * notified of events related to configuration.
- *
- * @param event the type of event observed on the config node.
- * @param data the contents of the config node
- */
- public void onConfigEvent(Event event, String data);
-}
\ No newline at end of file
diff --git a/cn/src/main/java/org/cloudname/Coordinate.java b/cn/src/main/java/org/cloudname/Coordinate.java
deleted file mode 100644
index e35d8b8c..00000000
--- a/cn/src/main/java/org/cloudname/Coordinate.java
+++ /dev/null
@@ -1,184 +0,0 @@
-package org.cloudname;
-
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.io.IOException;
-
-/**
- * This class represents a service coordinate. A coordinate is given
- * by four pieces of data.
- *
- * <dl>
- * <dt> Cell
- * <dd> A cell is roughly equivalent to "data center". The strict definition
- * is that a cell represents a ZooKeeper installation. You can have
- * multiple cells in a physical datacenter, but it is not advisable to
- * have ZooKeeper installations span physical data centers.
- *
- * <dt> User
- * <dd> The user owning the service. May or may not have any relation to
- * the operating system user.
- *
- * <dt> Service
- * <dd> The name of the service.
- *
- * <dt> Instance
- * </dd> An integer [0, Integer.MAX_VALUE) indicating the instance number
- * of the service.
- *
- * The canonical form of a coordinate is {@code 0.service.user.dc}.
- *
- * This class is immutable.
- *
- * @author borud
- */
-public class Coordinate {
- private final String cell;
- private final String user;
- private final String service;
- private final int instance;
-
- // TODO(borud): allow for numbers in service, user and cell. Just
- // not the first character.
- public static final Pattern coordinatePattern
- = Pattern.compile("^(\\d+)\\." // instance
- + "([a-z][a-z0-9-_]*)\\." // service
- + "([a-z][a-z0-9-_]*)\\." // user
- + "([a-z][a-z0-9-_]*)\\z"); // cell
-
- /**
- * Create a new coordinate instance.
- *
- * @param instance the instance number
- * @param service the service name
- * @param user the user name
- * @param cell the cell name
- * @throws IllegalArgumentException if the coordinate is invalid.
- */
- @JsonCreator
- public Coordinate (@JsonProperty("instance") int instance,
- @JsonProperty("service") String service,
- @JsonProperty("user") String user,
- @JsonProperty("cell") String cell) {
- // Enables validation of coordinate.
- this(instance, service, user, cell, true);
- }
-
- /**
- * Internal version of constructor. Makes validation optional.
- */
- public Coordinate (int instance, String service, String user, String cell, boolean validate) {
- this.instance = instance;
- this.service = service;
- this.user = user;
- this.cell = cell;
-
- if (instance < 0) {
- throw new IllegalArgumentException("Invalid instance number: " + instance);
- }
-
- // If the coordinate was created by the parse() method the
- // coordinate has already been parsed using the
- // coordinatePattern so no validation is required. If the
- // coordinate was defined using the regular constructor we
- // need to validate the parts. And we do this by re-using the
- // coordinatePattern.
- if (validate) {
- if (! coordinatePattern.matcher(asString()).matches()) {
- throw new IllegalArgumentException("Invalid coordinate: '" + asString() + "'");
- }
- }
- }
-
- /**
- * Parse coordinate and create a {@code Coordinate} instance from
- * a {@code String}.
- *
- * @param s Coordinate we wish to parse as a string.
- * @return a Coordinate instance equivalent to {@code s}
- * @throws IllegalArgumentException if the coordinate string {@s}
- * is not a valid coordinate.
- */
- public static Coordinate parse(String s) {
- Matcher m = coordinatePattern.matcher(s);
- if (! m.matches()) {
- throw new IllegalArgumentException("Malformed coordinate: " + s);
- }
-
- int instance = Integer.parseInt(m.group(1));
- String service = m.group(2);
- String user = m.group(3);
- String cell = m.group(4);
-
- return new Coordinate(instance, service, user, cell, false);
- }
-
- public String getCell() {
- return cell;
- }
-
- public String getUser() {
- return user;
- }
-
- public String getService() {
- return service;
- }
-
- public int getInstance() {
- return instance;
- }
-
- public String asString() {
- return instance + "." + service + "." + user + "." + cell;
- }
-
- @Override
- public String toString() {
- return asString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (null == o) {
- return false;
- }
-
- if (this == o) {
- return true;
- }
-
- if (getClass() != o.getClass()) {
- return false;
- }
-
- Coordinate c = (Coordinate) o;
- return ((instance == c.instance)
- && service.equals(c.service)
- && user.equals(c.user)
- && cell.equals(c.cell));
- }
-
- @Override
- public int hashCode() {
- return asString().hashCode();
- }
-
- public String toJson() {
- try {
- return new ObjectMapper().writeValueAsString(this);
- } catch (IOException e) {
- return null;
- }
- }
-
- public static Coordinate fromJson(String json) throws IOException {
- return new ObjectMapper().readValue(json, Coordinate.class);
- }
-
-}
diff --git a/cn/src/main/java/org/cloudname/CoordinateDeletionException.java b/cn/src/main/java/org/cloudname/CoordinateDeletionException.java
deleted file mode 100644
index c1ac89c7..00000000
--- a/cn/src/main/java/org/cloudname/CoordinateDeletionException.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.cloudname;
-
-/**
- * Thrown when there are problems deleting a coordinate.
- * @auther dybdahl
- */
-public class CoordinateDeletionException extends CoordinateException {
- public CoordinateDeletionException(String reason) {
- super(reason);
- }
-}
diff --git a/cn/src/main/java/org/cloudname/CoordinateException.java b/cn/src/main/java/org/cloudname/CoordinateException.java
deleted file mode 100644
index fadb25b7..00000000
--- a/cn/src/main/java/org/cloudname/CoordinateException.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.cloudname;
-
-/**
- * Base class for exception related to a specific coordinate.
- * @auther dybdahl
- */
-public abstract class CoordinateException extends Exception {
-
- public CoordinateException(String reason) {
- super(reason);
- }
-}
diff --git a/cn/src/main/java/org/cloudname/CoordinateExistsException.java b/cn/src/main/java/org/cloudname/CoordinateExistsException.java
deleted file mode 100644
index 7ba067a0..00000000
--- a/cn/src/main/java/org/cloudname/CoordinateExistsException.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.cloudname;
-
-/**
- * It was assumed that the coordinate did not exist, but it did.
- * @auther dybdahl
- */
-public class CoordinateExistsException extends CoordinateException {
- public CoordinateExistsException(String reason) {
- super(reason);
- }
-}
diff --git a/cn/src/main/java/org/cloudname/CoordinateListener.java b/cn/src/main/java/org/cloudname/CoordinateListener.java
deleted file mode 100644
index 9a057ae7..00000000
--- a/cn/src/main/java/org/cloudname/CoordinateListener.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.cloudname;
-
-/**
- * Interface for listening to status on a claimed coordinate.
- * @author dybdahl
- */
-public interface CoordinateListener {
- /**
- * Events that can be triggered when monitoring a coordinate.
- */
- public enum Event {
-
- /**
- * Everything is fine.
- */
- COORDINATE_OK,
-
- /**
- * Connection lost to storage, no more events will occur.
- */
- NO_CONNECTION_TO_STORAGE,
-
- /**
- * Problems with parsing the data in storage for this coordinate.
- */
- COORDINATE_CORRUPTED,
-
- /**
- * The data in the storage and memory is out of sync.
- */
- COORDINATE_OUT_OF_SYNC,
-
- /**
- * No longer the owner of the coordinate.
- */
- NOT_OWNER,
- }
-
-
-
- /**
- * Implement this function to receive the events.
- * Return false if no more events are wanted, will stop eventually.
- * @param event the event that happened.
- * @param message some message associated with the event.
- */
- public void onCoordinateEvent(Event event, String message);
-}
diff --git a/cn/src/main/java/org/cloudname/CoordinateMissingException.java b/cn/src/main/java/org/cloudname/CoordinateMissingException.java
deleted file mode 100644
index 6fcdb56a..00000000
--- a/cn/src/main/java/org/cloudname/CoordinateMissingException.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.cloudname;
-
-/**
- * Exception related to a coordinate that is missing.
- * @auther dybdahl
- */
-public class CoordinateMissingException extends CoordinateException {
- public CoordinateMissingException(String reason) {
- super(reason);
- }
-}
diff --git a/cn/src/main/java/org/cloudname/Endpoint.java b/cn/src/main/java/org/cloudname/Endpoint.java
deleted file mode 100644
index b892cfaf..00000000
--- a/cn/src/main/java/org/cloudname/Endpoint.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package org.cloudname;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.io.IOException;
-
-/**
- * Representation of an endpoint. This class is used to describe a
- * wide range of endpoints, but it is, initially geared mainly towards
- * services for which we need to know a hostname, port and protocol.
- * As a stop-gap measure we provide an {@code endpointData} field
- * which can be used in a pinch to communicate extra information about
- * the endpoint.
- *
- * Instances of this class are immutable.
- *
- * TODO(borud): decide if coordinate and name should be part of this
- * class.
- *
- * @author borud
- */
-public class Endpoint {
- // This gets saved into ZooKeeper as well and is redundant info,
- // but it makes sense to have this information in the Endpoint
- // instances to make it possible for clients to get a list of
- // endpoints and be able to figure out what coordinates they come
- // from if they were gathered from multiple services.
- private final Coordinate coordinate;
- // Ditto for name.
- private final String name;
- private final String host;
- private final int port;
- private final String protocol;
- private final String endpointData;
-
- @JsonCreator
- public Endpoint(@JsonProperty("coordinate") Coordinate coordinate,
- @JsonProperty("name") String name,
- @JsonProperty("host") String host,
- @JsonProperty("port") int port,
- @JsonProperty("protocol") String protocol,
- @JsonProperty("endpointData") String endpointData)
- {
- this.coordinate = coordinate;
- this.name = name;
- this.host = host;
- this.port = port;
- this.protocol = protocol;
- this.endpointData = endpointData;
- }
-
- public Coordinate getCoordinate() {
- return coordinate;
- }
-
- public String getName() {
- return name;
- }
-
- public String getHost() {
- return host;
- }
-
- public int getPort() {
- return port;
- }
-
- public String getProtocol() {
- return protocol;
- }
-
- public String getEndpointData() {
- return endpointData;
- }
-
- @Override
- public boolean equals(Object endpoint) {
- return endpoint instanceof Endpoint && ((Endpoint) endpoint).toJson().equals(toJson());
- }
-
- public int hashCode() {
- return toJson().hashCode();
- }
-
- public static Endpoint fromJson(String json) throws IOException {
- return new ObjectMapper().readValue(json, Endpoint.class);
- }
-
- public String toJson() {
- try {
- return new ObjectMapper().writeValueAsString(this);
- } catch (IOException e) {
- return null;
- }
- }
-
- public String toString() {
- return toJson();
- }
-}
diff --git a/cn/src/main/java/org/cloudname/Resolver.java b/cn/src/main/java/org/cloudname/Resolver.java
deleted file mode 100644
index e6c08728..00000000
--- a/cn/src/main/java/org/cloudname/Resolver.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package org.cloudname;
-
-import java.util.List;
-import java.util.Set;
-
-/**
- * This interface defines how we resolve endpoints in Cloudname. The client has to keep a reference to this Resolver
- * object otherwise it will stop resolving.
- *
- * @author borud
- */
-public interface Resolver {
-
- /**
- * Resolve an expression to a list of endpoints. The order of the
- * endpoints may be subject to ranking criteria.
- *
- * @param expression The expression to resolve, e.g. for ZooKeeper implementation there are various formats like
- * endpoint.instance.service.user.cell (see ZkResolver for details).
- * @throws CloudnameException if problems talking with storage.
- */
- List<Endpoint> resolve(String expression) throws CloudnameException;
-
-
- /**
- * Implement this interface to get dynamic information about what endpoints that are available.
- * If you want to register more than 1000 listeners in the same resolver, you might consider overriding
- * equals() and hashCode(), but the default implementation should work in normal cases.
- */
- interface ResolverListener {
- enum Event {
- /**
- * New endpoint was added.
- */
- NEW_ENDPOINT,
- /**
- * Endpoint removed. This include when the coordinate goes to draining.
- */
- REMOVED_ENDPOINT,
- /**
- * Endpoint data has been modified.
- */
- MODIFIED_ENDPOINT_DATA,
- /**
- * Lost connection to storage. The list of endpoints will get stale. The system will reconnect
- * automatically.
- */
- LOST_CONNECTION,
- /**
- * Connection to storage is good, list of endpoints will be updated.
- */
- CONNECTION_OK
- }
-
- /**
- * An Event happened related to the expression, see enum Event above.
- * @param endpoint is only populated for the Event NEW_ENDPOINT and REMOVED_ENDPOINT.
- */
- void endpointEvent(Event event, final Endpoint endpoint);
- }
-
- /**
- * Registers a ResolverListener to get dynamic information about an expression. The expression is set in the
- * ResolverListener. You will only get updates as long as you keep a reference to Resolver.
- * If you don't have a reference, it is up to the garbage collector to decide how long you will receive callbacks.
- * One listener can only be registered once.
- *
- * @param expression The expression to resolve, e.g. for ZooKeeper implementation there are various formats like
- * endpoint.instance.service.user.cell (see ZkResolver for details). This should be static data, i.e.
- * the function might be called only once.
- */
- void addResolverListener(String expression, ResolverListener listener) throws CloudnameException;
-
- /**
- * Calling this function unregisters the listener, i.e. stopping future callbacks.
- * The listener must be registered. For identification of listener, see comment on ResolverListener.
- * The default is to use object id.
- */
- void removeResolverListener(ResolverListener listener);
-
- /**
- * This class is used as a parameter to {@link #getEndpoints(CoordinateDataFilter)}. Override methods to filter
- * the endpoints to be
- * returned.
- */
- class CoordinateDataFilter {
- /**
- * Override these methods to filter on cell, user, service, endpointName, and/or service state.
- */
-
- public boolean includeCell(final String cell) {
- return true;
- }
- public boolean includeUser(final String user) {
- return true;
- }
- public boolean includeService(final String service) {
- return true;
- }
- public boolean includeEndpointname(final String endpointName) {
- return true;
- }
- public boolean includeServiceState(final ServiceState state) {
- return true;
- }
- }
-
- /**
- * This method reads out all the nodes from the storage. IT CAN BE VERY EXPENSIVE AND SHOULD BE USED ONLY
- * WHEN NO OTHER METHODS ARE FEASIBLE. Do not call it frequently!
- * @param filter class for filtering out endpoints
- * @return list of endpoints.
- */
- Set<Endpoint> getEndpoints(CoordinateDataFilter filter) throws CloudnameException, InterruptedException;
-}
diff --git a/cn/src/main/java/org/cloudname/ResolverStrategy.java b/cn/src/main/java/org/cloudname/ResolverStrategy.java
deleted file mode 100644
index b28ebfb2..00000000
--- a/cn/src/main/java/org/cloudname/ResolverStrategy.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.cloudname;
-
-import java.util.List;
-
-/**
- * The ResolverStrategy is an interface for implementing a strategy when resolving endpoints.
- *
- * @auther dybdahl
- */
-
-public interface ResolverStrategy {
-
- /**
- * Given a list of endpoints, return only those endpoints that are desired for this strategy.
- */
- public List<Endpoint> filter(List<Endpoint> endpoints);
-
- /**
- * Returns the endpoints ordered according to strategy specific scheme.
- */
- public List<Endpoint> order(List<Endpoint> endpoints);
-
- /**
- * Returns the name of this strategy. This is the same name that is used in the resolver
- * (e.g. "all", "any" etc).
- * @return name of strategy.
- */
- public String getName();
-}
diff --git a/cn/src/main/java/org/cloudname/ServiceHandle.java b/cn/src/main/java/org/cloudname/ServiceHandle.java
deleted file mode 100644
index e0b9d81e..00000000
--- a/cn/src/main/java/org/cloudname/ServiceHandle.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package org.cloudname;
-
-import java.util.List;
-
-/**
- * The service handle -- the interface through which services
- * communicate their state to the outside world and where services can
- * register listeners to handle configuration updates.
- *
- * @author borud
- */
-public interface ServiceHandle {
-
- /**
- * This is a convenient function for waiting for the connection to storage to be ok. It is the same as
- * registering a CoordinateListener and waiting for event coordinate ok.
- */
- boolean waitForCoordinateOkSeconds(int seconds) throws InterruptedException;
-
- /**
- * Set the status of this service.
- *
- * @param status the new status.
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems
- * with ZooKeeper.
- */
- void setStatus(ServiceStatus status) throws CoordinateMissingException, CloudnameException;
-
- /**
- * Publish a named endpoint. It is legal to push an endpoint with updated data.
- *
- * @param endpoint the endpoint data.
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems
- * with ZooKeeper.
- */
- void putEndpoint(Endpoint endpoint) throws CoordinateMissingException, CloudnameException;
-
- /**
- * Same as putEndpoints, but takes a list.
- *
- * @param endpoints the endpoints data.
- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems
- * with ZooKeeper.
- * @throws CoordinateMissingException if coordinate does not exist.
- */
- void putEndpoints(List<Endpoint> endpoints) throws CoordinateMissingException, CloudnameException;
-
- /**
- * Remove a published endpoint.
- *
- * @param name the name of the endpoint we wish to remove.
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems
- * with ZooKeeper.
- */
- void removeEndpoint(String name) throws CoordinateMissingException, CloudnameException;
-
- /**
- * Same as removeEndpoint() but takes a list of names.
- *
- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems
- * with ZooKeeper.
- * @throws CoordinateMissingException if coordinate does not exist.
- * @throws CoordinateMissingException if coordinate does not exist.
- */
- void removeEndpoints(List<String> names) throws CoordinateMissingException, CloudnameException;
-
-
- /**
- * Register a ConfigListener which will be called whenever there
- * is a configuration change.
- *
- * There may have been configuration pushed to the backing storage
- * already by the time a ConfigListener is registered. In that
- * case the ConfigListener will see these configuration items as
- * being created.
- */
- // TODO(dybdahl): This logic lacks tests. Before used in any production code, tests have to be added.
- void registerConfigListener(ConfigListener listener);
-
- /**
- * After registering a new listener, a new event is triggered which include current state, even without change
- * of state.
- * Don't call the cloudname library, do any heavy lifting, or do any IO operation from this callback thread.
- * That might deadlock as there is no guarantee what kind of thread that runs the callback.
- *
- * @throws CloudnameException if problems talking with storage.
- */
- void registerCoordinateListener(CoordinateListener listener)
- throws CloudnameException;
-
- /**
- * Close the service handle and free up the coordinate so it can
- * be claimed by others. After close() has been called all
- * operations on this instance of the service handle will result
- * in an exception being thrown. All endpoints are deleted.
- * @throws CloudnameException if problems removing the claim.
- */
- void close()
- throws CloudnameException;
-
-}
-
diff --git a/cn/src/main/java/org/cloudname/ServiceState.java b/cn/src/main/java/org/cloudname/ServiceState.java
deleted file mode 100644
index 6af89561..00000000
--- a/cn/src/main/java/org/cloudname/ServiceState.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.cloudname;
-
-/**
- * The defined states of a service.
- *
- * @author borud
- */
-public enum ServiceState {
- // This means that no service has claimed the coordinate, or in
- // more practical terms: there is no ephemeral node called
- // "status" in the service root path in ZooKeeper.
- UNASSIGNED,
-
- // A running process has claimed the coordinate and is in the
- // process of starting up.
- STARTING,
-
- // A running process has claimed the coordinate and is running
- // normally.
- RUNNING,
-
- // A running process has claimed the coordinate and is running,
- // but it is in the process of shutting down and will not accept
- // new work.
- DRAINING,
-
- // An error condition has occurred.
- ERROR
-}
diff --git a/cn/src/main/java/org/cloudname/ServiceStatus.java b/cn/src/main/java/org/cloudname/ServiceStatus.java
deleted file mode 100644
index eba04e20..00000000
--- a/cn/src/main/java/org/cloudname/ServiceStatus.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package org.cloudname;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.io.IOException;
-
-/**
- * A representation of the basic runtime status of a service.
- *
- * Instances of ServiceStatus are immutable.
- *
- * @author borud
- */
-public class ServiceStatus {
- private final ServiceState state;
- private final String message;
-
- /**
- * @param state the state of the service
- * @param message a human readable message
- */
- @JsonCreator
- public ServiceStatus(@JsonProperty("state") ServiceState state,
- @JsonProperty("message") String message)
- {
- this.state = state;
- this.message = message;
- }
-
- public ServiceState getState() {
- return state;
- }
-
- public String getMessage() {
- return message;
- }
-
- public static ServiceStatus fromJson(String json) throws IOException {
- return new ObjectMapper().readValue(json, ServiceStatus.class);
- }
-
- public String toJson() {
- try {
- return new ObjectMapper().writeValueAsString(this);
- } catch (IOException e) {
- return null;
- }
- }
-}
\ No newline at end of file
diff --git a/cn/src/main/java/org/cloudname/StrategyAll.java b/cn/src/main/java/org/cloudname/StrategyAll.java
deleted file mode 100644
index 2bf6dcbb..00000000
--- a/cn/src/main/java/org/cloudname/StrategyAll.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.cloudname;
-
-import java.util.List;
-
-/**
- * A strategy that implements "all" and returns everything and does not change order.
- * @author : dybdahl
- */
-public class StrategyAll implements ResolverStrategy {
-
- /**
- * Returns all the endpoints.
- */
- @Override
- public List<Endpoint> filter(List<Endpoint> endpoints) {
- return endpoints;
- }
-
- /**
- * Doesn't change ordering of endpoints.
- */
- @Override
- public List<Endpoint> order(List<Endpoint> endpoints) {
- return endpoints;
- }
-
- /**
- * The name of the strategy is "all".
- */
- @Override
- public String getName() {
- return "all";
- }
-
-}
diff --git a/cn/src/main/java/org/cloudname/StrategyAny.java b/cn/src/main/java/org/cloudname/StrategyAny.java
deleted file mode 100644
index 76679a55..00000000
--- a/cn/src/main/java/org/cloudname/StrategyAny.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.cloudname;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.SortedSet;
-
-/**
- * A strategy that returns the first element of the sorted coordinates (by instance value) hashed with
- * the time of this object creation. This is useful for returning the same endpoint in most cases even
- * if an endpoint is removed or added.
- * @author : dybdahl
- */
-public class StrategyAny implements ResolverStrategy {
-
- // Some systems might not have nano seconds accuracy and we do not want zeros in the least significant
- // numbers.
- private int sortSeed = (int) System.nanoTime() / 1000;
-
- /**
- * Returns a list of the first endpoint if any, else returns the empty list.
- */
- @Override
- public List<Endpoint> filter(List<Endpoint> endpoints) {
- if (endpoints.size() > 0) {
- List<Endpoint> retVal = new ArrayList<Endpoint>();
- retVal.add(endpoints.get(0));
- return retVal;
- }
- // Empty list.
- return endpoints;
- }
-
- /**
- * We return a list that is sorted differently for different clients. In this way only a few
- * clients are touched when an endpoint is added/removed.
- */
- @Override
- public List<Endpoint> order(List<Endpoint> endpoints) {
- Collections.sort(endpoints, new Comparator<Endpoint>() {
- @Override
- public int compare(Endpoint endpointA, Endpoint endpointB) {
- int instanceA = endpointA.getCoordinate().getInstance() ^ sortSeed;
- int instanceB = endpointB.getCoordinate().getInstance() ^ sortSeed;
- return (instanceA > instanceB ? -1 : (instanceA == instanceB ? 0 : 1));
- }
- });
- return endpoints;
- }
-
- /**
- * The name of the strategy is "any"
- */
- @Override
- public String getName() {
- return "any";
- }
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ClaimedCoordinate.java b/cn/src/main/java/org/cloudname/zk/ClaimedCoordinate.java
deleted file mode 100644
index f4d8e133..00000000
--- a/cn/src/main/java/org/cloudname/zk/ClaimedCoordinate.java
+++ /dev/null
@@ -1,535 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.*;
-import org.apache.zookeeper.data.Stat;
-import org.cloudname.*;
-
-import java.io.IOException;
-
-import java.io.UnsupportedEncodingException;
-import java.util.*;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.logging.Logger;
-
-/**
- * This class keeps track of coordinate data and endpoints for a coordinate. It is notified about
- * the state of ZooKeeper connection by implementing the ZkObjectHandler.ConnectionStateChanged.
- * It implements the Watcher interface to track the specific path of the coordinate.
- * This is useful for being notified if something happens to the coordinate (if it
- * is overwritten etc).
- *
- * @author dybdahl
- */
-public class ClaimedCoordinate implements Watcher, ZkObjectHandler.ConnectionStateChanged {
-
- /**
- * True if we know that our state is in sync with zookeeper.
- */
- private final AtomicBoolean isSynchronizedWithZooKeeper = new AtomicBoolean(false);
-
- /**
- * The client of the class has to call start. This will flip this bit.
- */
- private final AtomicBoolean started = new AtomicBoolean(false);
-
- /**
- * The connection from client to ZooKeeper might go down. If it comes up again within some time
- * window the server might think an ephemeral node should be alive. The client lib might think
- * otherwise. If this flag is set, the class will eventually check version.
- */
- private final AtomicBoolean checkVersion = new AtomicBoolean(false);
-
- /**
- * We keep track of the last version so we know if we are in sync. We set a large value to make
- * sure we do not accidentally overwrite an existing not owned coordinate.
- */
- private int lastStatusVersion = Integer.MAX_VALUE;
-
- private final Object lastStatusVersionMonitor = new Object();
-
- private static final Logger LOG = Logger.getLogger(ClaimedCoordinate.class.getName());
-
- private final ZkObjectHandler.Client zkClient;
-
- /**
- * The claimed coordinate.
- */
- private final Coordinate coordinate;
-
- /**
- * Status path of the coordinate.
- */
- private final String path;
-
- /**
- * This is needed to make sure that the first message about state is sent while
- * other update messages are queued.
- */
- private final Object callbacksMonitor = new Object();
-
- /**
- * The endpoints and the status of the coordinate is stored here.
- */
- private final ZkCoordinateData zkCoordinateData = new ZkCoordinateData();
-
- /**
- * For running internal thread.
- */
- private final ScheduledExecutorService scheduler =
- Executors.newSingleThreadScheduledExecutor();
-
- /**
- * A list of the coordinate listeners that are registered for this coordinate.
- */
- private final List<CoordinateListener> coordinateListenerList =
- Collections.synchronizedList(new ArrayList<CoordinateListener>());
-
- /**
- * A list of tracked configs for this coordinate.
- */
- private final List<TrackedConfig> trackedConfigList =
- Collections.synchronizedList(new ArrayList<TrackedConfig>());
-
-
- /**
- * This class implements the logic for handling callbacks from ZooKeeper on claim.
- * In general we could just ignore errors since we have a time based retry mechanism. However,
- * we want to notify clients, and we need to update the consistencyState.
- */
- class ClaimCallback implements AsyncCallback.StringCallback {
-
- @Override
- public void processResult(
- int rawReturnCode, String notUsed, Object parent, String notUsed2) {
-
- KeeperException.Code returnCode = KeeperException.Code.get(rawReturnCode);
- ClaimedCoordinate claimedCoordinate = (ClaimedCoordinate) parent;
- LOG.fine("Claim callback with " + returnCode.name() + " " + claimedCoordinate.path
- + " synched: " + isSynchronizedWithZooKeeper.get() + " thread: " + this);
- switch (returnCode) {
- // The claim was successful. This means that the node was created. We need to
- // populate the status and endpoints.
- case OK:
-
- // We should be the first one to write to the new node, or fail.
- // This requires that the first version is 0, have not seen this documented
- // but it should be a fair assumption and is verified by unit tests.
- synchronized (lastStatusVersionMonitor) {
- lastStatusVersion = 0;
- }
-
- // We need to set this to synced or updateCoordinateData will complain.
- // updateCoordinateData will set it to out-of-sync in case of problems.
- isSynchronizedWithZooKeeper.set(true);
-
-
- try {
- registerWatcher();
- } catch (CloudnameException e) {
- LOG.fine("Failed register watcher after claim. Going to state out of sync: "
- + e.getMessage());
-
- isSynchronizedWithZooKeeper.set(false);
- return;
-
- } catch (InterruptedException e) {
-
- LOG.fine("Interrupted while setting up new watcher. Going to state out of sync.");
- isSynchronizedWithZooKeeper.set(false);
- return;
-
- }
- // No exceptions, let's celebrate with a log message.
- LOG.info("Claim processed ok, path: " + path);
- claimedCoordinate.sendEventToCoordinateListener(
- CoordinateListener.Event.COORDINATE_OK, "claimed");
- return;
-
- case NODEEXISTS:
- // Someone has already claimed the coordinate. It might have been us in a
- // different thread. If we already have claimed the coordinate then don't care.
- // Else notify the client. If everything is fine, this is not a true negative,
- // so ignore it. It might happen if two attempts to tryClaim the coordinate run
- // in parallel.
- if (isSynchronizedWithZooKeeper.get() && started.get()) {
- LOG.fine("Everything is fine, ignoring NODEEXISTS message, path: " + path);
- return;
- }
-
- LOG.info("Claimed fail, node already exists, will retry: " + path);
- claimedCoordinate.sendEventToCoordinateListener(
- CoordinateListener.Event.NOT_OWNER, "Node already exists.");
- LOG.info("isSynchronizedWithZooKeeper: " + isSynchronizedWithZooKeeper.get());
- checkVersion.set(true);
- return;
- case NONODE:
- LOG.info("Could not claim due to missing coordinate, path: " + path);
- claimedCoordinate.sendEventToCoordinateListener(
- CoordinateListener.Event.NOT_OWNER,
- "No node on claiming coordinate: " + returnCode.name());
- return;
-
- default:
- // Random problem, report the problem to the client.
- claimedCoordinate.sendEventToCoordinateListener(
- CoordinateListener.Event.NO_CONNECTION_TO_STORAGE,
- "Could not reclaim coordinate. Return code: " + returnCode.name());
- return;
- }
- }
- }
-
-
- private class ResolveProblems implements Runnable {
- @Override
- public void run() {
- if (isSynchronizedWithZooKeeper.get() || ! zkClient.isConnected() ||
- ! started.get()) {
-
- return;
- }
- if (checkVersion.getAndSet(false)) {
- try {
- synchronized (lastStatusVersionMonitor) {
- final Stat stat = zkClient.getZookeeper().exists(path, null);
- if (stat != null && zkClient.getZookeeper().getSessionId() ==
- stat.getEphemeralOwner()) {
- zkClient.getZookeeper().delete(path, lastStatusVersion);
- }
- }
- } catch (InterruptedException e) {
- LOG.info("Interrupted");
- checkVersion.set(true);
- } catch (KeeperException e) {
- LOG.info("exception "+ e.getMessage());
- checkVersion.set(true);
- }
-
- }
- LOG.info("We are out-of-sync, have a zookeeper connection, and are started, trying reclaim: "
- + path + this);
- tryClaim();
- }
- }
-
- /**
- * Constructor.
- * @param coordinate The coordinate that is claimed.
- * @param zkClient for getting access to ZooKeeper.
- */
- public ClaimedCoordinate(final Coordinate coordinate, final ZkObjectHandler.Client zkClient) {
- this.coordinate = coordinate;
- path = ZkCoordinatePath.getStatusPath(coordinate);
- this.zkClient = zkClient;
- }
-
- /**
- * Claims a coordinate. To know if it was successful or not you need to register a listener.
- * @return this.
- */
- public ClaimedCoordinate start() {
- zkClient.registerListener(this);
- started.set(true);
- final long periodicDelayMs = 2000;
- scheduler.scheduleWithFixedDelay(new ResolveProblems(), 1 /* initial delay ms */,
- periodicDelayMs, TimeUnit.MILLISECONDS);
- return this;
- }
-
- /**
- * Callbacks from zkClient
- */
- @Override
- public void connectionUp() {
- isSynchronizedWithZooKeeper.set(false);
- }
-
- /**
- * Callbacks from zkClient
- */
- @Override
- public void connectionDown() {
- List<CoordinateListener> coordinateListenerListCopy = new ArrayList<CoordinateListener>();
- synchronized (coordinateListenerList) {
- coordinateListenerListCopy.addAll(coordinateListenerList);
- }
- for (CoordinateListener coordinateListener : coordinateListenerListCopy) {
- coordinateListener.onCoordinateEvent(
- CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down");
- }
- isSynchronizedWithZooKeeper.set(false);
- }
-
- @Override
- public void shutDown() {
- scheduler.shutdown();
- }
-
- /**
- * Updates the ServiceStatus and persists it. Only allowed if we claimed the coordinate.
- * @param status The new value for serviceStatus.
- */
- public void updateStatus(final ServiceStatus status)
- throws CloudnameException, CoordinateMissingException {
- zkCoordinateData.setStatus(status);
- updateCoordinateData();
- }
-
- /**
- * Adds new endpoints and persist them. Requires that this instance owns the tryClaim to the
- * coordinate.
- * @param newEndpoints endpoints to be added.
- */
- public void putEndpoints(final List<Endpoint> newEndpoints)
- throws CloudnameException, CoordinateMissingException {
- zkCoordinateData.putEndpoints(newEndpoints);
- updateCoordinateData();
- }
-
- /**
- * Remove endpoints and persist it. Requires that this instance owns the tryClaim to the
- * coordinate.
- * @param names names of endpoints to be removed.
- */
- public void removeEndpoints(final List<String> names)
- throws CloudnameException, CoordinateMissingException {
- zkCoordinateData.removeEndpoints(names);
- updateCoordinateData();
- }
-
- /**
- * Release the tryClaim of the coordinate. It means that nobody owns the coordinate anymore.
- * Requires that that this instance owns the tryClaim to the coordinate.
- */
- public void releaseClaim() throws CloudnameException {
- scheduler.shutdown();
- zkClient.deregisterListener(this);
-
- while (true) {
- final TrackedConfig config;
- synchronized (trackedConfigList) {
- if (trackedConfigList.isEmpty()) {
- break;
- }
- config = trackedConfigList.remove(0);
- }
- config.stop();
- }
-
- sendEventToCoordinateListener(
- CoordinateListener.Event.NOT_OWNER, "Released claim of coordinate");
-
- synchronized (lastStatusVersionMonitor) {
- try {
- zkClient.getZookeeper().delete(path, lastStatusVersion);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
- }
-
-
- /**
- * Creates a string for debugging etc
- * @return serialized version of the instance data.
- */
- public synchronized String toString() {
- return zkCoordinateData.snapshot().toString();
- }
-
- /**
- * Registers a coordinatelistener that will receive events when there are changes to the status
- * node. Don't do any heavy lifting in the callback and don't call cloudname from the callback
- * as this might create a deadlock.
- * @param coordinateListener
- */
- public void registerCoordinateListener(final CoordinateListener coordinateListener) {
-
- String message = "New listener added, resending current state.";
- synchronized (callbacksMonitor) {
- coordinateListenerList.add(coordinateListener);
- if (isSynchronizedWithZooKeeper.get()) {
- coordinateListener.onCoordinateEvent(
- CoordinateListener.Event.COORDINATE_OK, message);
- }
- }
- }
-
-
- public void deregisterCoordinateListener(final CoordinateListener coordinateListener) {
- coordinateListenerList.remove(coordinateListener);
- }
-
- /**
- * Registers a configlistener that will receive events when there are changes to the config node.
- * Don't do any heavy lifting in the callback and don't call cloudname from the callback as
- * this might create a deadlock.
- * @param trackedConfig
- */
- public void registerTrackedConfig(final TrackedConfig trackedConfig) {
- trackedConfigList.add(trackedConfig);
- }
-
- /**
- * Handles event from ZooKeeper for this coordinate.
- * @param event
- */
- @Override public void process(WatchedEvent event) {
- LOG.info("Got an event from ZooKeeper " + event.toString());
- synchronized (lastStatusVersionMonitor) {
- switch (event.getType()) {
-
- case None:
- switch (event.getState()) {
- case SyncConnected:
- break;
- case Disconnected:
- case AuthFailed:
- case Expired:
- default:
- // If we lost connection, we don't attempt to register another watcher as
- // this might be blocking forever. Parent will try to reconnect (reclaim)
- // later.
- isSynchronizedWithZooKeeper.set(false);
- sendEventToCoordinateListener(
- CoordinateListener.Event.NO_CONNECTION_TO_STORAGE,
- event.toString());
-
- return;
- }
- return;
-
- case NodeDeleted:
- // If node is deleted, we have no node to place a new watcher so we stop watching.
- isSynchronizedWithZooKeeper.set(false);
- sendEventToCoordinateListener(CoordinateListener.Event.NOT_OWNER, event.toString());
- return;
-
- case NodeDataChanged:
- LOG.fine("Node data changed, check versions.");
- boolean verifiedSynchronized = false;
- try {
- final Stat stat = zkClient.getZookeeper().exists(path, this);
- if (stat == null) {
- LOG.info("Could not stat path, setting out of synch, will retry claim");
- } else {
- LOG.fine("Previous version is " + lastStatusVersion + " now is "
- + stat.getVersion());
- if (stat.getVersion() != lastStatusVersion) {
- LOG.fine("Version mismatch, sending out of sync.");
- } else {
- verifiedSynchronized = true;
- }
- }
- } catch (KeeperException e) {
- LOG.fine("Problems with zookeeper, sending consistencyState out of sync: "
- + e.getMessage());
- } catch (InterruptedException e) {
- LOG.fine("Got interrupted: " + e.getMessage());
- return;
- } finally {
- isSynchronizedWithZooKeeper.set(verifiedSynchronized);
- }
-
- if (verifiedSynchronized) {
- sendEventToCoordinateListener(
- CoordinateListener.Event.COORDINATE_OUT_OF_SYNC, event.toString());
- }
- return;
-
- case NodeChildrenChanged:
- case NodeCreated:
- // This should not happen..
- isSynchronizedWithZooKeeper.set(false);
- sendEventToCoordinateListener(
- CoordinateListener.Event.COORDINATE_OUT_OF_SYNC, event.toString());
- return;
- }
- }
- }
-
- private void tryClaim() {
- try {
- zkClient.getZookeeper().create(
- path, zkCoordinateData.snapshot().serialize().getBytes(Util.CHARSET_NAME),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new ClaimCallback(), this);
- } catch (IOException e) {
- LOG.info("Got IO exception on claim with new ZooKeeper instance " + e.getMessage());
- }
- }
-
-
- /**
- * Sends an event too all coordinate listeners. Note that the event is sent from this thread so
- * if the callback code does the wrong calls, deadlocks might occur.
- * @param event
- * @param message
- */
- private void sendEventToCoordinateListener(
- final CoordinateListener.Event event, final String message) {
- synchronized (callbacksMonitor) {
- LOG.fine("Event " + event.name() + " " + message);
- List<CoordinateListener> coordinateListenerListCopy =
- new ArrayList<CoordinateListener>();
- synchronized (coordinateListenerList) {
- coordinateListenerListCopy.addAll(coordinateListenerList);
- }
- for (CoordinateListener listener : coordinateListenerListCopy) {
- listener.onCoordinateEvent(event, message);
- }
- }
- }
-
- /**
- * Register a watcher for the coordinate.
- */
- private void registerWatcher() throws CloudnameException, InterruptedException {
- LOG.fine("Register watcher for ZooKeeper..");
- try {
- zkClient.getZookeeper().exists(path, this);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
-
- /**
- * Creates the serialized value of the object and stores this in ZooKeeper under the path.
- * It updates the lastStatusVersion. It does not set a watcher for the path.
- */
- private void updateCoordinateData() throws CoordinateMissingException, CloudnameException {
- if (! started.get()) {
- throw new IllegalStateException("Not started.");
- }
-
- if (! zkClient.isConnected()) {
- throw new CloudnameException("No proper connection with zookeeper.");
- }
-
- synchronized (lastStatusVersionMonitor) {
- try {
- Stat stat = zkClient.getZookeeper().setData(path,
- zkCoordinateData.snapshot().serialize().getBytes(Util.CHARSET_NAME),
- lastStatusVersion);
- LOG.fine("Updated coordinate, latest version is " + stat.getVersion());
- lastStatusVersion = stat.getVersion();
- } catch (KeeperException.NoNodeException e) {
- throw new CoordinateMissingException("Coordinate does not exist " + path);
- } catch (KeeperException e) {
- throw new CloudnameException("ZooKeeper errror in updateCoordinateData: "
- + e.getMessage(), e);
- } catch (UnsupportedEncodingException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } catch (IOException e) {
- throw new CloudnameException(e);
- }
- }
-
- }
-}
diff --git a/cn/src/main/java/org/cloudname/zk/DynamicExpression.java b/cn/src/main/java/org/cloudname/zk/DynamicExpression.java
deleted file mode 100644
index 3811e640..00000000
--- a/cn/src/main/java/org/cloudname/zk/DynamicExpression.java
+++ /dev/null
@@ -1,379 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.cloudname.CloudnameException;
-import org.cloudname.Endpoint;
-import org.cloudname.Resolver;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.Executors;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Class that is capable of tracking an expression. An expression can include many nodes.
- * The number of nodes is dynamic and can change over time.
- * For now, the implementation is rather simple. For single endpoints it does use feedback from
- * ZooKeeper watcher events. For keeping track of new nodes, it does a scan on regular intervals.
- * @author dybdahl
- */
-class DynamicExpression implements Watcher, TrackedCoordinate.ExpressionResolverNotify,
- ZkObjectHandler.ConnectionStateChanged {
-
- /**
- * Keeps track of what picture (what an expression has resolved to) is sent to the user so that
- * we know when to send new events.
- */
- private final Map<String, Endpoint> clientPicture = new HashMap<String, Endpoint>();
-
- /**
- * Where to notify changes.
- */
- private final Resolver.ResolverListener clientCallback;
-
- /**
- * This is the expression to dynamically resolved represented as ZkResolver.Parameters.
- */
- private final ZkResolver.Parameters parameters;
-
- /**
- * When ZooKeeper reports an error about an path, when to try to read it again.
- */
- private final long RETRY_INTERVAL_ZOOKEEPER_ERROR_MS = 30000; // 30 seconds
-
- /**
- * We wait a bit after a node has changed because in many cases there might be several updates,
- * e.g. an application registers several endpoints, each causing an update.
- */
- private final long REFRESH_NODE_AFTER_CHANGE_MS = 2000; // two seconds
-
- /**
- * Does a full scan with this interval. Non-final so unit test can run faster.
- */
- protected static long TIME_BETWEEN_NODE_SCANNING_MS = 1 * 60 * 1000; // one minute
-
- /**
- * A Map with all the coordinate we care about for now.
- */
- final private Map<String, TrackedCoordinate> coordinateByPath =
- new HashMap<String, TrackedCoordinate>();
-
- /**
- * We always add some random noise to when to do things so not all servers fire at the same time
- * against
- * ZooKeeper.
- */
- private final Random random = new Random();
-
- private static final Logger log = Logger.getLogger(DynamicExpression.class.getName());
-
- private boolean stopped = false;
-
- private final ZkResolver zkResolver;
-
- private final ZkObjectHandler.Client zkClient;
-
- private final ScheduledExecutorService scheduler =
- Executors.newSingleThreadScheduledExecutor();
-
- private final Object instanceLock = new Object();
-
- /**
- * Start getting notified about changes to expression.
- * @param expression Coordinate expression.
- * @param clientCallback called on changes and initially.
- */
- public DynamicExpression(
- final String expression,
- final Resolver.ResolverListener clientCallback,
- final ZkResolver zkResolver,
- final ZkObjectHandler.Client zkClient) {
- this.clientCallback = clientCallback;
- this.parameters = new ZkResolver.Parameters(expression);
- this.zkResolver = zkResolver;
- this.zkClient = zkClient;
- }
-
- public void start() {
- zkClient.registerListener(this);
- scheduler.scheduleWithFixedDelay(new NodeScanner(""), 1 /* initial delay ms */,
- TIME_BETWEEN_NODE_SCANNING_MS, TimeUnit.MILLISECONDS);
- }
-
- /**
- * Stop receiving callbacks about coordinate.
- */
- public void stop() {
- scheduler.shutdown();
-
- synchronized (instanceLock) {
- stopped = true;
- for (TrackedCoordinate trackedCoordinate : coordinateByPath.values()) {
- trackedCoordinate.stop();
- }
- coordinateByPath.clear();
- }
- }
-
- private void scheduleRefresh(String path, long delayMs) {
- try {
- scheduler.schedule(new NodeScanner(path), delayMs, TimeUnit.MILLISECONDS);
- } catch (RejectedExecutionException e) {
- if (scheduler.isShutdown()) {
- return;
- }
- log.log(Level.SEVERE, "Got exception while scheduling new refresh", e);
- }
- }
-
- @Override
- public void connectionUp() {
- }
-
- @Override
- public void connectionDown() {
- }
-
- @Override
- public void shutDown() {
- scheduler.shutdown();
- }
-
- /**
- * The method will try to resolve the expression and find new nodes.
- */
- private class NodeScanner implements Runnable {
- final String path;
-
- public NodeScanner(final String path) {
- this.path = path;
- }
-
- @Override
- public void run() {
- if (path.isEmpty()) {
- resolve();
- } else {
- refreshPathWithWatcher(path);
- }
- notifyClient();
- }
- }
-
- /**
- * Callback from zookeeper watcher.
- */
- @Override
- public void process(WatchedEvent watchedEvent) {
- synchronized (instanceLock) {
- if (stopped) {
- return;
- }
- }
- String path = watchedEvent.getPath();
- Event.KeeperState state = watchedEvent.getState();
- Event.EventType type = watchedEvent.getType();
-
- switch (state) {
- case Expired:
- case AuthFailed:
- case Disconnected:
- // Something bad happened to the path, try again later.
- scheduleRefresh(path, RETRY_INTERVAL_ZOOKEEPER_ERROR_MS);
- break;
- }
- switch (type) {
- case NodeChildrenChanged:
- case None:
- case NodeCreated:
- scheduleRefresh(path, REFRESH_NODE_AFTER_CHANGE_MS);
- break;
- case NodeDeleted:
- synchronized (instanceLock) {
- coordinateByPath.remove(path);
- notifyClient();
- return;
- }
- case NodeDataChanged:
- refreshPathWithWatcher(path);
- break;
- }
-
- }
-
- /**
- * Implements interface TrackedCoordinate.ExpressionResolverNotify
- */
- @Override
- public void nodeDead(final String path) {
- synchronized (instanceLock) {
- TrackedCoordinate trackedCoordinate = coordinateByPath.remove(path);
- if (trackedCoordinate == null) {
- return;
- }
- trackedCoordinate.stop();
- // Triggers a new scan, and potential client updates.
- scheduleRefresh("" /** scan for all nodes */, 50 /* ms*/);
- }
- }
-
- /**
- * Implements interface TrackedCoordinate.ExpressionResolverNotify
- */
- @Override
- public void stateChanged(final String path) {
- // Something happened to a path, schedule a refetch.
- scheduleRefresh(path, 50);
- }
-
- private void resolve() {
- final List<Endpoint> endpoints;
- try {
- endpoints = zkResolver.resolve(parameters.getExpression());
- } catch (CloudnameException e) {
- log.warning("Exception from cloudname: " + e.toString());
- return;
- }
-
- final Set<String> validEndpointsPaths = new HashSet<String>();
-
- for (Endpoint endpoint : endpoints) {
-
- final String statusPath = ZkCoordinatePath.getStatusPath(endpoint.getCoordinate());
- validEndpointsPaths.add(statusPath);
-
- final TrackedCoordinate trackedCoordinate;
-
- synchronized (instanceLock) {
-
- // If already discovered, do nothing.
- if (coordinateByPath.containsKey(statusPath)) {
- continue;
- }
- trackedCoordinate = new TrackedCoordinate(this, statusPath, zkClient);
- coordinateByPath.put(statusPath, trackedCoordinate);
- }
- // Tracked coordinate has to be in coordinateByPath before start is called, or events
- // gets lost.
- trackedCoordinate.start();
- try {
- trackedCoordinate.waitForFirstData();
- } catch (InterruptedException e) {
- log.log(Level.SEVERE, "Got interrupt while waiting for data.", e);
- return;
- }
- }
-
- // Remove tracked coordinates that does not resolve.
- synchronized (instanceLock) {
- for (Iterator<Map.Entry<String, TrackedCoordinate> > it =
- coordinateByPath.entrySet().iterator();
- it.hasNext(); /* nop */) {
- Map.Entry<String, TrackedCoordinate> entry = it.next();
-
- if (! validEndpointsPaths.contains(entry.getKey())) {
- log.info("Killing endpoint " + entry.getKey() + ": No longer resolved.");
- entry.getValue().stop();
- it.remove();
- }
- }
- }
- }
-
- private String getEndpointKey(final Endpoint endpoint) {
- return endpoint.getCoordinate().asString() + "@" + endpoint.getName();
- }
-
-
- private List<Endpoint> getNewEndpoints() {
- final List<Endpoint> newEndpoints = new ArrayList<Endpoint>();
- for (TrackedCoordinate trackedCoordinate : coordinateByPath.values()) {
- if (trackedCoordinate.getCoordinatedata() != null) {
- ZkResolver.addEndpoints(
- trackedCoordinate.getCoordinatedata(),
- newEndpoints, parameters.getEndpointName());
- }
- }
- return newEndpoints;
- }
-
- private void notifyClient() {
- synchronized (instanceLock) {
- if (stopped) {
- return;
- }
- }
- // First generate a fresh list of endpoints.
- final List<Endpoint> newEndpoints = getNewEndpoints();
-
- synchronized (instanceLock) {
- final Map<String, Endpoint> newEndpointsByName = new HashMap<String, Endpoint>();
- for (final Endpoint endpoint : newEndpoints) {
- newEndpointsByName.put(getEndpointKey(endpoint), endpoint);
- }
- final Iterator<Map.Entry<String, Endpoint>> it = clientPicture.entrySet().iterator();
- while (it.hasNext()) {
-
- final Map.Entry<String, Endpoint> endpointEntry = it.next();
-
- final String key = endpointEntry.getKey();
- if (! newEndpointsByName.containsKey(key)) {
- it.remove();
- clientCallback.endpointEvent(
- Resolver.ResolverListener.Event.REMOVED_ENDPOINT,
- endpointEntry.getValue());
- }
- }
- for (final Endpoint endpoint : newEndpoints) {
- final String key = getEndpointKey(endpoint);
-
- if (! clientPicture.containsKey(key)) {
- clientCallback.endpointEvent(
- Resolver.ResolverListener.Event.NEW_ENDPOINT, endpoint);
- clientPicture.put(key, endpoint);
- continue;
- }
- final Endpoint clientEndpoint = clientPicture.get(key);
- if (endpoint.equals(clientEndpoint)) { continue; }
- if (endpoint.getHost().equals(clientEndpoint.getHost()) &&
- endpoint.getName().equals(clientEndpoint.getName()) &&
- endpoint.getPort() == clientEndpoint.getPort() &&
- endpoint.getProtocol().equals(clientEndpoint.getProtocol())) {
- clientCallback.endpointEvent(
- Resolver.ResolverListener.Event.MODIFIED_ENDPOINT_DATA, endpoint);
- clientPicture.put(key, endpoint);
- continue;
- }
- clientCallback.endpointEvent(
- Resolver.ResolverListener.Event.REMOVED_ENDPOINT,
- clientPicture.get(key));
- clientCallback.endpointEvent(
- Resolver.ResolverListener.Event.NEW_ENDPOINT, endpoint);
- clientPicture.put(key, endpoint);
- }
- }
- }
-
- private void refreshPathWithWatcher(String path) {
- synchronized (instanceLock) {
- TrackedCoordinate trackedCoordinate = coordinateByPath.get(path);
- if (trackedCoordinate == null) {
- // Endpoint has been removed while waiting for refresh.
- return;
- }
- trackedCoordinate.refreshAsync();
- }
- }
-
-}
\ No newline at end of file
diff --git a/cn/src/main/java/org/cloudname/zk/TrackedConfig.java b/cn/src/main/java/org/cloudname/zk/TrackedConfig.java
deleted file mode 100644
index aacd1908..00000000
--- a/cn/src/main/java/org/cloudname/zk/TrackedConfig.java
+++ /dev/null
@@ -1,220 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.data.Stat;
-import org.cloudname.CloudnameException;
-import org.cloudname.ConfigListener;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.logging.Logger;
-
-
-/**
- * This class keeps track of config for a coordinate.
- *
- * @author dybdahl
- */
-public class TrackedConfig implements Watcher, ZkObjectHandler.ConnectionStateChanged {
-
- private String configData = null;
- private final Object configDataMonitor = new Object();
- private final ConfigListener configListener;
-
- private static final Logger log = Logger.getLogger(TrackedConfig.class.getName());
-
- private final String path;
-
- private final AtomicBoolean isSynchronizedWithZookeeper = new AtomicBoolean(false);
-
- private final ZkObjectHandler.Client zkClient;
- private final ScheduledExecutorService scheduler =
- Executors.newSingleThreadScheduledExecutor();
- /**
- * Constructor, the ZooKeeper instances is retrieved from ZkObjectHandler.Client,
- * so we won't get it until the client reports we have a Zk Instance in the handler.
- * @param path is the path of the configuration of the coordinate.
- */
- public TrackedConfig(
- String path, ConfigListener configListener, ZkObjectHandler.Client zkClient) {
- this.path = path;
- this.configListener = configListener;
- this.zkClient = zkClient;
- }
-
-
- @Override
- public void connectionUp() {
- }
-
- @Override
- public void connectionDown() {
- isSynchronizedWithZookeeper.set(false);
- }
-
- @Override
- public void shutDown() {
- scheduler.shutdown();
- }
-
- /**
- * Starts tracking the config.
- */
- public void start() {
- zkClient.registerListener(this);
- final long periodicDelayMs = 2000;
- scheduler.scheduleWithFixedDelay(new ReloadConfigOnErrors(), 1 /* initial delay ms */,
- periodicDelayMs, TimeUnit.MILLISECONDS);
- }
-
- /**
- * Stops the tracker.
- */
- public void stop() {
- scheduler.shutdown();
- zkClient.deregisterListener(this);
- }
-
- /**
- * If connection to zookeeper is away, we need to reload because messages might have been
- * lost. This class has a method for checking this.
- */
- private class ReloadConfigOnErrors implements Runnable {
- @Override
- public void run() {
-
- if (isSynchronizedWithZookeeper.get())
- return;
-
- try {
- if (refreshConfigData()) {
- configListener.onConfigEvent(ConfigListener.Event.UPDATED, getConfigData());
- }
- } catch (CloudnameException e) {
- // No worries, we try again later
- }
- }
- }
-
- /**
- * Returns current config.
- * @return config
- */
- public String getConfigData() {
- synchronized (configDataMonitor) {
- return configData;
- }
- }
-
- /**
- * Creates a string for debugging etc
- * @return serialized version of the instance data.
- */
- public String toString() {
- return "Config: " + getConfigData();
- }
-
-
- /**
- * Handles event from ZooKeeper for this coordinate.
- * @param event Event to handle
- */
- @Override public void process(WatchedEvent event) {
- log.severe("Got an event from ZooKeeper " + event.toString() + " path: " + path);
-
- switch (event.getType()) {
- case None:
- switch (event.getState()) {
- case SyncConnected:
- break;
- case Disconnected:
- case AuthFailed:
- case Expired:
- default:
- isSynchronizedWithZookeeper.set(false);
- // If we lost connection, we don't attempt to register another watcher as
- // this might be blocking forever. Parent might try to reconnect.
- return;
- }
- break;
- case NodeDeleted:
- synchronized (configDataMonitor) {
- isSynchronizedWithZookeeper.set(false);
- configData = null;
- }
- configListener.onConfigEvent(ConfigListener.Event.DELETED, "");
- return;
- case NodeDataChanged:
- isSynchronizedWithZookeeper.set(false);
- return;
- case NodeChildrenChanged:
- case NodeCreated:
- break;
- }
- // We are only interested in registering a watcher in a few cases. E.g. if the event is lost
- // connection, registerWatcher does not make sense as it is blocking. In NodeDataChanged
- // above, a watcher is registerred in refreshConfigData().
- try {
- registerWatcher();
- } catch (CloudnameException e) {
- log.info("Got cloudname exception: " + e.getMessage());
- return;
- } catch (InterruptedException e) {
- log.info("Got interrupted exception: " + e.getMessage());
- return;
- }
- }
-
-
- /**
- * Loads the config from ZooKeeper. In case of failure, we keep the old data.
- *
- * @return Returns true if data has changed.
- */
- private boolean refreshConfigData() throws CloudnameException {
- if (! zkClient.isConnected()) {
- throw new CloudnameException("No connection to storage.");
- }
- synchronized (configDataMonitor) {
-
- String oldConfig = configData;
- Stat stat = new Stat();
- try {
- byte[] data;
-
- data = zkClient.getZookeeper().getData(path, this, stat);
- if (data == null) {
- configData = "";
- } else {
- configData = new String(data, Util.CHARSET_NAME);
- }
- isSynchronizedWithZookeeper.set(true);
- return oldConfig == null || ! oldConfig.equals(configData);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- } catch (UnsupportedEncodingException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } catch (IOException e) {
- throw new CloudnameException(e);
- }
- }
- }
-
- private void registerWatcher() throws CloudnameException, InterruptedException {
- try {
- zkClient.getZookeeper().exists(path, this);
-
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
-
-}
\ No newline at end of file
diff --git a/cn/src/main/java/org/cloudname/zk/TrackedCoordinate.java b/cn/src/main/java/org/cloudname/zk/TrackedCoordinate.java
deleted file mode 100644
index 37b314c0..00000000
--- a/cn/src/main/java/org/cloudname/zk/TrackedCoordinate.java
+++ /dev/null
@@ -1,220 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.*;
-import org.cloudname.*;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * This class keeps track of serviceStatus and endpoints for a coordinate.
- *
- * @author dybdahl
- */
-public class TrackedCoordinate implements Watcher, ZkObjectHandler.ConnectionStateChanged {
-
-
- /**
- * The client can implement this to get notified on changes.
- */
- public interface ExpressionResolverNotify {
- /**
- * This is called when the state has changed, it might have become unavailable.
- * @param statusPath path of the coordinate in zookeeper.
- */
- void stateChanged(final String statusPath);
-
- /**
- * This is called when node is deleted, or it can not be read.
- * @param statusPath path of the coordinate in zookeeper.
- */
- void nodeDead(final String statusPath);
- }
-
- private ZkCoordinateData.Snapshot coordinateData = null;
- private final Object coordinateDataMonitor = new Object();
-
- private static final Logger LOG = Logger.getLogger(TrackedCoordinate.class.getName());
- private final String path;
- private final ExpressionResolverNotify client;
- private final AtomicBoolean isSynchronizedWithZookeeper = new AtomicBoolean(false);
- private final ZkObjectHandler.Client zkClient;
-
- private final ScheduledExecutorService scheduler =
- Executors.newSingleThreadScheduledExecutor();
-
- private final CountDownLatch firstRound = new CountDownLatch(1);
- /**
- * Constructor, the ZooKeeper instances is retrieved from implementing the ZkUserInterface so
- * the object is not ready to be used before the ZooKeeper instance is received.
- * @param path is the path of the status of the coordinate.
- */
- public TrackedCoordinate(
- final ExpressionResolverNotify client, final String path,
- final ZkObjectHandler.Client zkClient) {
- LOG.finest("Tracking coordinate with path " + path);
- this.path = path;
- this.client = client;
- this.zkClient = zkClient;
- }
-
- // Implementation of ZkObjectHandler.ConnectionStateChanged.
- @Override
- public void connectionUp() {
- }
-
- // Implementation of ZkObjectHandler.ConnectionStateChanged.
- @Override
- public void connectionDown() {
- isSynchronizedWithZookeeper.set(false);
- }
-
- @Override
- public void shutDown() {
- scheduler.shutdown();
- }
-
- /**
- * Signalize that the class should reload its data.
- */
- public void refreshAsync() {
- isSynchronizedWithZookeeper.set(false);
- }
-
- public void start() {
- zkClient.registerListener(this);
- final long periodicDelayMs = 2000;
- scheduler.scheduleWithFixedDelay(new ReloadCoordinateData(), 1 /* initial delay ms */,
- periodicDelayMs, TimeUnit.MILLISECONDS);
- }
-
- public void stop() {
- scheduler.shutdown();
- zkClient.deregisterListener(this);
- }
-
- public void waitForFirstData() throws InterruptedException {
- firstRound.await();
- }
-
-
-
- /**
- * This class handles reloading new data from zookeeper if we are out of synch.
- */
- class ReloadCoordinateData implements Runnable {
- @Override
- public void run() {
- if (! isSynchronizedWithZookeeper.getAndSet(true)) { return; }
- try {
- refreshCoordinateData();
- } catch (CloudnameException e) {
- LOG.log(Level.INFO, "exception on reloading coordinate data.", e);
- isSynchronizedWithZookeeper.set(false);
- }
- firstRound.countDown();
- }
- }
-
-
- public ZkCoordinateData.Snapshot getCoordinatedata() {
- synchronized (coordinateDataMonitor) {
- return coordinateData;
- }
- }
-
-
- /**
- * Creates a string for debugging etc
- * @return serialized version of the instance data.
- */
- public String toString() {
- synchronized (coordinateDataMonitor) {
- return coordinateData.toString();
- }
- }
-
-
- /**
- * Handles event from ZooKeeper for this coordinate.
- * @param event Event to handle
- */
- @Override public void process(WatchedEvent event) {
- LOG.fine("Got an event from ZooKeeper " + event.toString() + " path: " + path);
-
- switch (event.getType()) {
- case None:
- switch (event.getState()) {
- case SyncConnected:
- break;
- case Disconnected:
- case AuthFailed:
- case Expired:
- default:
- // If we lost connection, we don't attempt to register another watcher as
- // this might be blocking forever. Parent might try to reconnect.
- return;
- }
- break;
- case NodeDeleted:
- synchronized (coordinateDataMonitor) {
- coordinateData = new ZkCoordinateData().snapshot();
- }
- client.nodeDead(path);
- return;
- case NodeDataChanged:
- isSynchronizedWithZookeeper.set(false);
- return;
- case NodeChildrenChanged:
- case NodeCreated:
- break;
- }
- try {
- registerWatcher();
- } catch (CloudnameException e) {
- LOG.log(Level.INFO, "Got cloudname exception.", e);
- } catch (InterruptedException e) {
- LOG.log(Level.INFO, "Got interrupted exception.", e);
- }
- }
-
-
- /**
- * Loads the coordinate from ZooKeeper. In case of failure, we keep the old data.
- * Notifies the client if state changes.
- */
- private void refreshCoordinateData() throws CloudnameException {
-
- if (! zkClient.isConnected()) {
- throw new CloudnameException("No connection to storage.");
- }
- synchronized (coordinateDataMonitor) {
- String oldDataSerialized = (null == coordinateData) ? "" : coordinateData.serialize();
- try {
- coordinateData = ZkCoordinateData.loadCoordinateData(
- path, zkClient.getZookeeper(), this).snapshot();
- } catch (CloudnameException e) {
- client.nodeDead(path);
- LOG.log(Level.FINER, "Exception while reading path " + path, e);
- return;
- }
- isSynchronizedWithZookeeper.set(true);
- if (! oldDataSerialized.equals(coordinateData.toString())) {
- client.stateChanged(path);
- }
- }
- }
-
- private void registerWatcher() throws CloudnameException, InterruptedException {
- try {
- zkClient.getZookeeper().exists(path, this);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
-}
\ No newline at end of file
diff --git a/cn/src/main/java/org/cloudname/zk/Util.java b/cn/src/main/java/org/cloudname/zk/Util.java
deleted file mode 100644
index 6bcd21e0..00000000
--- a/cn/src/main/java/org/cloudname/zk/Util.java
+++ /dev/null
@@ -1,177 +0,0 @@
-package org.cloudname.zk;
-
-import org.cloudname.CloudnameException;
-
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.data.ACL;
-import org.apache.zookeeper.KeeperException;
-import org.cloudname.CoordinateMissingException;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Various ZooKeeper utilities.
- *
- * @author borud
- */
-public final class Util {
- // Constants
- public static final String CHARSET_NAME = "UTF-8";
-
- /**
- * Create a path in ZooKeeper. We just start at the top and work
- * our way down. Nodes that exist will throw an exception but we
- * will just ignore those. The result should be a path consisting
- * of ZooKeeper nodes with the names specified by the path and
- * with their data element set to null.
- * @throws CloudnameException if problems talking with ZooKeeper.
- */
- public static void mkdir(final ZooKeeper zk, String path, final List<ACL> acl)
- throws CloudnameException, InterruptedException {
- if (path.startsWith("/")) {
- path = path.substring(1);
- }
-
- String[] parts = path.split("/");
-
- String createPath = "";
- for (String p : parts) {
- // Sonar will complain about this. Usually it would be
- // right but in this case it isn't.
- createPath += "/" + p;
- try {
- zk.create(createPath, null, acl, CreateMode.PERSISTENT);
- } catch (KeeperException.NodeExistsException e) {
- // This is okay. Ignore.
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
- }
-
- /**
- * Lists sub nodes of a path in a ZooKeeper instance.
- * @param path starts from this path
- * @param nodeList put sub-nodes in this list
- */
- public static void listRecursively(
- final ZooKeeper zk, final String path, final List<String> nodeList)
- throws CloudnameException, InterruptedException {
-
- List<String> children = null;
- try {
- children = zk.getChildren(path, false);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- if (children.size() == 0) {
- nodeList.add(path);
- return;
- }
- for (String childPath : children) {
- listRecursively(zk, path + "/" +childPath, nodeList);
- }
- }
-
- /**
- * Figures out if there are sub-nodes under the path in a ZooKeeper instance.
- * @return true if the node exists and has children.
- * @throws CoordinateMissingException if the path does not exist in ZooKeeper.
- */
- public static boolean hasChildren(final ZooKeeper zk, final String path)
- throws CloudnameException, CoordinateMissingException, InterruptedException {
- if (! exist(zk, path)) {
- throw new CoordinateMissingException("Could not get children due to non-existing path "
- + path);
- }
- List<String> children = null;
- try {
- children = zk.getChildren(path, false);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- return ((children != null) && (children.size() > 0));
- }
-
- /**
- * Figures out if a path exists in a ZooKeeper instance.
- * @throws CloudnameException if there are problems taking to the ZooKeeper instance.
- * @return true if the path exists.
- */
- public static boolean exist(final ZooKeeper zk, final String path)
- throws CloudnameException, InterruptedException {
- try {
- return zk.exists(path, false) != null;
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
-
- /**
- * Returns the version of the path.
- * @param zk
- * @param path
- * @return version number
- */
- public static int getVersionForDeletion(final ZooKeeper zk, final String path)
- throws CloudnameException, InterruptedException {
-
- try {
- int version = zk.exists(path, false).getVersion();
- if (version < 0) {
- throw new CloudnameException(
- new RuntimeException("Got negative version for path " + path));
- }
- return version;
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- }
-
- /**
- * Deletes nodes from a path from the right to the left.
- * @param zk
- * @param path to be deleted
- * @param keepMinLevels is the minimum number of levels (depths) to keep in the path.
- * @return the number of deleted levels.
- */
- public static int deletePathKeepRootLevels(
- final ZooKeeper zk, String path, int keepMinLevels)
- throws CloudnameException, CoordinateMissingException, InterruptedException {
- if (path.startsWith("/")) {
- path = path.substring(1);
- }
-
- String[] parts = path.split("/");
-
- // We are happy if only the first two deletions went through. The other deletions are just
- // cleaning up if there are no more coordinates on the same rootPath.
- int deletedNodes = 0;
- List<String> paths = new ArrayList<String>();
- String incrementalPath = "";
- for (String p : parts) {
- incrementalPath += "/" + p;
- paths.add(incrementalPath);
- }
-
- for (int counter = paths.size() - 1; counter >= keepMinLevels; counter--) {
- String deletePath = paths.get(counter);
- int version = getVersionForDeletion(zk, deletePath);
- if (hasChildren(zk, deletePath)) {
- return deletedNodes;
- }
- try {
- zk.delete(deletePath, version);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- deletedNodes++;
- }
- return deletedNodes;
- }
-
- // Should not be instantiated.
- private Util() {}
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ZkCloudname.java b/cn/src/main/java/org/cloudname/zk/ZkCloudname.java
deleted file mode 100644
index c14e5e7b..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkCloudname.java
+++ /dev/null
@@ -1,419 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.data.Stat;
-import org.cloudname.*;
-
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.KeeperException;
-
-import java.io.UnsupportedEncodingException;
-import java.util.List;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import java.util.concurrent.CountDownLatch;
-
-import java.io.IOException;
-
-
-/**
- * An implementation of Cloudname using ZooKeeper.
- *
- * This implementation assumes that the path prefix defined by
- * CN_PATH_PREFIX is only used by Cloudname. The structure and
- * semantics of things under this prefix are defined by this library
- * and will be subject to change.
- *
- *
- * @author borud
- * @author dybdahl
- * @author storsveen
- */
-public final class ZkCloudname implements Cloudname, Watcher, Runnable {
-
- private static final int SESSION_TIMEOUT = 5000;
-
- private static final Logger log = Logger.getLogger(ZkCloudname.class.getName());
-
- private ZkObjectHandler zkObjectHandler = null;
-
- private final String connectString;
-
- // Latches that count down when ZooKeeper is connected
- private final CountDownLatch connectedSignal = new CountDownLatch(1);
-
- private ZkResolver resolver = null;
-
- private int connectingCounter = 0;
-
- private final ScheduledExecutorService scheduler =
- Executors.newSingleThreadScheduledExecutor();
-
- private ZkCloudname(final Builder builder) {
- connectString = builder.getConnectString();
-
- }
-
- /**
- * Checks state of zookeeper connection and try to keep it running.
- */
- @Override
- public void run() {
- final ZooKeeper.States state = zkObjectHandler.getClient().getZookeeper().getState();
-
- if (state == ZooKeeper.States.CONNECTED) {
- connectingCounter = 0;
- return;
- }
-
- if (state == ZooKeeper.States.CONNECTING) {
- connectingCounter++;
- if (connectingCounter > 10) {
- log.fine("Long time in connecting, forcing a close of zookeeper client.");
- zkObjectHandler.close();
- connectingCounter = 0;
- }
- return;
- }
-
- if (state == ZooKeeper.States.CLOSED) {
- log.fine("Retrying connection to ZooKeeper.");
- try {
- zkObjectHandler.setZooKeeper(
- new ZooKeeper(connectString, SESSION_TIMEOUT, this));
- } catch (IOException e) {
- log.log(Level.SEVERE, "RetryConnection failed for some reason:"
- + e.getMessage(), e);
- }
- return;
- }
-
- log.severe("Unknown state " + state + " closing....");
- zkObjectHandler.close();
- }
-
-
- /**
- * Connect to ZooKeeper instance with time-out value.
- * @param waitTime time-out value for establishing connection.
- * @param waitUnit time unit for time-out when establishing connection.
- * @throws CloudnameException if connection can not be established
- * @return
- */
- public ZkCloudname connectWithTimeout(long waitTime, TimeUnit waitUnit)
- throws CloudnameException {
- boolean connected = false;
- try {
-
- zkObjectHandler = new ZkObjectHandler(
- new ZooKeeper(connectString, SESSION_TIMEOUT, this));
-
- if (! connectedSignal.await(waitTime, waitUnit)) {
- throw new CloudnameException("Connecting to ZooKeeper timed out.");
- }
- log.fine("Connected to ZooKeeper " + connectString);
- connected = true;
- } catch (IOException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } finally {
- if (!connected && zkObjectHandler != null) {
- zkObjectHandler.close();
- }
- }
- resolver = new ZkResolver.Builder().addStrategy(new StrategyAll())
- .addStrategy(new StrategyAny()).build(zkObjectHandler.getClient());
- scheduler.scheduleWithFixedDelay(this, 1 /* initial delay ms */,
- 1000 /* check state every second */, TimeUnit.MILLISECONDS);
- return this;
- }
-
- /**
- * Connect to ZooKeeper instance with long time-out, however, it might fail fast.
- * @return connected ZkCloudname object
- * @throws CloudnameException if connection can not be established.
- */
- public ZkCloudname connect() throws CloudnameException {
- // We wait up to 100 years.
- return connectWithTimeout(365 * 100, TimeUnit.DAYS);
- }
-
-
-
- @Override
- public void process(WatchedEvent event) {
- log.fine("Got event in ZkCloudname: " + event.toString());
- if (event.getState() == Event.KeeperState.Disconnected
- || event.getState() == Event.KeeperState.Expired) {
- zkObjectHandler.connectionDown();
- }
-
- // Initial connection to ZooKeeper is completed.
- if (event.getState() == Event.KeeperState.SyncConnected) {
- zkObjectHandler.connectionUp();
- // The first connection set up is blocking, this will unblock the connection.
- connectedSignal.countDown();
- }
- }
-
- /**
- * Create a given coordinate in the ZooKeeper node tree.
- *
- * Just blindly creates the entire path. Elements of the path may
- * exist already, but it seems wasteful to
- * @throws CoordinateExistsException if coordinate already exists-
- * @throws CloudnameException if problems with zookeeper connection.
- */
- @Override
- public void createCoordinate(final Coordinate coordinate)
- throws CloudnameException, CoordinateExistsException {
- // Create the root path for the coordinate. We do this
- // blindly, meaning that if the path already exists, then
- // that's ok -- so a more correct name for this method would
- // be ensureCoordinate(), but that might confuse developers.
- String root = ZkCoordinatePath.getCoordinateRoot(coordinate);
- final ZooKeeper zk = zkObjectHandler.getClient().getZookeeper();
- try {
- if (Util.exist(zk, root)) {
- throw new CoordinateExistsException("Coordinate already created:" +root);
- }
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
-
- try {
- Util.mkdir(zk, root, Ids.OPEN_ACL_UNSAFE);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
-
- // Create the nodes that represent subdirectories.
- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null);
- try {
- log.fine("Creating config node " + configPath);
- zk.create(configPath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
- }
-
- /**
- * Deletes a coordinate in the persistent service store. This includes deletion
- * of config. It will fail if the coordinate is claimed.
- * @param coordinate the coordinate we wish to destroy.
- */
- @Override
- public void destroyCoordinate(final Coordinate coordinate)
- throws CoordinateDeletionException, CoordinateMissingException, CloudnameException {
- String statusPath = ZkCoordinatePath.getStatusPath(coordinate);
- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null);
- String rootPath = ZkCoordinatePath.getCoordinateRoot(coordinate);
- final ZooKeeper zk = zkObjectHandler.getClient().getZookeeper();
- try {
- if (! Util.exist(zk, rootPath)) {
- throw new CoordinateMissingException("Coordinate not found: " + rootPath);
- }
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
-
-
- // Do this early to raise the error before anything is deleted. However, there might be a
- // race condition if someone claims while we delete configPath and instance (root) node.
- try {
- if (Util.exist(zk, configPath) && Util.hasChildren(zk, configPath)) {
- throw new CoordinateDeletionException("Coordinate has config node.");
- }
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
-
- try {
- if (Util.exist(zk, statusPath)) {
- throw new CoordinateDeletionException("Coordinate is claimed.");
- }
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
-
- // Delete config, the instance node, and continue with as much as possible.
- // We might have a raise condition if someone is creating a coordinate with a shared path
- // in parallel. We want to keep 3 levels of nodes (/cn/%CELL%/%USER%).
- int deletedNodes = 0;
- try {
- deletedNodes = Util.deletePathKeepRootLevels(zk, configPath, 3);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
- if (deletedNodes == 0) {
- throw new CoordinateDeletionException("Failed deleting config node, nothing deleted..");
- }
- if (deletedNodes == 1) {
- throw new CoordinateDeletionException("Failed deleting instance node.");
- }
- }
-
- /**
- * Claim a coordinate.
- *
- * In this implementation a coordinate is claimed by creating an
- * ephemeral with the name defined in CN_STATUS_NAME. If the node
- * already exists the coordinate has already been claimed.
- */
- @Override
- public ServiceHandle claim(final Coordinate coordinate) {
- String statusPath = ZkCoordinatePath.getStatusPath(coordinate);
- log.fine("Claiming " + coordinate.asString() + " (" + statusPath + ")");
-
- ClaimedCoordinate statusAndEndpoints = new ClaimedCoordinate(
- coordinate, zkObjectHandler.getClient());
-
- // If we have come thus far we have succeeded in creating the
- // CN_STATUS_NAME node within the service coordinate directory
- // in ZooKeeper and we can give the client a ServiceHandle.
- ZkServiceHandle handle = new ZkServiceHandle(
- statusAndEndpoints, coordinate, zkObjectHandler.getClient());
- statusAndEndpoints.start();
- return handle;
- }
-
- @Override
- public Resolver getResolver() {
-
- return resolver;
- }
-
- @Override
- public ServiceStatus getStatus(Coordinate coordinate) throws CloudnameException {
- String statusPath = ZkCoordinatePath.getStatusPath(coordinate);
- ZkCoordinateData zkCoordinateData = ZkCoordinateData.loadCoordinateData(
- statusPath, zkObjectHandler.getClient().getZookeeper(), null);
- return zkCoordinateData.snapshot().getServiceStatus();
- }
-
- @Override
- public void setConfig(
- final Coordinate coordinate, final String newConfig, final String oldConfig)
- throws CoordinateMissingException, CloudnameException {
- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null);
- int version = -1;
- final ZooKeeper zk = zkObjectHandler.getClient().getZookeeper();
- if (oldConfig != null) {
- Stat stat = new Stat();
- byte [] data = null;
- try {
- data = zk.getData(configPath, false, stat);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
- try {
- String stringData = new String(data, Util.CHARSET_NAME);
- if (! stringData.equals(oldConfig)) {
- throw new CloudnameException("Data did not match old config. Actual old "
- + stringData + " specified old " + oldConfig);
- }
- } catch (UnsupportedEncodingException e) {
- throw new CloudnameException(e);
- }
- version = stat.getVersion();
- }
- try {
- zk.setData(configPath, newConfig.getBytes(Util.CHARSET_NAME), version);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } catch (UnsupportedEncodingException e) {
- throw new CloudnameException(e);
- }
- }
-
-
- @Override
- public String getConfig(final Coordinate coordinate)
- throws CoordinateMissingException, CloudnameException {
- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null);
- Stat stat = new Stat();
- try {
- byte[] data = zkObjectHandler.getClient().getZookeeper().getData(
- configPath, false, stat);
- if (data == null) {
- return null;
- }
- return new String(data, Util.CHARSET_NAME);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } catch (UnsupportedEncodingException e) {
- throw new CloudnameException(e);
- }
- }
-
- /**
- * Close the connection to ZooKeeper.
- */
- @Override
- public void close() {
- zkObjectHandler.shutdown();
- log.fine("ZooKeeper session closed for " + connectString);
- scheduler.shutdown();
- }
-
- /**
- * List the sub-nodes in ZooKeeper owned by Cloudname.
- * @param nodeList
- */
- public void listRecursively(List<String> nodeList)
- throws CloudnameException, InterruptedException {
- Util.listRecursively(zkObjectHandler.getClient().getZookeeper(),
- ZkCoordinatePath.getCloudnameRoot(), nodeList);
- }
-
- /**
- * This class builds parameters for ZkCloudname.
- */
- public static class Builder {
- private String connectString;
-
- public Builder setConnectString(String connectString) {
- this.connectString = connectString;
- return this;
- }
-
- // TODO(borud, dybdahl): Make this smarter, some ideas:
- // Connect to one node and read from a magic path
- // how many zookeepers that are running and build
- // the path based on this information.
- public Builder setDefaultConnectString() {
- this.connectString = "z1:2181,z2:2181,z3:2181";
- return this;
- }
-
- public String getConnectString() {
- return connectString;
- }
-
- public ZkCloudname build() {
- if (connectString.isEmpty()) {
- throw new RuntimeException(
- "You need to specify connection string before you can build.");
- }
- return new ZkCloudname(this);
- }
- }
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ZkCoordinateData.java b/cn/src/main/java/org/cloudname/zk/ZkCoordinateData.java
deleted file mode 100644
index 622b6482..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkCoordinateData.java
+++ /dev/null
@@ -1,228 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.data.Stat;
-import org.cloudname.CloudnameException;
-import org.cloudname.Endpoint;
-import org.cloudname.ServiceState;
-import org.cloudname.ServiceStatus;
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * ZkCoordinateData represent the data regarding a coordinate. It can return an immutable snapshot.
- * The class has support for deserializing and serializing the data and methods for accessing
- * endpoints. The class is fully thread-safe.
- *
- * @auther dybdahl
- */
-public final class ZkCoordinateData {
- /**
- * The status of the coordinate, is it running etc.
- */
- private ServiceStatus serviceStatus = new ServiceStatus(ServiceState.UNASSIGNED,
- "No service state has been assigned");
-
- /**
- * The endpoints registered at the coordinate mapped by endpoint name.
- */
- private final Map<String, Endpoint> endpointsByName = new HashMap<String, Endpoint>();
-
- // Used for deserializing.
- private final ObjectMapper objectMapper = new ObjectMapper();
-
- private final Object localVariablesMonitor = new Object();
-
- /**
- * Create a new immutable snapshot object.
- */
- public Snapshot snapshot() {
- synchronized (localVariablesMonitor) {
- return new Snapshot(serviceStatus, endpointsByName);
- }
- }
-
- /**
- * Sets status, overwrite any existing status information.
- */
- public ZkCoordinateData setStatus(ServiceStatus status) {
- synchronized (localVariablesMonitor) {
- this.serviceStatus = status;
- return this;
- }
- }
-
- /**
- * Adds new endpoints to the builder. It is legal to add a new endpoint with an endpoint
- * that already exists.
- */
- public ZkCoordinateData putEndpoints(final List<Endpoint> newEndpoints) {
- synchronized (localVariablesMonitor) {
- for (Endpoint endpoint : newEndpoints) {
- endpointsByName.put(endpoint.getName(), endpoint);
- }
- }
- return this;
- }
-
- /**
- * Remove endpoints from the Dynamic object.
- */
- public ZkCoordinateData removeEndpoints(final List<String> names) {
- synchronized (localVariablesMonitor) {
- for (String name : names) {
- if (! endpointsByName.containsKey(name)) {
- throw new IllegalArgumentException("endpoint does not exist: " + name);
- }
- if (null == endpointsByName.remove(name)) {
- throw new IllegalArgumentException(
- "Endpoint does not exists, null in internal structure." + name);
- }
- }
- }
- return this;
- }
-
- /**
- * Sets the state of the Dynamic object based on a serialized byte string.
- * Any old data is overwritten.
- * @throws IOException if something went wrong, should not happen on valid data.
- */
- public ZkCoordinateData deserialize(byte[] data) throws IOException {
- synchronized (localVariablesMonitor) {
- final String stringData = new String(data, Util.CHARSET_NAME);
- final JsonFactory jsonFactory = new JsonFactory();
- final JsonParser jp = jsonFactory.createJsonParser(stringData);
- final String statusString = objectMapper.readValue(jp, new TypeReference<String>() {});
- serviceStatus = ServiceStatus.fromJson(statusString);
- endpointsByName.clear();
- endpointsByName.putAll((Map<String, Endpoint>)objectMapper.readValue(jp,
- new TypeReference <Map<String, Endpoint>>() {}));
- }
- return this;
- }
-
- /**
- * An immutable representation of the coordinate data.
- */
- public static class Snapshot {
- /**
- * The status of the coordinate, is it running etc.
- */
- private final ServiceStatus serviceStatus;
-
- /**
- * The endpoints registered at the coordinate mapped by endpoint name.
- */
- private final Map<String, Endpoint> endpointsByName;
-
- /**
- * Getter for status of coordinate.
- * @return the service status of the coordinate.
- */
- public ServiceStatus getServiceStatus() {
- return serviceStatus;
- }
-
- /**
- * Getter for endpoint of the coordinate given the endpoint name.
- * @param name of the endpoint.
- * @return the endpoint or null if non-existing.
- */
- public Endpoint getEndpoint(final String name) {
- return endpointsByName.get(name);
- }
-
- /**
- * Returns all the endpoints.
- * @return set of endpoints.
- */
- public Set<Endpoint> getEndpoints() {
- Set<Endpoint> endpoints = new HashSet<Endpoint>();
- endpoints.addAll(endpointsByName.values());
- return endpoints;
- }
-
- /**
- * A method for getting all endpoints.
- * @param endpoints The endpoints are put in this list.
- */
- public void appendAllEndpoints(final Collection<Endpoint> endpoints) {
- endpoints.addAll(endpointsByName.values());
- }
-
- /**
- * Return a serialized string representing the status and endpoint. It can be de-serialize
- * by the inner class.
- * @return The serialized string.
- * @throws IOException if something goes wrong, should not be a common problem though.
- */
- public String serialize() {
- final StringWriter stringWriter = new StringWriter();
- final JsonGenerator generator;
-
- try {
- generator = new JsonFactory(new ObjectMapper()).createJsonGenerator(stringWriter);
- generator.writeString(serviceStatus.toJson());
- generator.writeObject(endpointsByName);
-
- generator.flush();
- } catch (IOException e) {
- throw new RuntimeException(
- "Got IOException while serializing coordinate data." , e);
- }
- return new String(stringWriter.getBuffer());
- }
-
- /**
- * Private constructor, only ZkCoordinateData can build this.
- */
- private Snapshot(ServiceStatus serviceStatus, Map<String, Endpoint> endpointsByName) {
- this.serviceStatus = serviceStatus;
- this.endpointsByName = endpointsByName;
- }
- }
-
- /**
- * Utility function to create and load a ZkCoordinateData from ZooKeeper.
- * @param watcher for callbacks from ZooKeeper. It is ok to pass null.
- * @throws CloudnameException when problems loading data.
- */
- static public ZkCoordinateData loadCoordinateData(
- final String statusPath, final ZooKeeper zk, final Watcher watcher)
- throws CloudnameException {
- Stat stat = new Stat();
- try {
- byte[] data;
- if (watcher == null) {
- data = zk.getData(statusPath, false, stat);
- } else {
- data = zk.getData(statusPath, watcher, stat);
- }
- return new ZkCoordinateData().deserialize(data);
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- } catch (UnsupportedEncodingException e) {
- throw new CloudnameException(e);
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- } catch (IOException e) {
- throw new CloudnameException(e);
- }
- }
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ZkCoordinatePath.java b/cn/src/main/java/org/cloudname/zk/ZkCoordinatePath.java
deleted file mode 100644
index 6e4eb847..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkCoordinatePath.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package org.cloudname.zk;
-
-import org.cloudname.Coordinate;
-
-
-/**
- * A class for creating paths for ZooKeeper.
- * The semantic of a path is string of the form /cn/%cell%/%user%/%service%/%instance%/[status]|[config/%name%]
-
- * The prefix /cn indicates that the content is owned by the CloudName library.
- * Anything that lives under this prefix can only be touched by the Cloudname library.
- * If clients begin to fiddle with nodes under this prefix directly, all deals are off.
- * @author: dybdahl
- */
-public final class ZkCoordinatePath {
- private static final String CN_PATH_PREFIX = "/cn";
- private static final String CN_STATUS_NAME = "status";
- private static final String CN_CONFIG_NAME = "config";
-
- public static String getCloudnameRoot() {
- return CN_PATH_PREFIX;
- }
- /**
- * Builds the root path of a coordinate.
- * @param coordinate
- * @return the path of the coordinate in ZooKeeper (/cn/%cell%/%user%/%service%/%instance%).
- */
- public static String getCoordinateRoot(final Coordinate coordinate) {
- return coordinateAsPath(coordinate.getCell(), coordinate.getUser(), coordinate.getService(),
- coordinate.getInstance());
- }
-
- /**
- * Builds the status path of a coordinate.
- * @param coordinate
- * @return full status path (/cn/%cell%/%user%/%service%/%instance%/status)
- */
- public static String getStatusPath(final Coordinate coordinate) {
- return getCoordinateRoot(coordinate) + "/" + CN_STATUS_NAME;
- }
-
- /**
- * Builds the config path of a coordinate.
- * @param coordinate
- * @param name if null, the last path of the path (/%name%) is not included.
- * @return config path /cn/%cell%/%user%/%service%/%instance%/config or
- * /cn/%cell%/%user%/%service%/%instance%/config/%name%
- */
- public static String getConfigPath(final Coordinate coordinate, final String name) {
- if (name == null) {
- return getCoordinateRoot(coordinate) + "/" + CN_CONFIG_NAME;
- }
- return getCoordinateRoot(coordinate) + "/" + CN_CONFIG_NAME + "/" + name;
- }
-
- /**
- * Builds first part of a ZooKeeper path.
- * @param cell
- * @param user
- * @param service
- * @return path (/cn/%cell%/%user%/%service%)
- */
- public static String coordinateWithoutInstanceAsPath(
- final String cell, final String user, final String service) {
- return CN_PATH_PREFIX + "/" + cell + "/" + user + "/" + service;
- }
-
- public static String getStatusPath(String cell, String user, String service, Integer instance) {
- return coordinateAsPath(cell, user, service, instance) + "/" + CN_STATUS_NAME;
- }
-
- /**
- * Builds first part of a ZooKeeper path.
- * @param cell
- * @param user
- * @param service
- * @param instance
- * @return path (/cn/%cell%/%user%/%service%/%instance%)
- */
- private static String coordinateAsPath(
- final String cell, final String user, final String service, Integer instance) {
- return coordinateWithoutInstanceAsPath(cell, user, service) + "/" + instance.toString();
- }
-
- // Should not be instantiated.
- private ZkCoordinatePath() {}
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ZkObjectHandler.java b/cn/src/main/java/org/cloudname/zk/ZkObjectHandler.java
deleted file mode 100644
index e17e0009..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkObjectHandler.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.ZooKeeper;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Class that keeps an instance of zookeeper. It has a sub-class with read access and
- * a listener service.
- * @author dybdahl
- */
-public class ZkObjectHandler {
- private ZooKeeper zooKeeper = null;
- private final Object zooKeeperMonitor = new Object();
-
- private final Set<ConnectionStateChanged> registeredCallbacks =
- new HashSet<ConnectionStateChanged>();
- private final Object callbacksMonitor = new Object();
-
- private final AtomicBoolean isConnected = new AtomicBoolean(true);
-
- /**
- * Constructor
- * @param zooKeeper first zooKeeper to use, should not be null.
- */
- public ZkObjectHandler(final ZooKeeper zooKeeper) {
- this.zooKeeper = zooKeeper;
- }
-
- /**
- * Interface for notification of connection state changes.
- */
- public interface ConnectionStateChanged {
- void connectionUp();
- void connectionDown();
- void shutDown();
- }
-
- /**
- * Indicate that zookeeper connection is working by calling this method.
- */
- public void connectionUp() {
- boolean previous = isConnected.getAndSet(true);
- if (previous == true) { return; }
- synchronized (callbacksMonitor) {
- for (ConnectionStateChanged connectionStateChanged : registeredCallbacks) {
- connectionStateChanged.connectionUp();
- }
- }
- }
-
- /**
- * Indicate that zookeeper connection is broken by calling this method.
- */
- public void connectionDown() {
- boolean previous = isConnected.getAndSet(false);
- if (previous == false) { return; }
- synchronized (callbacksMonitor) {
- for (ConnectionStateChanged connectionStateChanged : registeredCallbacks) {
- connectionStateChanged.connectionDown();
- }
- }
- }
-
- /**
- * Every class using Zookeeper has an instance of this Client class
- * to check the connection and fetch the instance.
- */
- public class Client {
- public ZooKeeper getZookeeper() {
- synchronized (zooKeeperMonitor) {
- return zooKeeper;
- }
- }
-
- /**
- * Check if we are connected to Zookeeper
- * @return True if zkCloudname confirmed connection <1000ms ago.
- */
- public boolean isConnected() {
- return isConnected.get();
- }
-
- /**
- * Register a callback.
- * @param connectionStateChanged Callback to register
- * @return true if this is a new callback.
- */
- public boolean registerListener(ConnectionStateChanged connectionStateChanged) {
- synchronized (callbacksMonitor) {
- return registeredCallbacks.add(connectionStateChanged);
- }
- }
-
- /**
- * Deregister a callback.
- * @param connectionStateChanged Callback to deregister.
- * @return true if the callback was registered.
- */
- public boolean deregisterListener(ConnectionStateChanged connectionStateChanged) {
- synchronized (callbacksMonitor) {
- return registeredCallbacks.remove(connectionStateChanged);
- }
- }
- }
-
- /**
- * Returns client
- * @return client object.
- */
- public Client getClient() {
- return new Client();
- }
-
- /**
- * Update zooKeeper instance.
- * @param zooKeeper
- */
- public void setZooKeeper(final ZooKeeper zooKeeper) {
- synchronized (zooKeeperMonitor) {
- this.zooKeeper = zooKeeper;
- }
- }
-
- /**
- * Closes zooKeeper object.
- */
- public void close() {
- synchronized (zooKeeperMonitor) {
- if (zooKeeper == null) { return; }
-
- try {
- zooKeeper.close();
- } catch (InterruptedException e) {
- // ignore
- }
- }
- }
-
- /**
- * Shut down all listeners.
- */
- public void shutdown() {
- synchronized (callbacksMonitor) {
- for (ConnectionStateChanged connectionStateChanged : registeredCallbacks) {
- connectionStateChanged.shutDown();
- }
- }
- try {
- zooKeeper.close();
- } catch (InterruptedException e) {
- // ignore
- }
- }
-}
\ No newline at end of file
diff --git a/cn/src/main/java/org/cloudname/zk/ZkResolver.java b/cn/src/main/java/org/cloudname/zk/ZkResolver.java
deleted file mode 100644
index 80b49197..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkResolver.java
+++ /dev/null
@@ -1,460 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
-import org.cloudname.*;
-
-import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
-
-
-/**
- * This class is used to resolve Cloudname coordinates into endpoints.
- *
- * @author borud
- */
-public final class ZkResolver implements Resolver, ZkObjectHandler.ConnectionStateChanged {
-
- private static final Logger log = Logger.getLogger(ZkResolver.class.getName());
-
- private Map<String, ResolverStrategy> strategies;
-
- private final ZkObjectHandler.Client zkGetter;
-
- private final Object dynamicAddressMonitor = new Object();
-
- private Map<ResolverListener, DynamicExpression> dynamicAddressesByListener = new HashMap<ResolverListener, DynamicExpression>();
-
- @Override
- public void connectionUp() {
- synchronized (dynamicAddressMonitor) {
- for (ResolverListener listener : dynamicAddressesByListener.keySet()) {
- listener.endpointEvent(ResolverListener.Event.CONNECTION_OK, null);
- }
- }
- }
-
- @Override
- public void connectionDown() {
- synchronized (dynamicAddressMonitor) {
- for (ResolverListener listener : dynamicAddressesByListener.keySet()) {
- listener.endpointEvent(ResolverListener.Event.LOST_CONNECTION, null);
- }
- }
- }
-
- @Override
- public void shutDown() {
- // Nothing to shut down here.
- }
-
- public static class Builder {
-
- final private Map<String, ResolverStrategy> strategies = new HashMap<String, ResolverStrategy>();
-
- public Builder addStrategy(ResolverStrategy strategy) {
- strategies.put(strategy.getName(), strategy);
- return this;
- }
-
- public Map<String, ResolverStrategy> getStrategies() {
- return strategies;
- }
-
- public ZkResolver build(ZkObjectHandler.Client zkGetter) {
- return new ZkResolver(this, zkGetter);
- }
-
- }
-
-
- // Matches coordinate with endpoint of the form:
- // endpoint.instance.service.user.cell
- public static final Pattern endpointPattern
- = Pattern.compile( "^([a-z][a-z0-9-_]*)\\." // endpoint
- + "(\\d+)\\." // instance
- + "([a-z][a-z0-9-_]*)\\." // service
- + "([a-z][a-z0-9-_]*)\\." // user
- + "([a-z][a-z-_]*)\\z"); // cell
-
- // Parses abstract coordinate of the form:
- // strategy.service.user.cell. This pattern is useful for
- // resolving hosts, but not endpoints.
- public static final Pattern strategyPattern
- = Pattern.compile( "^([a-z][a-z0-9-_]*)\\." // strategy
- + "([a-z][a-z0-9-_]*)\\." // service
- + "([a-z][a-z0-9-_]*)\\." // user
- + "([a-z][a-z0-9-_]*)\\z"); // cell
-
- // Parses abstract coordinate of the form:
- // strategy.service.user.cell. This pattern is useful for
- // resolving hosts, but not endpoints.
- public static final Pattern instancePattern
- = Pattern.compile( "^([a-z0-9-_]*)\\." // strategy
- + "([a-z][a-z0-9-_]*)\\." // service
- + "([a-z][a-z0-9-_]*)\\." // user
- + "([a-z][a-z0-9-_]*)\\z"); // cell
-
- // Parses abstract coordinate of the form:
- // endpoint.strategy.service.user.cell.
- public static final Pattern endpointStrategyPattern
- = Pattern.compile( "^([a-z][a-z0-9-_]*)\\." // endpoint
- + "([a-z][a-z0-9-_]*)\\." // strategy
- + "([a-z][a-z0-9-_]*)\\." // service
- + "([a-z][a-z0-9-_]*)\\." // user
- + "([a-z][a-z0-9-_]*)\\z"); // cell
-
-
- /**
- * Inner class to keep track of parameters parsed from addressExpression.
- */
- static class Parameters {
- private String endpointName = null;
- private Integer instance = null;
- private String service = null;
- private String user = null;
- private String cell = null;
- private String strategy = null;
- private String expression = null;
-
- /**
- * Constructor that takes an addressExperssion and sets the inner variables.
- * @param addressExpression
- */
- public Parameters(String addressExpression) {
- this.expression = addressExpression;
- if (! (trySetEndPointPattern(addressExpression) ||
- trySetStrategyPattern(addressExpression) ||
- trySetInstancePattern(addressExpression) ||
- trySetEndpointStrategyPattern(addressExpression))) {
- throw new IllegalStateException(
- "Could not parse addressExpression:" + addressExpression);
- }
-
- }
-
- /**
- * Returns the original expression set in the constructor of Parameters.
- * @return expression to be resolved.
- */
- public String getExpression() {
- return expression;
- }
-
- /**
- * Returns strategy.
- * @return the string (e.g. "all" or "any", or "" if there is no strategy
- * (but instance is specified).
- */
- public String getStrategy() {
- return strategy;
- }
-
- /**
- * Returns endpoint name if set or "" if not set.
- * @return endpointname.
- */
- public String getEndpointName() {
- return endpointName;
- }
-
- /**
- * Returns instance if set or negative number if not set.
- * @return instance number.
- */
- public Integer getInstance() {
- return instance;
- }
-
- /**
- * Returns service
- * @return service name.
- */
- public String getService() {
- return service;
- }
-
- /**
- * Returns user
- * @return user.
- */
- public String getUser() {
- return user;
- }
-
- /**
- * Returns cell.
- * @return cell.
- */
- public String getCell() {
- return cell;
- }
-
- private boolean trySetEndPointPattern(String addressExperssion) {
- Matcher m = endpointPattern.matcher(addressExperssion);
- if (! m.matches()) {
- return false;
- }
- endpointName = m.group(1);
- instance = Integer.parseInt(m.group(2));
- strategy = "";
- service = m.group(3);
- user = m.group(4);
- cell = m.group(5);
- return true;
-
- }
-
- private boolean trySetStrategyPattern(String addressExpression) {
- Matcher m = strategyPattern.matcher(addressExpression);
- if (! m.matches()) {
- return false;
- }
- endpointName = "";
- strategy = m.group(1);
- service = m.group(2);
- user = m.group(3);
- cell = m.group(4);
- instance = -1;
- return true;
- }
-
- private boolean trySetInstancePattern(String addressExpression) {
- Matcher m = instancePattern.matcher(addressExpression);
- if (! m.matches()) {
- return false;
- }
- endpointName = "";
- instance = Integer.parseInt(m.group(1));
- service = m.group(2);
- user = m.group(3);
- cell = m.group(4);
- strategy = "";
- return true;
- }
-
- private boolean trySetEndpointStrategyPattern(String addressExperssion) {
- Matcher m = endpointStrategyPattern.matcher(addressExperssion);
- if (! m.matches()) {
- return false;
- }
- endpointName = m.group(1);
- strategy = m.group(2);
- service = m.group(3);
- user = m.group(4);
- cell = m.group(5);
- instance = -1;
- return true;
- }
-
- }
-
- /**
- * Constructor, to be called from the inner Dynamic class.
- * @param builder
- */
- private ZkResolver(Builder builder, ZkObjectHandler.Client zkGetter) {
- this.strategies = builder.getStrategies();
- this.zkGetter = zkGetter;
- zkGetter.registerListener(this);
- }
-
-
- @Override
- public List<Endpoint> resolve(String addressExpression) throws CloudnameException {
- Parameters parameters = new Parameters(addressExpression);
- // TODO(borud): add some comments on the decision logic. I'm
- // not sure I am too fond of the check for negative values to
- // have some particular semantics. That smells like a problem
- // waiting to happen.
-
- ZooKeeper localZkPointer = zkGetter.getZookeeper();
- if (localZkPointer == null) {
- throw new CloudnameException("No connection to ZooKeeper.");
- }
- List<Integer> instances = resolveInstances(parameters, localZkPointer);
-
- List<Endpoint> endpoints = new ArrayList<Endpoint>();
- for (Integer instance : instances) {
- String statusPath = ZkCoordinatePath.getStatusPath(
- parameters.getCell(), parameters.getUser(),
- parameters.getService(), instance);
-
- try {
- if (! Util.exist(localZkPointer, statusPath)) {
- continue;
- }
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
-
- }
- final ZkCoordinateData zkCoordinateData = ZkCoordinateData.loadCoordinateData(
- statusPath, localZkPointer, null);
- addEndpoints(zkCoordinateData.snapshot(), endpoints, parameters.getEndpointName());
-
- }
- if (parameters.getStrategy().equals("")) {
- return endpoints;
- }
- ResolverStrategy strategy = strategies.get(parameters.getStrategy());
- return strategy.order(strategy.filter(endpoints));
- }
-
- @Override
- public void removeResolverListener(final ResolverListener listener) {
- synchronized (dynamicAddressMonitor) {
- DynamicExpression expression = dynamicAddressesByListener.remove(listener);
- if (expression == null) {
- throw new IllegalArgumentException("Do not have the listener in my list.");
- }
- expression.stop();
- }
- log.fine("Removed listener.");
- }
-
- /**
- * The implementation does filter while listing out nodes. In this way paths that are not of
- * interest are not traversed.
- * @param filter class for filtering out endpoints
- * @return the endpoints that passes the filter
- */
- @Override
- public Set<Endpoint> getEndpoints(final Resolver.CoordinateDataFilter filter)
- throws CloudnameException, InterruptedException {
-
- final Set<Endpoint> endpointsIncluded = new HashSet<Endpoint>();
- final String cellPath = ZkCoordinatePath.getCloudnameRoot();
- final ZooKeeper zk = zkGetter.getZookeeper();
- try {
- final List<String> cells = zk.getChildren(cellPath, false);
- for (final String cell : cells) {
- if (! filter.includeCell(cell)) {
- continue;
- }
- final String userPath = cellPath + "/" + cell;
- final List<String> users = zk.getChildren(userPath, false);
-
- for (final String user : users) {
- if (! filter.includeUser(user)) {
- continue;
- }
- final String servicePath = userPath + "/" + user;
- final List<String> services = zk.getChildren(servicePath, false);
-
- for (final String service : services) {
- if (! filter.includeService(service)) {
- continue;
- }
- final String instancePath = servicePath + "/" + service;
- final List<String> instances = zk.getChildren(instancePath, false);
-
- for (final String instance : instances) {
- final String statusPath;
- try {
- statusPath = ZkCoordinatePath.getStatusPath(
- cell, user, service, Integer.parseInt(instance));
- } catch (NumberFormatException e) {
- log.log(
- Level.WARNING,
- "Got non-number as instance in cn path: " + instancePath + "/"
- + instance + " skipping.",
- e);
- continue;
- }
-
- ZkCoordinateData zkCoordinateData = null;
- try {
- zkCoordinateData = ZkCoordinateData.loadCoordinateData(
- statusPath, zk, null);
- } catch (CloudnameException e) {
- // This is ok, an unclaimed node will not have status data, we
- // ignore it even though there might also be other exception
- // (this should be rare). The advantage is that we don't need to
- // check if the node exists and hence reduce the load on zookeeper.
- continue;
- }
- final Set<Endpoint> endpoints = zkCoordinateData.snapshot().getEndpoints();
- for (final Endpoint endpoint : endpoints) {
- if (filter.includeEndpointname(endpoint.getName())) {
- if (filter.includeServiceState(
- zkCoordinateData.snapshot().getServiceStatus().getState())) {
- endpointsIncluded.add(endpoint);
- }
- }
- }
- }
- }
- }
- }
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- return endpointsIncluded;
- }
-
- @Override
- public void addResolverListener(String expression, ResolverListener listener)
- throws CloudnameException {
- final DynamicExpression dynamicExpression =
- new DynamicExpression(expression, listener, this, zkGetter);
-
- synchronized (dynamicAddressMonitor) {
- DynamicExpression previousExpression = dynamicAddressesByListener.put(
- listener, dynamicExpression);
- if (previousExpression != null) {
- throw new IllegalArgumentException("It is not legal to register a listener twice.");
- }
- }
- dynamicExpression.start();
- }
-
- public static void addEndpoints(
- ZkCoordinateData.Snapshot statusAndEndpoints, List<Endpoint> endpoints,
- String endpointname) {
- if (statusAndEndpoints.getServiceStatus().getState() != ServiceState.RUNNING) {
- return;
- }
- if (endpointname.equals("")) {
- statusAndEndpoints.appendAllEndpoints(endpoints);
- } else {
- Endpoint e = statusAndEndpoints.getEndpoint(endpointname);
- if (e != null) {
- endpoints.add(e);
- }
- }
- }
-
- private List<Integer> resolveInstances(Parameters parameters, ZooKeeper zk)
- throws CloudnameException {
- List<Integer> instances = new ArrayList<Integer>();
- if (parameters.getInstance() > -1) {
- instances.add(parameters.getInstance());
- } else {
- try {
- instances = getInstances(zk,
- ZkCoordinatePath.coordinateWithoutInstanceAsPath(parameters.getCell(),
- parameters.getUser(), parameters.getService()));
- } catch (InterruptedException e) {
- throw new CloudnameException(e);
- }
- }
- return instances;
- }
-
- private List<Integer> getInstances(ZooKeeper zk, String path)
- throws CloudnameException, InterruptedException {
- List<Integer> paths = new ArrayList<Integer>();
- try {
- List<String> children = zk.getChildren(path, false /* watcher */);
- for (String child : children) {
- paths.add(Integer.parseInt(child));
- }
- } catch (KeeperException e) {
- throw new CloudnameException(e);
- }
- return paths;
- }
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ZkServiceHandle.java b/cn/src/main/java/org/cloudname/zk/ZkServiceHandle.java
deleted file mode 100644
index eb8fb837..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkServiceHandle.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package org.cloudname.zk;
-
-import org.cloudname.*;
-
-import java.util.ArrayList;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Logger;
-
-import java.util.List;
-
-/**
- * A service handle implementation. It does not have a lot of logic, it wraps ClaimedCoordinate, and
- * handles some config logic.
- *
- * @author borud
- */
-public class ZkServiceHandle implements ServiceHandle {
- private final ClaimedCoordinate claimedCoordinate;
- private static final Logger LOG = Logger.getLogger(ZkServiceHandle.class.getName());
-
- private final ZkObjectHandler.Client zkClient;
-
- private final Coordinate coordinate;
-
- /**
- * Create a ZkServiceHandle for a given coordinate.
- *
- * @param claimedCoordinate the claimed coordinate for this service handle.
- */
- public ZkServiceHandle(
- ClaimedCoordinate claimedCoordinate, Coordinate coordinate,
- ZkObjectHandler.Client zkClient) {
- this.claimedCoordinate = claimedCoordinate;
- this.coordinate = coordinate;
- this.zkClient = zkClient;
- }
-
-
- @Override
- public boolean waitForCoordinateOkSeconds(int seconds) throws InterruptedException {
- final CountDownLatch latch = new CountDownLatch(1);
-
- CoordinateListener listner = new CoordinateListener() {
-
- @Override
- public void onCoordinateEvent(Event event, String message) {
- if (event == Event.COORDINATE_OK) {
- latch.countDown();
- }
- }
- };
- registerCoordinateListener(listner);
- boolean result = latch.await(seconds, TimeUnit.SECONDS);
- claimedCoordinate.deregisterCoordinateListener(listner);
- return result;
- }
-
-
- @Override
- public void setStatus(ServiceStatus status)
- throws CoordinateMissingException, CloudnameException {
- claimedCoordinate.updateStatus(status);
- }
-
- @Override
- public void putEndpoints(List<Endpoint> endpoints)
- throws CoordinateMissingException, CloudnameException {
- claimedCoordinate.putEndpoints(endpoints);
- }
-
- @Override
- public void putEndpoint(Endpoint endpoint)
- throws CoordinateMissingException, CloudnameException {
- List<Endpoint> endpoints = new ArrayList<Endpoint>();
- endpoints.add(endpoint);
- putEndpoints(endpoints);
- }
-
- @Override
- public void removeEndpoints(List<String> names)
- throws CoordinateMissingException, CloudnameException {
- claimedCoordinate.removeEndpoints(names);
- }
-
- @Override
- public void removeEndpoint(String name)
- throws CoordinateMissingException, CloudnameException {
- List<String> names = new ArrayList<String>();
- names.add(name);
- removeEndpoints(names);
- }
-
- @Override
- public void registerConfigListener(ConfigListener listener) {
- TrackedConfig trackedConfig = new TrackedConfig(
- ZkCoordinatePath.getConfigPath(coordinate, null), listener, zkClient);
- claimedCoordinate.registerTrackedConfig(trackedConfig);
- trackedConfig.start();
- }
-
- @Override
- public void registerCoordinateListener(CoordinateListener listener) {
- claimedCoordinate.registerCoordinateListener(listener);
- }
-
- @Override
- public void close() throws CloudnameException {
- claimedCoordinate.releaseClaim();
- }
-
- @Override
- public String toString() {
- return "Claimed coordinate instance: "+ claimedCoordinate.toString();
- }
-}
diff --git a/cn/src/main/java/org/cloudname/zk/ZkTool.java b/cn/src/main/java/org/cloudname/zk/ZkTool.java
deleted file mode 100644
index 7be0f8cf..00000000
--- a/cn/src/main/java/org/cloudname/zk/ZkTool.java
+++ /dev/null
@@ -1,359 +0,0 @@
-package org.cloudname.zk;
-
-import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.ConsoleAppender;
-import org.apache.log4j.Level;
-import org.apache.log4j.PatternLayout;
-import org.cloudname.*;
-import org.cloudname.Resolver.ResolverListener;
-import org.cloudname.flags.Flag;
-import org.cloudname.flags.Flags;
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-
-/**
- * Command line tool for using the Cloudname library. Run with
- * <code>--help</code> option to see available flags.
- *
- * @author dybdahl
- */
-public final class ZkTool {
- @Flag(name="zookeeper", description="A list of host:port for connecting to ZooKeeper.")
- private static String zooKeeperFlag = null;
-
- @Flag(name="coordinate", description="The coordinate to work on.")
- private static String coordinateFlag = null;
-
- @Flag(name="operation", options = Operation.class,
- description = "The operation to do on coordinate.")
- private static Operation operationFlag = Operation.STATUS;
-
- @Flag(name = "setup-file",
- description = "Path to file containing a list of coordinates to create (1 coordinate per line).")
- private static String filePath = null;
-
- @Flag(name = "config",
- description = "New config if setting new config.")
- private static String configFlag = "";
-
- @Flag(name = "resolver-expression",
- description = "The resolver expression to listen to events for.")
- private static String resolverExpression = null;
-
- @Flag(name = "list",
- description = "Print the coordinates in ZooKeeper.")
- private static Boolean listFlag = null;
-
- /**
- * List of flag names for flags that select which action the tool should
- * perform. These flags are mutually exclusive.
- */
- private static String actionSelectingFlagNames =
- "--setup-file, --resolver, --coordinate, --list";
-
- /**
- * The possible operations to do on a coordinate.
- */
- public enum Operation {
- /**
- * Create a new coordinate.
- */
- CREATE,
- /**
- * Delete a coordinate.
- */
- DELETE,
- /**
- * Print out some status about a coordinate.
- */
- STATUS,
- /**
- * Print the host of a coordinate.
- */
- HOST,
- /**
- * Set config
- */
- SET_CONFIG,
- /**
- * Read config
- */
- READ_CONFIG;
- }
-
- /**
- * Matches coordinate of type: cell.user.service.instance.config.
- */
- public static final Pattern instanceConfigPattern
- = Pattern.compile("\\/cn\\/([a-z][a-z-_]*)\\/" // cell
- + "([a-z][a-z0-9-_]*)\\/" // user
- + "([a-z][a-z0-9-_]*)\\/" // service
- + "(\\d+)\\/config\\z"); // instance
-
- private static ZkCloudname cloudname = null;
-
- public static void main(final String[] args) {
-
- // Disable log system, we want full control over what is sent to console.
- final ConsoleAppender consoleAppender = new ConsoleAppender();
- consoleAppender.activateOptions();
- consoleAppender.setLayout(new PatternLayout("%p %t %C:%M %m%n"));
- consoleAppender.setThreshold(Level.OFF);
- BasicConfigurator.configure(consoleAppender);
-
- // Parse the flags.
- Flags flags = new Flags()
- .loadOpts(ZkTool.class)
- .parse(args);
-
- // Check if we wish to print out help text
- if (flags.helpFlagged()) {
- flags.printHelp(System.out);
- System.out.println("Must specify one of the following options:");
- System.out.println(actionSelectingFlagNames);
- return;
- }
-
- checkArgumentCombinationValid(flags);
-
- ZkCloudname.Builder builder = new ZkCloudname.Builder();
- if (zooKeeperFlag == null) {
- builder.setDefaultConnectString();
- } else {
- builder.setConnectString(zooKeeperFlag);
- }
- try {
- cloudname = builder.build().connect();
- } catch (CloudnameException e) {
- System.err.println("Could not connect to zookeeper " + e.getMessage());
- return;
- }
-
- try {
- if (filePath != null) {
- handleFilepath();
- } else if (coordinateFlag != null) {
- handleCoordinateOperation();
- } else if (resolverExpression != null) {
- handleResolverExpression();
- } else if (listFlag) {
- listCoordinates();
- } else {
- System.err.println("No action specified");
- }
- } catch (Exception e) {
- System.err.println("An error occurred: " + e.getMessage());
- e.printStackTrace();
- } finally {
- cloudname.close();
- }
- }
-
- private static void checkArgumentCombinationValid(final Flags flags) {
- int actionSelectedCount = 0;
- final Object[] actionSelectingFlags = {
- filePath, coordinateFlag, resolverExpression, listFlag
- };
- for (Object flag: actionSelectingFlags) {
- if (flag != null) {
- actionSelectedCount++;
- }
- }
- if (actionSelectedCount != 1) {
- System.err.println("Must specify exactly one of the following options:");
- System.err.println(actionSelectingFlagNames);
- flags.printHelp(System.err);
- System.exit(1);
- }
- }
-
- private static void handleResolverExpression() {
- final Resolver resolver = cloudname.getResolver();
- try {
- System.out.println("Added a resolver listener for expression: " + resolverExpression + ". Will print out all events for the given expression.");
- resolver.addResolverListener(resolverExpression, new ResolverListener() {
- @Override
- public void endpointEvent(Event event, Endpoint endpoint) {
- System.out.println("Received event: " + event + " for endpoint: " + endpoint);
- }
- });
- } catch (CloudnameException e) {
- System.err.println("Problem with cloudname: " + e.getMessage());
- }
- final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- while(true) {
- System.out.println("Press enter to exit");
- String s = null;
- try {
- s = br.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (s.length() == 0) {
- System.out.println("Exiting");
- System.exit(0);
- }
- }
- }
-
- private static void handleCoordinateOperation() {
- final Resolver resolver = cloudname.getResolver();
- final Coordinate coordinate = Coordinate.parse(coordinateFlag);
- switch (operationFlag) {
- case CREATE:
- try {
- cloudname.createCoordinate(coordinate);
- } catch (CloudnameException e) {
- System.err.println("Got error: " + e.getMessage());
- break;
- } catch (CoordinateExistsException e) {
- e.printStackTrace();
- break;
- }
- System.err.println("Created coordinate.");
- break;
- case DELETE:
- try {
- cloudname.destroyCoordinate(coordinate);
- } catch (CoordinateDeletionException e) {
- System.err.println("Got error: " + e.getMessage());
- return;
- } catch (CoordinateMissingException e) {
- System.err.println("Got error: " + e.getMessage());
- break;
- } catch (CloudnameException e) {
- System.err.println("Got error: " + e.getMessage());
- break;
- }
- System.err.println("Deleted coordinate.");
- break;
- case STATUS: {
- ServiceStatus status;
- try {
- status = cloudname.getStatus(coordinate);
- } catch (CloudnameException e) {
- System.err.println("Problems loading status, is service running? Error:\n" + e.getMessage());
- break;
- }
- System.err.println("Status:\n" + status.getState().toString() + " " + status.getMessage());
- List<Endpoint> endpoints = null;
- try {
- endpoints = resolver.resolve("all." + coordinate.getService()
- + "." + coordinate.getUser() + "." + coordinate.getCell());
- } catch (CloudnameException e) {
- System.err.println("Got error: " + e.getMessage());
- break;
- }
- System.err.println("Endpoints:");
- for (Endpoint endpoint : endpoints) {
- if (endpoint.getCoordinate().getInstance() == coordinate.getInstance()) {
- System.err.println(endpoint.getName() + "-->" + endpoint.getHost() + ":" + endpoint.getPort()
- + " protocol:" + endpoint.getProtocol());
- System.err.println("Endpoint data:\n" + endpoint.getEndpointData());
- }
- }
- break;
- }
- case HOST: {
- List<Endpoint> endpoints = null;
- try {
- endpoints = resolver.resolve(coordinate.asString());
- } catch (CloudnameException e) {
- System.err.println("Could not resolve " + coordinate.asString() + " Error:\n" + e.getMessage());
- break;
- }
- for (Endpoint endpoint : endpoints) {
- System.out.println("Host: " + endpoint.getHost());
- }
- }
- break;
- case SET_CONFIG:
- try {
- cloudname.setConfig(coordinate, configFlag, null);
- } catch (CloudnameException e) {
- System.err.println("Got error: " + e.getMessage());
- break;
-
- } catch (CoordinateMissingException e) {
- System.err.println("Non-existing coordinate.");
- }
- System.err.println("Config updated.");
- break;
-
- case READ_CONFIG:
- try {
- System.out.println("Config is:" + cloudname.getConfig(coordinate));
- } catch (CoordinateMissingException e) {
- System.err.println("Non-existing coordinate.");
- } catch (CloudnameException e) {
- System.err.println("Problem with cloudname: " + e.getMessage());
- }
- break;
- default:
- System.out.println("Unknown command " + operationFlag);
- }
- }
-
- private static void listCoordinates() {
- try {
- final List<String> nodeList = new ArrayList<String>();
- cloudname.listRecursively(nodeList);
- for (final String node : nodeList) {
- final Matcher m = instanceConfigPattern.matcher(node);
-
- /*
- * We only parse config paths, and we convert these to
- * Cloudname coordinates to not confuse the user.
- */
- if (m.matches()) {
- System.out.printf("%s.%s.%s.%s\n",
- m.group(4), m.group(3), m.group(2), m.group(1));
- }
- }
- } catch (final CloudnameException e) {
- System.err.println("Got error: " + e.getMessage());
- } catch (final InterruptedException e) {
- System.err.println("Got error: " + e.getMessage());
- }
- }
-
- private static void handleFilepath() {
- final BufferedReader br;
- try {
- br = new BufferedReader(new FileReader(filePath));
- } catch (FileNotFoundException e) {
- throw new RuntimeException("File not found: " + filePath, e);
- }
- String line;
- try {
- while ((line = br.readLine()) != null) {
- try {
- cloudname.createCoordinate(Coordinate.parse(line));
- System.out.println("Created " + line);
- } catch (Exception e) {
- System.err.println("Could not create: " + line + "Got error: " + e.getMessage());
- }
- }
- } catch (IOException e) {
- throw new RuntimeException("Failed to read coordinate from file. " + e.getMessage(), e);
- } finally {
- cloudname.close();
- try {
- br.close();
- } catch (IOException e) {
- System.err.println("Failed while trying to close file reader. " + e.getMessage());
- }
- }
- }
-
- // Should not be instantiated.
- private ZkTool() {}
-}
diff --git a/cn/src/test/java/org/cloudname/CoordinateTest.java b/cn/src/test/java/org/cloudname/CoordinateTest.java
deleted file mode 100644
index 42ee09cc..00000000
--- a/cn/src/test/java/org/cloudname/CoordinateTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package org.cloudname;
-
-import org.junit.*;
-import static org.junit.Assert.*;
-
-/**
- * Unit tests for Coordinate.
- *
- * @author borud
- */
-public class CoordinateTest {
- @Test
- public void testSimple() throws Exception {
- Coordinate c = Coordinate.parse("1.service.user.cell");
- assertNotNull(c);
- assertEquals(1, c.getInstance());
- assertEquals("service", c.getService());
- assertEquals("user", c.getUser());
- assertEquals("cell", c.getCell());
- }
-
- @Test (expected = IllegalArgumentException.class)
- public void testInvalidInstanceNumber() throws Exception {
- new Coordinate(-1, "service", "user", "cell");
- }
-
- @Test
- public void testEquals() throws Exception {
- assertEquals(
- new Coordinate(1,"foo", "bar", "baz"),
- new Coordinate(1, "foo", "bar", "baz")
- );
- }
-
- @Test
- public void testSymmetry() throws Exception {
- String s = "0.fooservice.baruser.bazcell";
- assertEquals(s, Coordinate.parse(s).asString());
- assertEquals(s, new Coordinate(0,
- "fooservice",
- "baruser",
- "bazcell").asString());
-
- System.out.println(Coordinate.parse(s));
- }
-
- @Test (expected = IllegalArgumentException.class)
- public void testInvalidInstance() throws Exception {
- Coordinate.parse("invalid.service.user.cell");
- }
-
- @Test (expected = IllegalArgumentException.class)
- public void testInvalidCharacters() throws Exception {
- Coordinate.parse("0.ser!vice.user.cell");
- }
-
- @Test
- public void testLegalCharacters() throws Exception {
- Coordinate.parse("0.service-test.user.cell");
- Coordinate.parse("0.service_test.user.cell");
- Coordinate.parse("0.service.user-foo.cell");
- Coordinate.parse("0.service.user_foo.ce_ll");
- }
-
- @Test (expected = IllegalArgumentException.class)
- public void testRequireStartsWithLetter() throws Exception {
- Coordinate.parse("0._aaa._bbb._ccc");
- }
-
- @Test (expected = IllegalArgumentException.class)
- public void testIllegalArgumentsConstructor() throws Exception {
- new Coordinate(1, "service", "_user", "cell");
- }
-}
\ No newline at end of file
diff --git a/cn/src/test/java/org/cloudname/EndpointTest.java b/cn/src/test/java/org/cloudname/EndpointTest.java
deleted file mode 100644
index 0769ac51..00000000
--- a/cn/src/test/java/org/cloudname/EndpointTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.cloudname;
-
-import org.junit.*;
-import static org.junit.Assert.*;
-
-/**
- * Unit tests for Endpoint.
- *
- * @author borud
- */
-public class EndpointTest {
- @Test
- public void testSimple() throws Exception {
- Endpoint endpoint = new Endpoint(Coordinate.parse("1.foo.bar.zot"),
- "rest-api",
- "somehost",
- 4711,
- "http",
- null);
- String json = endpoint.toJson();
- Endpoint endpoint2 = Endpoint.fromJson(json);
-
- assertEquals(endpoint.getCoordinate(), endpoint2.getCoordinate());
- assertEquals(endpoint.getName(), endpoint2.getName());
- assertEquals(endpoint.getHost(), endpoint2.getHost());
- assertEquals(endpoint.getPort(), endpoint2.getPort());
- assertEquals(endpoint.getEndpointData(), endpoint2.getEndpointData());
-
- System.out.println(json);
- }
-}
\ No newline at end of file
diff --git a/cn/src/test/java/org/cloudname/ServiceStatusTest.java b/cn/src/test/java/org/cloudname/ServiceStatusTest.java
deleted file mode 100644
index ec7fe5b3..00000000
--- a/cn/src/test/java/org/cloudname/ServiceStatusTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.cloudname;
-
-import org.junit.*;
-import static org.junit.Assert.*;
-
-/**
- * Unit tests for ServiceStatus.
- *
- * @author borud
- */
-public class ServiceStatusTest {
- @Test
- public void testSimple() throws Exception {
- ServiceStatus status = new ServiceStatus(ServiceState.STARTING,
- "Loading hamster into wheel");
- String json = status.toJson();
- assertNotNull(json);
-
- ServiceStatus status2 = ServiceStatus.fromJson(json);
-
- assertEquals(status.getMessage(), status2.getMessage());
- assertSame(status.getState(), status2.getState());
- }
-}
\ No newline at end of file
diff --git a/cn/src/test/java/org/cloudname/StrategyAnyTest.java b/cn/src/test/java/org/cloudname/StrategyAnyTest.java
deleted file mode 100644
index d6f56f54..00000000
--- a/cn/src/test/java/org/cloudname/StrategyAnyTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.cloudname;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.lessThan;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-
-/**
- * Unit tests for StrategyAny.
- * @author dybdahl
- */
-public class StrategyAnyTest {
- private List<Endpoint> endpoints;
-
- /**
- * Adds a list endpoints with even instance number to the endpoints list.
- */
- @Before
- public void setup() {
- endpoints = new ArrayList<Endpoint>();
- // Only even instance numbers.
- for (int i = 0; i < 100; i+= 2) {
- endpoints.add(new Endpoint(Coordinate.parse(String.valueOf(i) + ".foo.bar.zot"),
- "rest-api",
- "somehost",
- 4711,
- "http",
- null));
- }
- }
-
- /**
- * Different clients should have different lists.
- */
- @Test
- public void testDifferentLists() {
- StrategyAny strategyAny = new StrategyAny();
-
- List<Endpoint> sortedResult = strategyAny.order(new ArrayList<Endpoint>(endpoints));
-
- // Try with up tp 150 clients, if they all have the same first element, something is wrong.
- // In each iteration there is 1/50 probability for this. For 150 runs, the probability for
- // false negative is 1,42724769 × 10^-255 (e.g. zero).
- for (int z = 0; z < 150; z++) {
- StrategyAny strategyAny2 = new StrategyAny();
- List<Endpoint> sortedResult2 = strategyAny2.order(new ArrayList<Endpoint>(endpoints));
- if (sortedResult.get(0).getCoordinate().getInstance() !=
- sortedResult2.get(0).getCoordinate().getInstance()) {
- return;
- }
- }
- assertTrue(false);
- }
-
- /**
- * Test that insertion does only create a new first element now and then.
- */
- @Test
- public void testInsertions() {
- StrategyAny strategyAny = new StrategyAny();
-
- List<Endpoint> sortedResult = strategyAny.order(new ArrayList<Endpoint>(endpoints));
- int newFrontEndpoint = 0;
- for (int c = 1; c < 30; c +=2) {
- int headInstance = sortedResult.get(0).getCoordinate().getInstance();
- sortedResult.add(new Endpoint(Coordinate.parse(String.valueOf(c) + ".foo.bar.zot"),
- "rest-api",
- "somehost",
- 4711,
- "http",
- null));
- sortedResult = strategyAny.order(sortedResult);
- if (headInstance != sortedResult.get(0).getCoordinate().getInstance()) {
- ++newFrontEndpoint;
- }
- }
- // For each insertion it a probability of less than 1/50 that front element is changed. The probability
- // that more than 10 front elements are changed should be close to zero.
- assertThat(newFrontEndpoint, is(lessThan(10)));
- }
-}
diff --git a/cn/src/test/java/org/cloudname/zk/ZkCloudnameTest.java b/cn/src/test/java/org/cloudname/zk/ZkCloudnameTest.java
deleted file mode 100644
index 5bccc3f6..00000000
--- a/cn/src/test/java/org/cloudname/zk/ZkCloudnameTest.java
+++ /dev/null
@@ -1,324 +0,0 @@
-package org.cloudname.zk;
-
-import org.cloudname.*;
-
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooKeeper;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.*;
-
-import org.junit.*;
-import org.junit.rules.TemporaryFolder;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertTrue;
-
-import org.cloudname.testtools.Net;
-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper;
-
-import java.io.File;
-import java.util.logging.Logger;
-
-/**
- * Unit test for the ZkCloudname class.
- *
- * @author borud, dybdahl
- */
-public class ZkCloudnameTest {
- private static final Logger LOG = Logger.getLogger(ZkCloudnameTest.class.getName());
-
- private ZooKeeper zk;
- private int zkport;
-
- @Rule public TemporaryFolder temp = new TemporaryFolder();
-
- /**
- * Set up an embedded ZooKeeper instance backed by a temporary
- * directory. The setup procedure also allocates a port that is
- * free for the ZooKeeper server so that you should be able to run
- * multiple instances of this test.
- */
- @Before
- public void setup() throws Exception {
- File rootDir = temp.newFolder("zk-test");
- zkport = Net.getFreePort();
-
- LOG.info("EmbeddedZooKeeper rootDir=" + rootDir.getCanonicalPath() + ", port=" + zkport
- );
-
- // Set up and initialize the embedded ZooKeeper
- final EmbeddedZooKeeper ezk = new EmbeddedZooKeeper(rootDir, zkport);
- ezk.init();
-
- // Set up a zookeeper client that we can use for inspection
- final CountDownLatch connectedLatch = new CountDownLatch(1);
-
- zk = new ZooKeeper("localhost:" + zkport, 1000, new Watcher() {
- public void process(WatchedEvent event) {
- if (event.getState() == Event.KeeperState.SyncConnected) {
- connectedLatch.countDown();
- }
- }
- });
- connectedLatch.await();
-
- LOG.info("ZooKeeper port is " + zkport);
- }
-
- @After
- public void tearDown() throws Exception {
- zk.close();
- }
-
- /**
- * Tests that the time-out mechanism on connecting to ZooKeeper works.
- */
- @Test
- public void testTimeout() throws IOException, InterruptedException {
- int deadPort = Net.getFreePort();
- try {
- new ZkCloudname.Builder().setConnectString("localhost:" + deadPort).build()
- .connectWithTimeout(1000, TimeUnit.NANOSECONDS);
- fail("Expected time-out exception.");
- } catch (CloudnameException e) {
- // Expected.
- }
- }
-
- /**
- * A relatively simple voyage through a typical lifecycle.
- */
- @Test
- public void testSimple() throws Exception {
- final Coordinate c = Coordinate.parse("1.service.user.cell");
- final ZkCloudname cn = makeLocalZkCloudname();
-
- assertFalse(pathExists("/cn/cell/user/service/1"));
- cn.createCoordinate(c);
-
- // Coordinate should exist, but no status node
- assertTrue(pathExists("/cn/cell/user/service/1"));
- assertTrue(pathExists("/cn/cell/user/service/1/config"));
- assertFalse(pathExists("/cn/cell/user/service/1/status"));
-
- // Claiming the coordinate creates the status node
- final ServiceHandle handle = cn.claim(c);
- assertTrue(handle.waitForCoordinateOkSeconds(3));
- assertNotNull(handle);
- final CountDownLatch latch = new CountDownLatch(1);
- handle.registerCoordinateListener(new CoordinateListener() {
-
- @Override
- public void onCoordinateEvent(Event event, String message) {
- if (event == Event.COORDINATE_OK) {
- latch.countDown();
- }
- }
- });
- assertTrue(latch.await(2, TimeUnit.SECONDS));
-
- final CountDownLatch configLatch1 = new CountDownLatch(1);
- final CountDownLatch configLatch2 = new CountDownLatch(2);
- final StringBuilder buffer = new StringBuilder();
- handle.registerConfigListener(new ConfigListener() {
- @Override
- public void onConfigEvent(Event event, String data) {
- buffer.append(data);
- configLatch1.countDown();
- configLatch2.countDown();
- }
- });
- assertTrue(configLatch1.await(5, TimeUnit.SECONDS));
- assertEquals(buffer.toString(), "");
- zk.setData("/cn/cell/user/service/1/config", "hello".getBytes(), -1);
- assertTrue(configLatch2.await(5, TimeUnit.SECONDS));
- assertEquals(buffer.toString(), "hello");
-
- assertTrue(pathExists("/cn/cell/user/service/1/status"));
-
- List<String> nodes = new ArrayList<String>();
- cn.listRecursively(nodes);
- assertEquals(2, nodes.size());
- assertEquals(nodes.get(0), "/cn/cell/user/service/1/config");
- assertEquals(nodes.get(1), "/cn/cell/user/service/1/status");
-
- // Try to set the status to something else
- String msg = "Hamster getting quite eager now";
- handle.setStatus(new ServiceStatus(ServiceState.STARTING,msg));
- ServiceStatus status = cn.getStatus(c);
- assertEquals(msg, status.getMessage());
- assertSame(ServiceState.STARTING, status.getState());
-
- // Publish two endpoints
- handle.putEndpoint(new Endpoint(c, "foo", "localhost", 1234, "http", null));
- handle.putEndpoint(new Endpoint(c, "bar", "localhost", 1235, "http", null));
-
- handle.setStatus(new ServiceStatus(ServiceState.RUNNING, msg));
-
- // Remove one of them
- handle.removeEndpoint("bar");
-
- List<Endpoint> endpointList = cn.getResolver().resolve("bar.1.service.user.cell");
- assertEquals(0, endpointList.size());
-
- endpointList = cn.getResolver().resolve("foo.1.service.user.cell");
- assertEquals(1, endpointList.size());
- Endpoint endpointFoo = endpointList.get(0);
-
- String fooData = endpointFoo.getName();
- assertEquals("foo", fooData);
- assertEquals("foo", endpointFoo.getName());
- assertEquals("localhost", endpointFoo.getHost());
- assertEquals(1234, endpointFoo.getPort());
- assertEquals("http", endpointFoo.getProtocol());
- assertNull(endpointFoo.getEndpointData());
-
- // Close handle just invalidates handle
- handle.close();
-
- // These nodes are ephemeral and will be cleaned out when we
- // call cn.releaseClaim(), but calling handle.releaseClaim() explicitly
- // cleans out the ephemeral nodes.
- assertFalse(pathExists("/cn/cell/user/service/1/status"));
-
- // Closing Cloudname instance disconnects the zk client
- // connection and thus should kill all ephemeral nodes.
- cn.close();
-
- // But the coordinate and its persistent subnodes should
- assertTrue(pathExists("/cn/cell/user/service/1"));
- assertFalse(pathExists("/cn/cell/user/service/1/endpoints"));
- assertTrue(pathExists("/cn/cell/user/service/1/config"));
- }
-
- /**
- * Claim non-existing coordinate
- */
- @Test
- public void testCoordinateNotFound() throws CloudnameException, InterruptedException {
- final Coordinate c = Coordinate.parse("3.service.user.cell");
- final Cloudname cn = makeLocalZkCloudname();
-
- final ExecutorService executor = Executors.newCachedThreadPool();
- final Callable<Object> task = new Callable<Object>() {
- public Object call() throws InterruptedException {
- return cn.claim(c);
- }
- };
- final Future<Object> future = executor.submit(task);
- try {
- future.get(300, TimeUnit.MILLISECONDS);
- } catch (TimeoutException ex) {
- // handle the timeout
- LOG.info("Got time out, nice!");
- } catch (InterruptedException e) {
- fail("Interrupted");
- } catch (ExecutionException e) {
- fail("Some error " + e.getMessage());
- // handle other exceptions
- } finally {
- future.cancel(true);
- }
- }
-
- /**
- * Try to claim coordinate twice
- */
- @Test
- public void testDoubleClaim() throws CloudnameException, InterruptedException {
- final Coordinate c = Coordinate.parse("2.service.user.cell");
- final CountDownLatch okCounter = new CountDownLatch(1);
- final CountDownLatch failCounter = new CountDownLatch(1);
-
- final CoordinateListener listener = new CoordinateListener() {
- @Override
- public void onCoordinateEvent(Event event, String message) {
- switch (event) {
- case COORDINATE_OK:
- okCounter.countDown();
- break;
- case NOT_OWNER:
- failCounter.countDown();
- default: //Any other Event is unexpected.
- assert(false);
- break;
- }
- }
- };
- final Cloudname cn;
- try {
- cn = makeLocalZkCloudname();
- } catch (CloudnameException e) {
- fail("connecting to localhost failed.");
- return;
- }
-
- try {
- cn.createCoordinate(c);
- } catch (CoordinateExistsException e) {
- fail("should not happen.");
- }
- final ServiceHandle handle1 = cn.claim(c);
- assert(handle1.waitForCoordinateOkSeconds(4));
- handle1.registerCoordinateListener(listener);
- ServiceHandle handle2 = cn.claim(c);
- assertFalse(handle2.waitForCoordinateOkSeconds(1));
- handle2.registerCoordinateListener(listener);
- assert(okCounter.await(4, TimeUnit.SECONDS));
- assert(failCounter.await(2, TimeUnit.SECONDS));
- }
-
-
- @Test
- public void testDestroyBasic() throws Exception {
- final Coordinate c = Coordinate.parse("1.service.user.cell");
- final Cloudname cn = makeLocalZkCloudname();
- cn.createCoordinate(c);
- assertTrue(pathExists("/cn/cell/user/service/1/config"));
- cn.destroyCoordinate(c);
- assertFalse(pathExists("/cn/cell/user/service"));
- assertTrue(pathExists("/cn/cell/user"));
- }
-
- @Test
- public void testDestroyTwoInstances() throws Exception {
- final Coordinate c1 = Coordinate.parse("1.service.user.cell");
- final Coordinate c2 = Coordinate.parse("2.service.user.cell");
- final Cloudname cn = makeLocalZkCloudname();
- cn.createCoordinate(c1);
- cn.createCoordinate(c2);
- assertTrue(pathExists("/cn/cell/user/service/1/config"));
- assertTrue(pathExists("/cn/cell/user/service/2/config"));
- cn.destroyCoordinate(c1);
- assertFalse(pathExists("/cn/cell/user/service/1"));
- assertTrue(pathExists("/cn/cell/user/service/2/config"));
- }
-
- @Test
- public void testDestroyClaimed() throws Exception {
- final Coordinate c = Coordinate.parse("1.service.user.cell");
- final Cloudname cn = makeLocalZkCloudname();
- cn.createCoordinate(c);
- ServiceHandle handle = cn.claim(c);
- handle.waitForCoordinateOkSeconds(1);
- try {
- cn.destroyCoordinate(c);
- fail("Expected exception to happen");
- } catch (CoordinateException e) {
- }
- }
-
- private boolean pathExists(String path) throws Exception {
- return (null != zk.exists(path, false));
- }
-
- /**
- * Makes a local ZkCloudname instance with the port given by zkPort.
- */
- private ZkCloudname makeLocalZkCloudname() throws CloudnameException {
- return new ZkCloudname.Builder().setConnectString("localhost:" + zkport).build().connect();
- }
-}
diff --git a/cn/src/test/java/org/cloudname/zk/ZkCoordinatePathTest.java b/cn/src/test/java/org/cloudname/zk/ZkCoordinatePathTest.java
deleted file mode 100644
index 9e9f6dcf..00000000
--- a/cn/src/test/java/org/cloudname/zk/ZkCoordinatePathTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.cloudname.zk;
-
-import org.cloudname.Coordinate;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * Unit tests for class ZkCoordinatePathTest.
- * @author dybdahl
- */
-public class ZkCoordinatePathTest {
- @Test
- public void testSimple() throws Exception {
- final Coordinate coordinate = new Coordinate(
- 42 /*instance*/, "service", "user", "cell", false /*validate*/);
- assertEquals("/cn/cell/user/service/42/config",
- ZkCoordinatePath.getConfigPath(coordinate, null));
- assertEquals("/cn/cell/user/service/42/config/name",
- ZkCoordinatePath.getConfigPath(coordinate, "name"));
- assertEquals("/cn/cell/user/service/42",
- ZkCoordinatePath.getCoordinateRoot(coordinate));
- assertEquals("/cn/cell/user/service/42/status",
- ZkCoordinatePath.getStatusPath(coordinate));
- assertEquals("/cn/cell/user/service",
- ZkCoordinatePath.coordinateWithoutInstanceAsPath(
- "cell", "user", "service"));
- assertEquals("/cn/cell/user/service/42/status",
- ZkCoordinatePath.getStatusPath("cell", "user", "service", 42));
- }
-}
diff --git a/cn/src/test/java/org/cloudname/zk/ZkResolverTest.java b/cn/src/test/java/org/cloudname/zk/ZkResolverTest.java
deleted file mode 100644
index 3dd868f6..00000000
--- a/cn/src/test/java/org/cloudname/zk/ZkResolverTest.java
+++ /dev/null
@@ -1,134 +0,0 @@
-package org.cloudname.zk;
-
-import org.cloudname.*;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import static org.junit.Assert.*;
-
-
-/**
- * This class contains the unit tests for the ZkResolver class.
- *
- * TODO(borud): add tests for when the input is a coordinate.
- *
- * @author borud
- */
-public class ZkResolverTest {
- private Resolver resolver;
-
- @Rule
- public TemporaryFolder temp = new TemporaryFolder();
-
- /**
- * Set up an embedded ZooKeeper instance backed by a temporary
- * directory. The setup procedure also allocates a port that is
- * free for the ZooKeeper server so that you should be able to run
- * multiple instances of this test.
- */
- @Before
- public void setup() throws Exception {
- resolver = new ZkResolver.Builder()
- .addStrategy(new StrategyAll())
- .addStrategy(new StrategyAny())
- .build(new ZkObjectHandler(null).getClient());
- }
-
- // Valid endpoints.
- public static final String[] validEndpointPatterns = new String[] {
- "http.1.service.user.cell",
- "foo-bar.3245.service.user.cell",
- "foo_bar.3245.service.user.cell",
- };
-
- // Valid strategy.
- public static final String[] validStrategyPatterns = new String[] {
- "any.service.user.cell",
- "all.service.user.cell",
- "somestrategy.service.user.cell",
- };
-
- // Valid endpoint strategy.
- public static final String[] validEndpointStrategyPatterns = new String[] {
- "http.any.service.user.cell",
- "thrift.all.service.user.cell",
- "some-endpoint.somestrategy.service.user.cell",
- };
-
- @Test(expected=IllegalArgumentException.class)
- public void testRegisterSameListenerTwice() throws Exception {
- Resolver.ResolverListener resolverListener = new Resolver.ResolverListener() {
- @Override
- public void endpointEvent(Event event, Endpoint endpoint) {
-
- }
- };
- resolver.addResolverListener("foo.all.service.user.cell", resolverListener);
- resolver.addResolverListener("bar.all.service.user.cell", resolverListener);
- }
-
- @Test
- public void testEndpointPatterns() throws Exception {
- // Test input that should match
- for (String s : validEndpointPatterns) {
- assertTrue("Didn't match '" + s + "'",
- ZkResolver.endpointPattern.matcher(s).matches());
- }
-
- // Test input that should not match
- for (String s : validStrategyPatterns) {
- assertFalse("Matched '" + s + "'",
- ZkResolver.endpointPattern.matcher(s).matches());
- }
-
- // Test input that should not match
- for (String s : validEndpointStrategyPatterns) {
- assertFalse("Matched '" + s + "'",
- ZkResolver.endpointPattern.matcher(s).matches());
- }
- }
-
- @Test
- public void testStrategyPatterns() throws Exception {
- // Test input that should match
- for (String s : validStrategyPatterns) {
- assertTrue("Didn't match '" + s + "'",
- ZkResolver.strategyPattern.matcher(s).matches());
- }
-
- // Test input that should not match
- for (String s : validEndpointPatterns) {
- assertFalse("Matched '" + s + "'",
- ZkResolver.strategyPattern.matcher(s).matches());
- }
- // Test input that should not match
- for (String s : validEndpointStrategyPatterns) {
- assertFalse("Matched '" + s + "'",
- ZkResolver.endpointPattern.matcher(s).matches());
- }
- }
-
- @Test
- public void testEndpointStrategyPatterns() throws Exception {
- // Test input that should match
- for (String s : validEndpointStrategyPatterns) {
- assertTrue("Didn't match '" + s + "'",
- ZkResolver.endpointStrategyPattern.matcher(s).matches());
- }
-
- // Test input that should not match
- for (String s : validStrategyPatterns) {
- assertFalse("Matched '" + s + "'",
- ZkResolver.endpointStrategyPattern.matcher(s).matches());
- }
-
-
- // Test input that should not match
- for (String s : validEndpointPatterns) {
- assertFalse("Matched '" + s + "'",
- ZkResolver.endpointStrategyPattern.matcher(s).matches());
- }
- }
-}
\ No newline at end of file
diff --git a/flags/src/test/java/org/cloudname/flags/FlagsTest.java b/flags/src/test/java/org/cloudname/flags/FlagsTest.java
index 7db55632..4cc3aa75 100644
--- a/flags/src/test/java/org/cloudname/flags/FlagsTest.java
+++ b/flags/src/test/java/org/cloudname/flags/FlagsTest.java
@@ -4,7 +4,7 @@
import java.io.File;
import java.io.FileOutputStream;
import javax.annotation.PostConstruct;
-import junit.framework.Assert;
+import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
diff --git a/pom.xml b/pom.xml
index bde06f53..19b35348 100644
--- a/pom.xml
+++ b/pom.xml
@@ -39,7 +39,7 @@
<cn.curator.version>2.9.0</cn.curator.version>
<cn.jackson.version>2.1.1</cn.jackson.version>
<cn.junit.version>4.11</cn.junit.version>
- <cn.netty.version>4.0.32.Final</cn.netty.version>
+ <cn.netty.version>3.7.0.Final</cn.netty.version>
<cn.protobuf.version>2.6.1</cn.protobuf.version>
<cn.jline.version>0.9.94</cn.jline.version>
<cn.jmxri.version>1.2.1</cn.jmxri.version>
@@ -47,13 +47,14 @@
<cn.jbcrypt.version>0.3m</cn.jbcrypt.version>
<cn.joda-time.version>2.1</cn.joda-time.version>
<cn.a3.jersey.version>1.16</cn.a3.jersey.version>
- <integrationSourceDirectory>src/integrationtest</integrationSourceDirectory>
- <integrationOutputDirectory>target/integrationtest-classes</integrationOutputDirectory>
</properties>
<modules>
<module>a3</module>
- <module>cn</module>
+ <module>cn-core</module>
+ <module>cn-service</module>
+ <module>cn-memory</module>
+ <module>cn-zookeeper</module>
<module>testtools</module>
<module>log</module>
<module>timber</module>
@@ -82,15 +83,6 @@
<useFile>false</useFile>
</configuration>
</plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- <version>2.5.2</version>
- <configuration>
- <format>xml</format>
- <aggregate>true</aggregate>
- </configuration>
- </plugin>
</plugins>
</build>
@@ -108,7 +100,13 @@
<!-- Internal dependencies -->
<dependency>
<groupId>org.cloudname</groupId>
- <artifactId>cn</artifactId>
+ <artifactId>cn-core</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cn-memory</artifactId>
<version>${project.version}</version>
</dependency>
@@ -139,7 +137,7 @@
<!-- Netty -->
<dependency>
<groupId>io.netty</groupId>
- <artifactId>netty-all</artifactId>
+ <artifactId>netty</artifactId>
<version>${cn.netty.version}</version>
</dependency>
@@ -157,34 +155,6 @@
<version>${cn.protobuf.version}</version>
</dependency>
- <!-- ZooKeeper -->
- <dependency>
- <groupId>org.apache.zookeeper</groupId>
- <artifactId>zookeeper</artifactId>
- <version>${cn.zookeeper.version}</version>
- <exclusions>
- <exclusion>
- <groupId>com.sun.jmx</groupId>
- <artifactId>jmxri</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.sun.jdmk</groupId>
- <artifactId>jmxtools</artifactId>
- </exclusion>
- <exclusion>
- <groupId>javax.jms</groupId>
- <artifactId>jms</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <!-- Apache Curator -->
- <dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-framework</artifactId>
- <version>${cn.curator.version}</version>
- </dependency>
-
<!-- Jackson JSON library -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
@@ -254,135 +224,4 @@
</dependencies>
</dependencyManagement>
- <profiles>
- <profile>
- <activation>
- <file><exists>src/integrationtest</exists></file>
- </activation>
- <id>it</id>
- <build>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.10</version>
- <configuration>
- <test>**/*.java</test>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>create-directory</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>run</goal>
- </goals>
- <configuration>
- <tasks>
- <echo message="Creating Directory ${integrationOutputDirectory}" />
- <mkdir dir="${integrationOutputDirectory}" />
- </tasks>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <version>1.5</version>
- <executions>
- <execution>
- <id>add-test-sources</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>add-test-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>${integrationSourceDirectory}/java</source>
- </sources>
- </configuration>
- </execution>
- <execution>
- <id>add-test-resources</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>add-test-resource</goal>
- </goals>
- <configuration>
- <resources>
- <resource>
- <directory>${integrationSourceDirectory}/java</directory>
- <targetPath>${integrationOutputDirectory}</targetPath>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>add-empty-directory</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>add-test-resource</goal>
- </goals>
- <configuration>
- <resources>
- <resource>
- <directory>${integrationSourceDirectory}/java</directory>
- <targetPath>${integrationOutputDirectory}</targetPath>
- <excludes>
- <exclude>**/*</exclude>
- </excludes>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.3.2</version>
- <executions>
- <execution>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>testCompile</goal>
- </goals>
- <configuration>
- <compilerArguments>
- <d>${basedir}/${integrationOutputDirectory}</d>
- </compilerArguments>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-failsafe-plugin</artifactId>
- <version>2.8</version>
- <configuration>
- <testClassesDirectory>${integrationOutputDirectory}</testClassesDirectory>
- <reportsDirectory>${integrationOutputDirectory}/failsafe-reports</reportsDirectory>
- <test>**/*.java</test>
- <additionalClasspathElements>
- <additionalClasspathElement>${integrationSourceDirectory}/resources</additionalClasspathElement>
- </additionalClasspathElements>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>integration-test</goal>
- <goal>verify</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- </profile>
- </profiles>
</project>
diff --git a/testtools/pom.xml b/testtools/pom.xml
index c50037e1..817a9a87 100644
--- a/testtools/pom.xml
+++ b/testtools/pom.xml
@@ -15,17 +15,16 @@
<url>https://github.com/Cloudname/cloudname</url>
<dependencies>
- <dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-test</artifactId>
- <version>${cn.curator.version}</version>
- </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <scope>test</scope>
+ <scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.cloudname</groupId>
+ <artifactId>cn-core</artifactId>
+ </dependency>
</dependencies>
</project>
diff --git a/testtools/src/main/java/org/cloudname/testtools/backend/CoreBackendTest.java b/testtools/src/main/java/org/cloudname/testtools/backend/CoreBackendTest.java
new file mode 100644
index 00000000..3525b4d6
--- /dev/null
+++ b/testtools/src/main/java/org/cloudname/testtools/backend/CoreBackendTest.java
@@ -0,0 +1,635 @@
+package org.cloudname.testtools.backend;
+
+import org.cloudname.core.CloudnameBackend;
+import org.cloudname.core.CloudnamePath;
+import org.cloudname.core.LeaseHandle;
+import org.cloudname.core.LeaseListener;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * Core backend tests. This ensures the backend implementation works as expected on the most
+ * basic level. Override this class in your backend implementation to test it.
+ *
+ * @author [email protected]
+ */
+public abstract class CoreBackendTest {
+ private final CloudnamePath serviceA = new CloudnamePath(
+ new String[] { "local", "test", "service-a" });
+ private final CloudnamePath serviceB = new CloudnamePath(
+ new String[] { "local", "test", "service-b" });
+
+ private final Random random = new Random();
+
+ /**
+ * Max data propagation time (in ms) for notifications from the backend. Override if your
+ * backend implementation is slow. 5 ms is a lot of time though so do it carefully.
+ */
+ protected int getBackendPropagationTime() {
+ return 5;
+ }
+ /**
+ * Ensure multiple clients can connect and that leases get an unique path for each client.
+ */
+ @Test
+ public void temporaryLeaseCreation() throws Exception {
+ try (final CloudnameBackend backend = getBackend()) {
+ final String data = Long.toHexString(random.nextLong());
+ final LeaseHandle lease = backend.createTemporaryLease(serviceA, data);
+ assertThat("Expected lease to be not null", lease, is(notNullValue()));
+
+ assertTrue("Expected lease path to be a subpath of the supplied lease (" + serviceA
+ + ") but it is " + lease.getLeasePath(),
+ serviceA.isSubpathOf(lease.getLeasePath()));
+
+ assertThat("The temporary lease data can be read",
+ backend.readTemporaryLeaseData(lease.getLeasePath()), is(data));
+
+ final String newData = Long.toHexString(random.nextLong());
+ assertThat("Expected to be able to write lease data but didn't",
+ lease.writeLeaseData(newData), is(true));
+
+ assertThat("Expected to be able to read data back but didn't",
+ backend.readTemporaryLeaseData(lease.getLeasePath()), is(newData));
+ lease.close();
+
+ assertThat("Expect the lease path to be null", lease.getLeasePath(), is(nullValue()));
+
+ assertFalse("Did not expect to be able to write lease data for a closed lease",
+ lease.writeLeaseData(Long.toHexString(random.nextLong())));
+ assertThat("The temporary lease data can not be read",
+ backend.readTemporaryLeaseData(lease.getLeasePath()), is(nullValue()));
+
+
+ final int numberOfLeases = 50;
+
+ final Set<String> leasePaths = new HashSet<>();
+ for (int i = 0; i < numberOfLeases; i++) {
+ final String randomData = Long.toHexString(random.nextLong());
+ final LeaseHandle handle = backend.createTemporaryLease(serviceB, randomData);
+ leasePaths.add(handle.getLeasePath().join(':'));
+ handle.close();
+ }
+
+ assertThat("Expected " + numberOfLeases + " unique paths but it was " + leasePaths.size(),
+ leasePaths.size(), is(numberOfLeases));
+ }
+ }
+
+ /**
+ * A very simple single-threaded notification. Make sure this works before implementing
+ * the multiple notifications elsewhere in this test.
+ */
+ @Test
+ public void simpleTemporaryNotification() throws Exception {
+
+ try (final CloudnameBackend backend = getBackend()) {
+
+ final CloudnamePath rootPath = new CloudnamePath(new String[]{"simple"});
+ final CountDownLatch createCounter = new CountDownLatch(1);
+ final CountDownLatch removeCounter = new CountDownLatch(1);
+ final CountDownLatch dataCounter = new CountDownLatch(1);
+
+ final String firstData = "first data";
+ final String lastData = "last data";
+ final LeaseListener listener = new LeaseListener() {
+ @Override
+ public void leaseCreated(CloudnamePath path, String data) {
+ createCounter.countDown();
+ if (data.equals(lastData)) {
+ dataCounter.countDown();
+ }
+ }
+
+ @Override
+ public void leaseRemoved(CloudnamePath path) {
+ removeCounter.countDown();
+ }
+
+ @Override
+ public void dataChanged(CloudnamePath path, String data) {
+ dataCounter.countDown();
+ }
+ };
+ backend.addTemporaryLeaseListener(rootPath, listener);
+ final LeaseHandle handle = backend.createTemporaryLease(rootPath, firstData);
+ assertThat(handle, is(notNullValue()));
+ Thread.sleep(getBackendPropagationTime());
+
+ handle.writeLeaseData(lastData);
+ Thread.sleep(getBackendPropagationTime());
+
+ handle.close();
+
+ assertTrue("Expected create notification but didn't get one",
+ createCounter.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS));
+ assertTrue("Expected remove notification but didn't get one",
+ removeCounter.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS));
+ assertTrue("Expected data notification but didn't get one",
+ dataCounter.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS));
+
+ backend.removeTemporaryLeaseListener(listener);
+ }
+ }
+
+ /**
+ * Ensure permanent leases can be created and that they can't be overwritten by clients using
+ * the library.
+ */
+ @Test
+ public void permanentLeaseCreation() throws Exception {
+ final CloudnamePath leasePath = new CloudnamePath(new String[]{"some", "path"});
+ final String dataString = "some data string";
+ final String newDataString = "new data string";
+
+
+ try (final CloudnameBackend backend = getBackend()) {
+ backend.removePermanentLease(leasePath);
+
+ assertThat("Permanent lease can be created",
+ backend.createPermanantLease(leasePath, dataString), is(true));
+
+ assertThat("Permanent lease data can be read",
+ backend.readPermanentLeaseData(leasePath), is(dataString));
+
+ assertThat("Permanent lease can't be created twice",
+ backend.createPermanantLease(leasePath, dataString), is(false));
+
+ assertThat("Permanent lease can be updated",
+ backend.writePermanentLeaseData(leasePath, newDataString), is(true));
+
+ assertThat("Permanent lease data can be read after update",
+ backend.readPermanentLeaseData(leasePath), is(newDataString));
+ }
+
+ try (final CloudnameBackend backend = getBackend()) {
+ assertThat("Permanent lease data can be read from another backend",
+ backend.readPermanentLeaseData(leasePath), is(newDataString));
+ assertThat("Permanent lease can be removed",
+ backend.removePermanentLease(leasePath), is(true));
+ assertThat("Lease can't be removed twice",
+ backend.removePermanentLease(leasePath), is(false));
+ assertThat("Lease data can't be read from deleted lease",
+ backend.readPermanentLeaseData(leasePath), is(nullValue()));
+ }
+ }
+
+ /**
+ * Ensure clients are notified of changes
+ */
+ @Test
+ public void multipleTemporaryNotifications() throws Exception {
+ try (final CloudnameBackend backend = getBackend()) {
+ final CloudnamePath rootPath = new CloudnamePath(new String[]{"root", "lease"});
+ final String clientData = "client data here";
+
+ final LeaseHandle lease = backend.createTemporaryLease(rootPath, clientData);
+ assertThat("Handle to lease is returned", lease, is(notNullValue()));
+ assertThat("Lease is a child of the root lease",
+ rootPath.isSubpathOf(lease.getLeasePath()), is(true));
+
+ int numListeners = 10;
+ final int numUpdates = 10;
+
+ // Add some listeners to the temporary lease. Each should be notified once on
+ // creation, once on removal and once every time the data is updated
+ final CountDownLatch createNotifications = new CountDownLatch(numListeners);
+ final CountDownLatch dataNotifications = new CountDownLatch(numListeners * numUpdates);
+ final CountDownLatch removeNotifications = new CountDownLatch(numListeners);
+
+ final List<LeaseListener> listeners = new ArrayList<>();
+ for (int i = 0; i < numListeners; i++) {
+ final LeaseListener listener = new LeaseListener() {
+ private AtomicInteger lastData = new AtomicInteger(-1);
+
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ createNotifications.countDown();
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ removeNotifications.countDown();
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ assertThat(lastData.incrementAndGet(), is(Integer.parseInt(data)));
+ dataNotifications.countDown();
+ }
+ };
+ listeners.add(listener);
+ backend.addTemporaryLeaseListener(rootPath, listener);
+ }
+
+ // Change the data a few times. Every change should be propagated to the listeners
+ // in the same order they have changed
+ for (int i = 0; i < numUpdates; i++) {
+ lease.writeLeaseData(Integer.toString(i));
+ Thread.sleep(getBackendPropagationTime());
+ }
+
+ // Remove the lease. Removal notifications will be sent to the clients
+
+ assertThat("All create notifications are received but " + createNotifications.getCount()
+ + " remains out of " + numListeners,
+ createNotifications.await(getBackendPropagationTime(), TimeUnit.MICROSECONDS), is(true));
+
+ assertThat("All data notifications are received but " + dataNotifications.getCount()
+ + " remains out of " + (numListeners * numUpdates),
+ dataNotifications.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS), is(true));
+
+ lease.close();
+ assertThat("All remove notifications are received but " + removeNotifications.getCount()
+ + " remains out of " + numListeners,
+ removeNotifications.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS), is(true));
+
+ // Remove the listeners
+ for (final LeaseListener listener : listeners) {
+ lease.close();
+ backend.removeTemporaryLeaseListener(listener);
+ }
+ }
+ }
+
+ /**
+ * Test a simple peer to peer scheme; all clients grabbing a lease and listening on other
+ * clients.
+ */
+ @Test
+ public void multipleServicesWithMultipleClients() throws Exception {
+ try (final CloudnameBackend backend = getBackend()) {
+
+ final CloudnamePath rootLease = new CloudnamePath(new String[]{"multi", "multi"});
+ final int numberOfClients = 5;
+
+ // All clients will be notified of all other clients (including themselves)
+ final CountDownLatch createNotifications
+ = new CountDownLatch(numberOfClients * numberOfClients);
+ // All clients will write one change each
+ final CountDownLatch dataNotifications = new CountDownLatch(numberOfClients);
+ // There will be 99 + 98 + 97 + 96 ... 1 notifications, in all n (n + 1) / 2
+ // remove notifications
+ final int n = numberOfClients - 1;
+ final CountDownLatch removeNotifications = new CountDownLatch(n * (n + 1) / 2);
+
+ final Runnable clientProcess = new Runnable() {
+ @Override
+ public void run() {
+ final String myData = Long.toHexString(random.nextLong());
+ final LeaseHandle handle = backend.createTemporaryLease(rootLease, myData);
+ assertThat("Got a valid handle back", handle, is(notNullValue()));
+ backend.addTemporaryLeaseListener(rootLease, new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ assertThat("Notification belongs to root path",
+ rootLease.isSubpathOf(path), is(true));
+ createNotifications.countDown();
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ removeNotifications.countDown();
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ dataNotifications.countDown();
+ }
+ });
+
+ try {
+ assertThat(createNotifications.await(
+ getBackendPropagationTime(), TimeUnit.MILLISECONDS),
+ is(true));
+ } catch (InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+
+ // Change the data for my own lease, wait for it to propagate
+ assertThat(handle.writeLeaseData(Long.toHexString(random.nextLong())),
+ is(true));
+ try {
+ Thread.sleep(getBackendPropagationTime());
+ } catch (final InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+
+ try {
+ assertThat(dataNotifications.await(
+ getBackendPropagationTime(), TimeUnit.MILLISECONDS),
+ is(true));
+ } catch (InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+
+ // ..and close my lease
+ try {
+ handle.close();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+ };
+
+ final Executor executor = Executors.newCachedThreadPool();
+ for (int i = 0; i < numberOfClients; i++) {
+ executor.execute(clientProcess);
+ }
+
+ removeNotifications.await(getBackendPropagationTime(), TimeUnit.SECONDS);
+ }
+ }
+
+
+ /**
+ * Just make sure unknown listeners doesn't throw exceptions
+ */
+ @Test
+ public void removeInvalidListener() throws Exception {
+ try (final CloudnameBackend backend = getBackend()) {
+ final LeaseListener unknownnListener = new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ }
+ };
+ backend.removeTemporaryLeaseListener(unknownnListener);
+ }
+ }
+
+
+ /**
+ * Create a whole set of different listener pairs that runs in parallel. They won't
+ * receive notifications from any other lease - listener pairs.
+ */
+ @Test
+ public void multipleIndependentListeners() throws Exception {
+ try (final CloudnameBackend backend = getBackend()) {
+ final int leasePairs = 10;
+
+ class LeaseWorker {
+ private final String id;
+ private final CloudnamePath rootPath;
+ private final LeaseListener listener;
+ private final AtomicInteger createNotifications = new AtomicInteger(0);
+ private final AtomicInteger dataNotifications = new AtomicInteger(0);
+ private LeaseHandle handle;
+
+ public LeaseWorker(final String id) {
+ this.id = id;
+ rootPath = new CloudnamePath(new String[]{"pair", id});
+ listener = new LeaseListener() {
+
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ createNotifications.incrementAndGet();
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ dataNotifications.incrementAndGet();
+ }
+ };
+ }
+
+ public void createLease() {
+ backend.addTemporaryLeaseListener(rootPath, listener);
+ try {
+ Thread.sleep(getBackendPropagationTime());
+ } catch (final InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+ handle = backend.createTemporaryLease(rootPath, id);
+ }
+
+ public void writeData() {
+ handle.writeLeaseData(id);
+ }
+
+ public void checkNumberOfNotifications() {
+ // There will be two notifications; one for this lease, one for the other
+ assertThat("Expected 2 create notifications", createNotifications.get(), is(2));
+ // There will be two notifications; one for this lease, one for the other
+ assertThat("Expected 2 data notifications", dataNotifications.get(), is(2));
+ }
+
+ public void closeLease() {
+ try {
+ handle.close();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+ }
+
+ final List<LeaseWorker> workers = new ArrayList<>();
+
+ for (int i = 0; i < leasePairs; i++) {
+ final String id = Long.toHexString(random.nextLong());
+ final LeaseWorker leaseWorker1 = new LeaseWorker(id);
+ leaseWorker1.createLease();
+ workers.add(leaseWorker1);
+ final LeaseWorker leaseWorker2 = new LeaseWorker(id);
+ leaseWorker2.createLease();
+ workers.add(leaseWorker2);
+ }
+
+ for (final LeaseWorker worker : workers) {
+ worker.writeData();
+ }
+ Thread.sleep(getBackendPropagationTime());
+ for (final LeaseWorker worker : workers) {
+ worker.checkNumberOfNotifications();
+ }
+ for (final LeaseWorker worker : workers) {
+ worker.closeLease();
+ }
+ }
+ }
+
+ /**
+ * Ensure permanent leases distribute notifications as well
+ */
+ @Test
+ public void permanentLeaseNotifications() throws Exception {
+ final CloudnamePath rootLease = new CloudnamePath(new String[] { "permanent", "vacation" });
+ final String leaseData = "the aero smiths";
+ final String newLeaseData = "popcultural reference";
+
+ try (final CloudnameBackend backend = getBackend()) {
+ backend.removePermanentLease(rootLease);
+ assertThat("Can create permanent node",
+ backend.createPermanantLease(rootLease, leaseData), is(true));
+ }
+
+ final AtomicInteger numberOfNotifications = new AtomicInteger(0);
+ final CountDownLatch createLatch = new CountDownLatch(1);
+ final CountDownLatch removeLatch = new CountDownLatch(1);
+ final CountDownLatch dataLatch = new CountDownLatch(1);
+
+ final LeaseListener listener = new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ assertThat(path, is(equalTo(rootLease)));
+ assertThat(data, is(equalTo(leaseData)));
+ numberOfNotifications.incrementAndGet();
+ createLatch.countDown();
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ assertThat(path, is(equalTo(rootLease)));
+ numberOfNotifications.incrementAndGet();
+ removeLatch.countDown();
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ assertThat(path, is(equalTo(rootLease)));
+ assertThat(data, is(equalTo(newLeaseData)));
+ numberOfNotifications.incrementAndGet();
+ dataLatch.countDown();
+ }
+ };
+
+ try (final CloudnameBackend backend = getBackend()) {
+
+ assertThat("Lease still exists",
+ backend.readPermanentLeaseData(rootLease), is(leaseData));
+
+ // Add the lease back
+ backend.addPermanentLeaseListener(rootLease, listener);
+
+ assertThat("New data can be written",
+ backend.writePermanentLeaseData(rootLease, newLeaseData), is(true));
+
+ // Write new data
+ assertThat("Lease can be removed", backend.removePermanentLease(rootLease), is(true));
+
+ assertTrue(createLatch.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS));
+ assertTrue(dataLatch.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS));
+ assertTrue(removeLatch.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS));
+ // This includes one created, one data, one close
+ assertThat("One notifications is expected but only got "
+ + numberOfNotifications.get(), numberOfNotifications.get(), is(3));
+
+ backend.removePermanentLeaseListener(listener);
+ // just to be sure - this won't upset anything
+ backend.removePermanentLeaseListener(listener);
+ }
+ }
+
+
+ /**
+ * Set up two listeners listening to different permanent leases. There should be no crosstalk
+ * between the listeners.
+ */
+ @Test
+ public void multiplePermanentListeners() throws Exception {
+ final CloudnamePath permanentA = new CloudnamePath(new String[] { "primary" });
+ final CloudnamePath permanentB = new CloudnamePath(new String[] { "secondary" });
+ final CloudnamePath permanentC = new CloudnamePath(
+ new String[] { "tertiary", "permanent", "lease" });
+
+ try (final CloudnameBackend backend = getBackend()) {
+ backend.addPermanentLeaseListener(permanentA, new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ assertThat(path, is(equalTo(permanentA)));
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ assertThat(path, is(equalTo(permanentA)));
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ assertThat(path, is(equalTo(permanentA)));
+ }
+ });
+
+ backend.addPermanentLeaseListener(permanentB, new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ assertThat(path, is(equalTo(permanentB)));
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ assertThat(path, is(equalTo(permanentB)));
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ assertThat(path, is(equalTo(permanentB)));
+ }
+ });
+
+ backend.addPermanentLeaseListener(permanentC, new LeaseListener() {
+ @Override
+ public void leaseCreated(final CloudnamePath path, final String data) {
+ fail("Did not expect any leases to be created at " + permanentC);
+ }
+
+ @Override
+ public void leaseRemoved(final CloudnamePath path) {
+ fail("Did not expect any leases to be created at " + permanentC);
+ }
+
+ @Override
+ public void dataChanged(final CloudnamePath path, final String data) {
+ fail("Did not expect any leases to be created at " + permanentC);
+ }
+ });
+
+ backend.createPermanantLease(permanentA, "Some data that belongs to A");
+ backend.createPermanantLease(permanentB, "Some data that belongs to B");
+
+ // Some might say this is a dirty trick but permanent and temporary leases should not
+ // interfere with eachother.
+ final LeaseHandle handle = backend.createTemporaryLease(
+ permanentC, "Some data that belongs to C");
+ assertThat(handle, is(notNullValue()));
+ handle.writeLeaseData("Some other data that belongs to C");
+ try {
+ handle.close();
+ } catch (Exception ex) {
+ fail(ex.getMessage());
+ }
+ }
+ }
+
+ protected abstract CloudnameBackend getBackend();
+}
diff --git a/testtools/src/main/java/org/cloudname/testtools/network/ClientThread.java b/testtools/src/main/java/org/cloudname/testtools/network/ClientThread.java
deleted file mode 100644
index cadbb470..00000000
--- a/testtools/src/main/java/org/cloudname/testtools/network/ClientThread.java
+++ /dev/null
@@ -1,121 +0,0 @@
-package org.cloudname.testtools.network;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Socket;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * ClientThread forwards communication for one pair of sockets.
- * TODO(borud): this class lacks unit tests
- *
- * @author dybdahl
- */
-class ClientThread {
- private final static Logger log = Logger.getLogger(ClientThread.class.getName());
-
- private Socket serverSocket = null;
- private Socket clientSocket = null;
- private Object threadMonitor = new Object();
-
-
- /**
- * Constructor
- * @param clientSocket socket crated for incomming call
- * @param hostName destination host name
- * @param hostPort destination host port
- */
- public ClientThread(final Socket clientSocket, final String hostName, final int hostPort) {
- this.clientSocket = clientSocket;
- Runnable myRunnable = new Runnable() {
- @Override
- public void run() {
- final InputStream clientIn, serverIn;
- final OutputStream clientOut, serverOut;
-
- try {
- synchronized (threadMonitor) {
- serverSocket = new Socket(hostName, hostPort);
- }
- clientIn = clientSocket.getInputStream();
- clientOut = clientSocket.getOutputStream();
- serverIn = serverSocket.getInputStream();
- serverOut = serverSocket.getOutputStream();
- } catch (IOException ioe) {
- log.severe("Portforwarder: Can not connect to " + hostName + ":" + hostPort);
- try {
- if (serverSocket != null) {
- serverSocket.close();
- }
- } catch (IOException e) {
- log.severe("Could not close server socket");
- }
- return;
- }
- synchronized (threadMonitor) {
- startForwarderThread(clientIn, serverOut);
- startForwarderThread(serverIn, clientOut);
- }
- }
- };
- Thread fireAndForget = new Thread(myRunnable);
- fireAndForget.start();
- }
-
- /**
- * Closes sockets, which again closes the running threads.
- */
- public void close() {
- synchronized (threadMonitor) {
- try {
- if (serverSocket != null) {
- serverSocket.close();
- serverSocket = null;
- }
- } catch (Exception e) {
- log.log(Level.SEVERE, "Error while closing server socket", e);
- }
- try {
- if (clientSocket != null) {
- clientSocket.close();
- clientSocket = null;
- }
- } catch (Exception e) {
- log.log(Level.SEVERE, "Error while closing client socket", e);
- }
- }
- }
-
- private Thread startForwarderThread(
- final InputStream inputStream, final OutputStream outputStream) {
- final int BUFFER_SIZE = 4096;
- Runnable myRunnable = new Runnable() {
- @Override
- public void run() {
- byte[] buffer = new byte[BUFFER_SIZE];
- try {
- while (true) {
- int bytesRead = inputStream.read(buffer);
-
- if (bytesRead == -1)
- // End of stream is reached --> exit
- break;
-
- outputStream.write(buffer, 0, bytesRead);
- outputStream.flush();
- }
- } catch (IOException e) {
- // Read/write failed --> connection is broken
- log.log(Level.SEVERE, "Forwarding in loop died.");
- }
- // Notify parent thread that the connection is broken
- close();
- }
- };
- Thread forwarder = new Thread(myRunnable);
- forwarder.start();
- return forwarder;
- }
-}
diff --git a/testtools/src/main/java/org/cloudname/testtools/network/PortForwarder.java b/testtools/src/main/java/org/cloudname/testtools/network/PortForwarder.java
deleted file mode 100644
index 35c2ec5e..00000000
--- a/testtools/src/main/java/org/cloudname/testtools/network/PortForwarder.java
+++ /dev/null
@@ -1,145 +0,0 @@
-package org.cloudname.testtools.network;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Simple class for setting up port forwarding in unit tests. This
- * enables killing the connection.
- *
- * TODO(stalehd): Remove? Replace with TestCluster class. Makes for better integration tests.
- * TODO(borud): this class lacks unit tests
- *
- * @author dybdahl
- */
-public class PortForwarder {
- private final static Logger log = Logger.getLogger(PortForwarder.class.getName());
-
- private final int myPort;
- private final AtomicBoolean isAlive = new AtomicBoolean(true);
- private ServerSocket serverSocket = null;
-
- private Thread portThread;
- private final Object threadMonitor = new Object();
-
- private final List<ClientThread> clientThreadList = new ArrayList<ClientThread>();
- private final AtomicBoolean pause = new AtomicBoolean(false);
-
- private final String hostName;
- private final int hostPort;
-
- /**
- * Constructor for port-forwarder. Does stat the forwarder.
- * @param myPort client port
- * @param hostName name of host to forward to.
- * @param hostPort port of host to forward to.
- * @throws IOException if unable to open server socket
- */
- public PortForwarder(final int myPort, final String hostName, final int hostPort) throws IOException {
- this.myPort = myPort;
- this.hostName = hostName;
- this.hostPort = hostPort;
- log.info("Starting port forwarder " + myPort + " -> " + hostPort);
- startServerSocketThread();
- }
-
- private void startServerSocketThread()
- throws IOException {
- openServerSocket();
- Runnable myRunnable = new Runnable() {
- @Override
- public void run() {
- log.info("Forwarder running");
- while (isAlive.get() && !pause.get()) {
- try {
- final Socket clientSocket = serverSocket.accept();
- synchronized (threadMonitor) {
- if (isAlive.get() && !pause.get()) {
- clientThreadList.add(new ClientThread(clientSocket, hostName, hostPort));
- } else {
- clientSocket.close();
- }
- }
- } catch (IOException e) {
- log.log(Level.SEVERE, "Got exception in forwarder", e);
- // Keep going, maybe later connections will succeed.
- }
- }
- log.info("Forwarder stopped");
- }
- };
- portThread = new Thread(myRunnable);
- // Make this a daemon thread, so it won't keep the VM running at shutdown.
- portThread.setDaemon(true);
- portThread.start();
- }
-
- private void openServerSocket() throws IOException {
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.bind(new InetSocketAddress("localhost", myPort));
- }
-
- /**
- * Forces client to loose connection and refuses to create new (closing attempts to connect).
- * @throws IOException
- * @throws InterruptedException
- */
- public void pause() throws IOException, InterruptedException {
- final Thread currentServerThread;
- synchronized (threadMonitor) {
- if (!pause.compareAndSet(false, true)) {
- return;
- }
- for (ClientThread clientThread: clientThreadList) {
- clientThread.close();
-
- }
- clientThreadList.clear();
- serverSocket.close();
- /*
- * Make a copy of the server socket thread, so we can wait for it
- * to complete outside any monitor.
- */
- currentServerThread = portThread;
- }
- currentServerThread.join();
- }
-
- /**
- * Lets client start connecting again.
- * @throws IOException
- */
- public void unpause() throws IOException {
- synchronized (threadMonitor) {
- if (pause.compareAndSet(true, false)) {
- startServerSocketThread();
- }
- }
- }
-
- /**
- * Shuts down the forwarder.
- */
- public void close() {
- isAlive.set(false);
- try {
- pause();
- } catch (final IOException e) {
- // Ignore this
- log.severe("Could not close server socket.");
- } catch (InterruptedException e) {
- log.severe("Interrupted while waiting for server thread to finish.");
- // Reassert interrupt.
- Thread.currentThread().interrupt();
- }
- }
-}
-
diff --git a/testtools/src/main/java/org/cloudname/testtools/zookeeper/EmbeddedZooKeeper.java b/testtools/src/main/java/org/cloudname/testtools/zookeeper/EmbeddedZooKeeper.java
deleted file mode 100644
index c081434f..00000000
--- a/testtools/src/main/java/org/cloudname/testtools/zookeeper/EmbeddedZooKeeper.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.cloudname.testtools.zookeeper;
-
-import org.apache.curator.test.TestingServer;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * Utility class to fire up an embedded ZooKeeper server in the
- * current JVM for testing purposes.
- *
- * @author borud
- * @author stalehd
- */
-public final class EmbeddedZooKeeper {
- private final File rootDir;
- private final int port;
- private TestingServer server;
-
- /**
- * @param rootDir the root directory of where the ZooKeeper
- * instance will keep its files. If null, a temporary directory is created
- * @param port the port where ZooKeeper will listen for client
- * connections.
- */
- public EmbeddedZooKeeper(File rootDir, int port) {
- this.rootDir = rootDir;
- this.port = port;
- }
-
- private void delDir(File path) throws IOException {
- for(File f : path.listFiles())
- {
- if(f.isDirectory()) {
- delDir(f);
- } else {
- if (!f.delete() && f.exists()) {
- throw new IOException("Failed to delete file " + f);
- }
- }
- }
- if (!path.delete() && path.exists()) {
- throw new IOException("Failed to delete directory " + path);
- }
-
- }
-
- /**
- * Delete all data owned by the ZooKeeper instance.
- * @throws IOException if some file could not be deleted
- */
- public void del() throws IOException {
- File path = new File(rootDir, "data");
- delDir(path);
- }
-
-
- /**
- * Set up the ZooKeeper instance.
- */
- public void init() throws Exception {
- this.server = new TestingServer(this.port, this.rootDir);
- // Create the data directory
- File dataDir = new File(rootDir, "data");
- dataDir.mkdir();
-
- this.server.start();
- }
-
- /**
- * Shut the ZooKeeper instance down.
- * @throws IOException if shutdown encountered I/O errors
- */
- public void shutdown() throws IOException {
- this.server.stop();
- del();
- }
-
- /**
- * Get the client connection string for the ZooKeeper instance.
- *
- * @return a String containing a comma-separated list of host:port
- * entries for use as a parameter to the ZooKeeper client class.
- */
- public String getClientConnectionString() {
- return "127.0.0.1:" + port;
- }
-}
diff --git a/timber/pom.xml b/timber/pom.xml
index 3ed79030..6dca5385 100644
--- a/timber/pom.xml
+++ b/timber/pom.xml
@@ -62,7 +62,7 @@
<dependency>
<groupId>io.netty</groupId>
- <artifactId>netty-all</artifactId>
+ <artifactId>netty</artifactId>
</dependency>
<dependency>
@@ -75,11 +75,13 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
+
<dependency>
<groupId>org.cloudname</groupId>
<artifactId>idgen</artifactId>
<scope>test</scope>
</dependency>
+
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
|
f0bb45ae2869920cfa29a46ea7704b1a6c69ab37
|
spring-framework
|
included qualifier value in debug log for each- transaction (SPR-6811)--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
index 86c6b5281244..01dbf705e6d7 100644
--- a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
+++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2008 the original author or authors.
+ * Copyright 2002-2010 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.
@@ -103,7 +103,7 @@ public TransactionAttribute getTransactionAttribute(Method method, Class targetC
}
else {
if (logger.isDebugEnabled()) {
- logger.debug("Adding transactional method [" + method.getName() + "] with attribute [" + txAtt + "]");
+ logger.debug("Adding transactional method '" + method.getName() + "' with attribute: " + txAtt);
}
this.attributeCache.put(cacheKey, txAtt);
}
diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java
index d9a9cf515e7b..3bae2f663d05 100644
--- a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java
+++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2010 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.
@@ -94,4 +94,17 @@ public boolean rollbackOn(Throwable ex) {
return (ex instanceof RuntimeException || ex instanceof Error);
}
+
+ /**
+ * Return an identifying description for this transaction attribute.
+ * <p>Available to subclasses, for inclusion in their <code>toString()</code> result.
+ */
+ protected final StringBuilder getAttributeDescription() {
+ StringBuilder result = getDefinitionDescription();
+ if (this.qualifier != null) {
+ result.append("; '").append(this.qualifier).append("'");
+ }
+ return result;
+ }
+
}
diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java
index 87a5da020413..d67368843f36 100644
--- a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java
+++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2008 the original author or authors.
+ * Copyright 2002-2010 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.
@@ -30,7 +30,7 @@
* both positive and negative. If no rules are relevant to the exception, it
* behaves like DefaultTransactionAttribute (rolling back on runtime exceptions).
*
- * <p>TransactionAttributeEditor creates objects of this class.
+ * <p>{@link TransactionAttributeEditor} creates objects of this class.
*
* @author Rod Johnson
* @author Juergen Hoeller
@@ -159,7 +159,7 @@ public boolean rollbackOn(Throwable ex) {
@Override
public String toString() {
- StringBuilder result = getDefinitionDescription();
+ StringBuilder result = getAttributeDescription();
if (this.rollbackRules != null) {
for (RollbackRuleAttribute rule : this.rollbackRules) {
String sign = (rule instanceof NoRollbackRuleAttribute ? PREFIX_COMMIT_RULE : PREFIX_ROLLBACK_RULE);
diff --git a/org.springframework.transaction/src/test/resources/log4j.xml b/org.springframework.transaction/src/test/resources/log4j.xml
index 767b96d6206d..e684ff2b7e90 100644
--- a/org.springframework.transaction/src/test/resources/log4j.xml
+++ b/org.springframework.transaction/src/test/resources/log4j.xml
@@ -15,7 +15,7 @@
<level value="warn" />
</logger>
- <logger name="org.springframework.binding">
+ <logger name="org.springframework.transaction">
<level value="debug" />
</logger>
|
149822837837249fd39fc6a09ac5263c0c02fa44
|
arquillian$arquillian-graphene
|
ARQGRA-235: Automatically infer ID locator from field name annotated
just by @FindBy - support added
* It is configurable with standard way of using GrapheneConfiguration
(arquillian.xml).
* Default element locating strategy is ID_OR_NAME.
* The property for this feature is set either as a lowerCase or upperCase How.values()
* Throwing exception when there is empty findby removed
* Tests for this feature added
* Tests which asserted failure when empty @FindBy usage were removed
* Code for support of @FindBys commented in Annotations.java
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java
new file mode 100644
index 000000000..8043282c7
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java
@@ -0,0 +1,125 @@
+package org.jboss.arquillian.graphene.enricher;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.net.URL;
+import java.util.List;
+
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.enricher.findby.FindBy;
+import org.jboss.arquillian.graphene.spi.annotations.Page;
+import org.jboss.arquillian.junit.Arquillian;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.ui.Select;
+
+/**
+ * @author <a href="mailto:[email protected]">Juraj Huska</a>
+ */
+@RunWith(Arquillian.class)
+public class TestInitializeEmptyFindBy {
+
+ @Drone
+ private WebDriver browser;
+
+ @FindBy
+ private WebElement divWebElement;
+
+ @FindBy
+ private SpanFragment spanFragment;
+
+ @FindBy
+ private Select selectElement;
+
+ @FindBy
+ private WebElement nameOfInputElement;
+
+ @Page
+ private PageObject pageObjectWithSeleniumFindBys;
+
+ @Before
+ public void loadPage() {
+ URL page = this.getClass().getClassLoader()
+ .getResource("org/jboss/arquillian/graphene/ftest/enricher/empty-findby.html");
+ browser.get(page.toString());
+ }
+
+ @Test
+ public void testWebElementById() {
+ checkWebElementById(divWebElement);
+ }
+
+ @Test
+ public void testWebElementByName() {
+ checkWebElementByName(nameOfInputElement);
+ }
+
+ @Test
+ public void testPageFragmentById() {
+ checkPageFragmentById(spanFragment);
+ }
+
+ @Test
+ public void testSelectById() {
+ checkSelectById(selectElement);
+ }
+
+ @Test
+ public void testSeleniumFindBy() {
+ checkPageFragmentById(pageObjectWithSeleniumFindBys.spanFragment);
+ checkSelectById(pageObjectWithSeleniumFindBys.selectElement);
+ checkWebElementById(pageObjectWithSeleniumFindBys.divWebElement);
+ checkWebElementByName(pageObjectWithSeleniumFindBys.nameOfInputElement);
+ }
+
+ public class PageObject {
+ @org.openqa.selenium.support.FindBy
+ public WebElement divWebElement;
+
+ @org.openqa.selenium.support.FindBy
+ public SpanFragment spanFragment;
+
+ @org.openqa.selenium.support.FindBy
+ public Select selectElement;
+
+ @org.openqa.selenium.support.FindBy
+ public WebElement nameOfInputElement;
+ }
+
+ public class SpanFragment {
+
+ @FindBy(tagName = "span")
+ private List<WebElement> span;
+
+ public List<WebElement> getSpan() {
+ return span;
+ }
+ }
+
+ private void checkWebElementById(WebElement element) {
+ assertNotNull(element);
+ assertEquals("WebElement content", element.getText());
+ }
+
+ private void checkWebElementByName(WebElement element) {
+ assertNotNull(element);
+ String expected = "Test";
+ element.sendKeys(expected);
+ assertEquals(expected, element.getAttribute("value"));
+ }
+
+ private void checkPageFragmentById(SpanFragment fragment) {
+ assertNotNull(fragment);
+ assertEquals("1", fragment.getSpan().get(0).getText());
+ }
+
+ private void checkSelectById(Select select) {
+ assertNotNull(select);
+ select.selectByIndex(1);
+ assertEquals("two", select.getFirstSelectedOption().getText());
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java
index fc6213f64..6795a8ac5 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java
@@ -25,6 +25,7 @@
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.drone.configuration.ConfigurationMapper;
import org.jboss.arquillian.drone.spi.DroneConfiguration;
+import org.jboss.arquillian.graphene.enricher.findby.How;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
@@ -41,6 +42,12 @@ public class GrapheneConfiguration implements DroneConfiguration<GrapheneConfigu
private long javascriptInstallationLimit = 5;
+ private String defaultElementLocatingStrategy = How.ID_OR_NAME.toString().toLowerCase();
+
+ public String getDefaultElementLocatingStrategy() {
+ return defaultElementLocatingStrategy;
+ }
+
public long getWaitAjaxInterval() {
return waitAjaxInterval;
}
@@ -77,6 +84,17 @@ public void validate() {
if (javascriptInstallationLimit <= 0) {
throw new IllegalArgumentException("The javascriptInstallationLimut property has to a positive number.");
}
+ try {
+ How.valueOf(defaultElementLocatingStrategy.toUpperCase());
+ } catch (IllegalArgumentException ex) {
+ String values = "";
+ for(How value : How.values()) {
+ values += value.toString().toLowerCase() + ", ";
+ }
+ throw new IllegalArgumentException(
+ "The defaultElementLocatingStrategy property has to be one of the: " + values + " and was: "
+ + ((defaultElementLocatingStrategy.length() != 0) ? defaultElementLocatingStrategy : "empty"), ex);
+ }
}
@Override
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
index 37eb5437e..b2bd344bf 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
@@ -73,7 +73,8 @@ public void enrich(SearchContext searchContext, Object target) {
protected final boolean isPageFragmentClass(Class<?> clazz) {
// check whether it isn't interface or final class
- if (Modifier.isInterface(clazz.getModifiers()) || Modifier.isFinal(clazz.getModifiers()) || Modifier.isAbstract(clazz.getModifiers())) {
+ if (Modifier.isInterface(clazz.getModifiers()) || Modifier.isFinal(clazz.getModifiers())
+ || Modifier.isAbstract(clazz.getModifiers())) {
return false;
}
@@ -82,7 +83,7 @@ protected final boolean isPageFragmentClass(Class<?> clazz) {
// check whether there is an empty constructor
if (outerClass == null || Modifier.isStatic(clazz.getModifiers())) {
return ReflectionHelper.hasConstructor(clazz);
- // check whether there is an empty constructor with outer class
+ // check whether there is an empty constructor with outer class
} else {
return ReflectionHelper.hasConstructor(clazz, outerClass);
}
@@ -110,8 +111,8 @@ public static final <T> T createPageFragment(Class<T> clazz, WebElement root) {
List<Field> roots = ReflectionHelper.getFieldsWithAnnotation(clazz, Root.class);
if (roots.size() > 1) {
throw new PageFragmentInitializationException("The Page Fragment " + NEW_LINE + pageFragment.getClass()
- + NEW_LINE + " can not have more than one field annotated with Root annotation!"
- + "Your fields with @Root annotation: " + roots + NEW_LINE);
+ + NEW_LINE + " can not have more than one field annotated with Root annotation!"
+ + "Your fields with @Root annotation: " + roots + NEW_LINE);
}
if (roots.size() == 1) {
setValue(roots.get(0), pageFragment, root);
@@ -120,39 +121,29 @@ public static final <T> T createPageFragment(Class<T> clazz, WebElement root) {
return pageFragment;
} catch (NoSuchMethodException ex) {
throw new PageFragmentInitializationException(" Check whether declared Page Fragment has no argument constructor!",
- ex);
+ ex);
} catch (IllegalAccessException ex) {
throw new PageFragmentInitializationException(
- " Check whether declared Page Fragment has public no argument constructor!", ex);
+ " Check whether declared Page Fragment has public no argument constructor!", ex);
} catch (InstantiationException ex) {
throw new PageFragmentInitializationException(
- " Check whether you did not declare Page Fragment with abstract type!", ex);
+ " Check whether you did not declare Page Fragment with abstract type!", ex);
} catch (Exception ex) {
throw new PageFragmentInitializationException(ex);
}
}
protected final void setupPageFragmentList(SearchContext searchContext, Object target, Field field)
- throws ClassNotFoundException {
+ throws ClassNotFoundException {
+ //the by retrieved in this way is never null, by default it is ByIdOrName using field name
By rootBy = FindByUtilities.getCorrectBy(field);
- if (rootBy == null) {
- throw new PageFragmentInitializationException("Your declaration of Page Fragment in test "
- + field.getDeclaringClass().getName() + " is annotated with @FindBy without any "
- + "parameters, in other words without reference to root of the particular Page Fragment on the page!"
- + NEW_LINE);
- }
List<?> pageFragments = createPageFragmentList(getListType(field), searchContext, rootBy);
setValue(field, target, pageFragments);
}
protected final void setupPageFragment(SearchContext searchContext, Object target, Field field) {
+ //the by retrieved in this way is never null, by default it is ByIdOrName using field name
By rootBy = FindByUtilities.getCorrectBy(field);
- if (rootBy == null) {
- throw new PageFragmentInitializationException("Your declaration of Page Fragment in test "
- + field.getDeclaringClass().getName() + " is annotated with @FindBy without any "
- + "parameters, in other words without reference to root of the particular Page Fragment on the page!"
- + NEW_LINE);
- }
WebElement root = WebElementUtils.findElementLazily(rootBy, searchContext);
Object pageFragment = createPageFragment(field.getType(), root);
setValue(field, target, pageFragment);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
index a90464731..2413b4173 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
@@ -24,7 +24,6 @@
import java.lang.reflect.Field;
import java.util.List;
-import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
@@ -41,24 +40,15 @@ public void enrich(SearchContext searchContext, Object target) {
try {
List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target);
for (Field field : fields) {
+ //by should never by null, by default it is ByIdOrName using field name
By by = FindByUtilities.getCorrectBy(field);
- String message = "Your @FindBy annotation over field " + NEW_LINE + field.getName() + NEW_LINE
- + " declared in: " + NEW_LINE + field.getDeclaringClass().getName() + NEW_LINE
- + " is annotated with empty @FindBy annotation, in other words it "
- + "should contain parameter which will define the strategy for referencing that element.";
// WebElement
if (field.getType().isAssignableFrom(WebElement.class)) {
- if (by == null) {
- throw new GrapheneTestEnricherException(message);
- }
WebElement element = WebElementUtils.findElementLazily(by, searchContext);
setValue(field, target, element);
// List<WebElement>
} else if (field.getType().isAssignableFrom(List.class)
&& getListType(field).isAssignableFrom(WebElement.class)) {
- if (by == null) {
- throw new GrapheneTestEnricherException(message);
- }
List<WebElement> elements = WebElementUtils.findElementsLazily(by, searchContext);
setValue(field, target, elements);
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java
index 004ad6043..693425441 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java
@@ -23,20 +23,29 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
import org.jboss.arquillian.graphene.intercept.InterceptorBuilder;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.openqa.selenium.By;
+import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.internal.WrapsElement;
+import org.openqa.selenium.support.ByIdOrName;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
*/
public final class WebElementUtils {
+ private final static Logger LOGGER = Logger.getLogger(WebElementUtils.class.getName());
+ private final static String EMPTY_FIND_BY_WARNING = " Be aware of the fact that fields anotated with empty "
+ + "@FindBy were located by default strategy, which is ByIdOrName with field name as locator! ";
+
private WebElementUtils() {
}
@@ -53,7 +62,7 @@ public static WebElement findElement(final By by, final SearchContext searchCont
public Object getTarget() {
if (element == null) {
if (searchContext instanceof GrapheneProxyInstance) {
- return ((SearchContext)((GrapheneProxyInstance) searchContext).unwrap()).findElement(by);
+ return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElement(by);
} else {
return searchContext.findElement(by);
}
@@ -79,7 +88,12 @@ public static WebElement findElementLazily(final By by, final SearchContext sear
return findElement(new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
- return searchContext.findElement(by);
+ try {
+ return searchContext.findElement(by);
+ } catch (NoSuchElementException ex) {
+ throw new NoSuchElementException((by instanceof ByIdOrName ? EMPTY_FIND_BY_WARNING : "") + ex.getMessage(),
+ ex);
+ }
}
});
}
@@ -90,6 +104,9 @@ public static List<WebElement> findElementsLazily(final By by, final SearchConte
public Object getTarget() {
List<WebElement> result = new ArrayList<WebElement>();
List<WebElement> elements = searchContext.findElements(by);
+ if ((by instanceof ByIdOrName) && (elements.size() == 0)) {
+ LOGGER.log(Level.WARNING, EMPTY_FIND_BY_WARNING);
+ }
for (int i = 0; i < elements.size(); i++) {
result.add(findElementLazily(by, searchContext, i));
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java
index bbaec73dd..276fd6638 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java
@@ -14,35 +14,18 @@
limitations under the License.
*/
/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-/**
- * Utility class originally copied from WebDriver. The differences are:
+ * <p>
+ * Utility class originally copied from WebDriver. It main purpose is to retrieve correct
+ * <code>By</code> instance according to the field on which <code>@Find</code> annotation is.</p>
+ *
+ * <p>The differences are:
* <ul>
* <li>this class supports also Graphene <code>@FindBy</code> with JQuery locators support</li>
- * <li></li>
+ * <li>it is able to return default locating strategy according to the <code>GrapheneConfiguration</code></li>
* </ul>
- *
+ * </p>
*
- * @author <a href="mailto:[email protected]">Juraj Huska</a>
+ * <p>Altered by <a href="mailto:[email protected]">Juraj Huska</a></p>.
*/
package org.jboss.arquillian.graphene.enricher.findby;
@@ -50,6 +33,7 @@
import java.util.HashSet;
import java.util.Set;
+import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ByIdOrName;
import org.openqa.selenium.support.CacheLookup;
@@ -69,12 +53,12 @@ public boolean isLookupCached() {
}
public By buildBy() {
- //un-comment once FindBys is supported
// assertValidAnnotations();
By ans = null;
- //FindBys is not supported for now, that is why it is commented
+ ans = checkAndProcessEmptyFindBy();
+
// FindBys findBys = field.getAnnotation(FindBys.class);
// if (ans == null && findBys != null) {
// ans = buildByFromFindBys(findBys);
@@ -102,8 +86,35 @@ public By buildBy() {
return ans;
}
+ private By checkAndProcessEmptyFindBy() {
+ By result = null;
+
+ FindBy findBy = field.getAnnotation(FindBy.class);
+ if (findBy != null) {
+ int numberOfValues = assertValidFindBy(findBy);
+ if (numberOfValues == 0) {
+ result = buildByFromDefault();
+ }
+ }
+
+ org.jboss.arquillian.graphene.enricher.findby.FindBy grapheneFindBy = field
+ .getAnnotation(org.jboss.arquillian.graphene.enricher.findby.FindBy.class);
+ if (grapheneFindBy != null) {
+ int numberOfValues = assertValidFindBy(grapheneFindBy);
+ if (numberOfValues == 0) {
+ result = buildByFromDefault();
+ }
+ }
+
+ return result;
+ }
+
protected By buildByFromDefault() {
- return new ByIdOrName(field.getName());
+ org.jboss.arquillian.graphene.enricher.findby.How how = org.jboss.arquillian.graphene.enricher.findby.How
+ .valueOf(GrapheneConfigurationContext.getProxy().getDefaultElementLocatingStrategy().toUpperCase());
+
+ String using = field.getName();
+ return getByFromGrapheneHow(how, using);
}
// protected By buildByFromFindBys(FindBys findBys) {
@@ -182,7 +193,10 @@ protected By buildByFromLongFindBy(FindBy findBy) {
protected By buildByFromLongFindBy(org.jboss.arquillian.graphene.enricher.findby.FindBy findBy) {
org.jboss.arquillian.graphene.enricher.findby.How how = findBy.how();
String using = findBy.using();
+ return getByFromGrapheneHow(how, using);
+ }
+ private By getByFromGrapheneHow(org.jboss.arquillian.graphene.enricher.findby.How how, String using) {
switch (how) {
case CLASS_NAME:
return By.className(using);
@@ -210,7 +224,7 @@ protected By buildByFromLongFindBy(org.jboss.arquillian.graphene.enricher.findby
case XPATH:
return By.xpath(using);
-
+
case JQUERY:
return ByJQuery.jquerySelector(using);
@@ -274,7 +288,7 @@ protected By buildByFromShortFindBy(org.jboss.arquillian.graphene.enricher.findb
if (!"".equals(findBy.xpath()))
return By.xpath(findBy.xpath());
-
+
if (!"".equals(findBy.jquery()))
return ByJQuery.jquerySelector((findBy.jquery()));
@@ -282,17 +296,17 @@ protected By buildByFromShortFindBy(org.jboss.arquillian.graphene.enricher.findb
return null;
}
-// private void assertValidAnnotations() {
-// FindBys findBys = field.getAnnotation(FindBys.class);
-// FindBy findBy = field.getAnnotation(FindBy.class);
-// org.jboss.arquillian.graphene.enricher.findby.FindBy grapheneFindBy = field
-// .getAnnotation(org.jboss.arquillian.graphene.enricher.findby.FindBy.class);
-//
-// if (findBys != null && (findBy != null || grapheneFindBy != null)) {
-// throw new IllegalArgumentException("If you use a '@FindBys' annotation, "
-// + "you must not also use a '@FindBy' annotation");
-// }
-// }
+ // private void assertValidAnnotations() {
+ // FindBys findBys = field.getAnnotation(FindBys.class);
+ // FindBy findBy = field.getAnnotation(FindBy.class);
+ // org.jboss.arquillian.graphene.enricher.findby.FindBy grapheneFindBy = field
+ // .getAnnotation(org.jboss.arquillian.graphene.enricher.findby.FindBy.class);
+ //
+ // if (findBys != null && (findBy != null || grapheneFindBy != null)) {
+ // throw new IllegalArgumentException("If you use a '@FindBys' annotation, "
+ // + "you must not also use a '@FindBy' annotation");
+ // }
+ // }
// private void assertValidFindBys(FindBys findBys) {
// for (FindBy findBy : findBys.value()) {
@@ -300,7 +314,7 @@ protected By buildByFromShortFindBy(org.jboss.arquillian.graphene.enricher.findb
// }
// }
- private void assertValidFindBy(FindBy findBy) {
+ private int assertValidFindBy(FindBy findBy) {
if (findBy.how() != null) {
if (findBy.using() == null) {
throw new IllegalArgumentException("If you set the 'how' property, you must also set 'using'");
@@ -333,9 +347,11 @@ private void assertValidFindBy(FindBy findBy) {
String.format("You must specify at most one location strategy. Number found: %d (%s)", finders.size(),
finders.toString()));
}
+
+ return finders.size();
}
- private void assertValidFindBy(org.jboss.arquillian.graphene.enricher.findby.FindBy findBy) {
+ private int assertValidFindBy(org.jboss.arquillian.graphene.enricher.findby.FindBy findBy) {
if (findBy.how() != null) {
if (findBy.using() == null) {
throw new IllegalArgumentException("If you set the 'how' property, you must also set 'using'");
@@ -370,5 +386,7 @@ private void assertValidFindBy(org.jboss.arquillian.graphene.enricher.findby.Fin
String.format("You must specify at most one location strategy. Number found: %d (%s)", finders.size(),
finders.toString()));
}
+
+ return finders.size();
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentEnricher.java
index 36a02cacb..7b6eb798e 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentEnricher.java
@@ -42,11 +42,6 @@ public void testMissingNoArgConstructor() {
Assert.assertNull(target.pageFragment);
}
- @Test
- public void testNoReference() {
- thrown.expect(PageFragmentInitializationException.class);
- getGrapheneEnricher().enrich(new NoReferenceTest());
- }
@Test
public void testTooManyRoots() {
@@ -66,11 +61,6 @@ public static class NoArgConstructorTest {
private WrongPageFragmentMissingNoArgConstructor pageFragment;
}
- public static class NoReferenceTest {
- @FindBy
- private AbstractPageFragmentStub pageFragment;
- }
-
public static class TooManyRootsTest {
@SuppressWarnings("unused")
@FindBy(id = "foo")
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java
index df92b30bd..43f08645c 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java
@@ -48,12 +48,6 @@ public class TestWebElementEnricher extends AbstractGrapheneEnricherTest {
@Mock
WebElement element;
- @Test
- public void testEmptyFindBy() {
- thrown.expect(GrapheneTestEnricherException.class);
- getGrapheneEnricher().enrich(new EmptyFindByTest());
- }
-
@Test
public void generated_webelement_implements_WrapsElement_interface() {
TestPage page = new TestPage();
@@ -69,13 +63,6 @@ public void generated_webelement_implements_WrapsElement_interface() {
assertEquals(element, wrappedElement);
}
- public static class EmptyFindByTest {
-
- @SuppressWarnings("unused")
- @FindBy
- private WebElement wrongWebElem;
- }
-
public static class TestPage {
@FindBy(id = "id")
private WebElement element;
|
3c558b6bd33611c366f4299f9e639288a7e47d38
|
tapiji
|
adds missing folders in plug-in
|
c
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java
new file mode 100644
index 00000000..59f26760
--- /dev/null
+++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java
@@ -0,0 +1,50 @@
+package org.eclipselabs.tapiji.tools.core.ui;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipselabs.tapiji.tools.core.ui"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
new file mode 100644
index 00000000..c0af7f62
--- /dev/null
+++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
@@ -0,0 +1,10 @@
+package org.eclipselabs.tapiji.tools.core.ui.widgets;
+
+import org.eclipse.swt.dnd.TextTransfer;
+
+public class MVTextTransfer {
+
+ private MVTextTransfer () {
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
new file mode 100644
index 00000000..064dbf54
--- /dev/null
+++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
@@ -0,0 +1,659 @@
+package org.eclipselabs.tapiji.tools.core.ui.widgets;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IElementComparer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.ui.IViewSite;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.model.view.SortInfo;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
+import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource;
+import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.ExactMatcher;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter;
+import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
+
+public class PropertyKeySelectionTree extends Composite implements IResourceBundleChangedListener {
+
+ private final int KEY_COLUMN_WEIGHT = 1;
+ private final int LOCALE_COLUMN_WEIGHT = 1;
+
+ private ResourceBundleManager manager;
+ private String resourceBundle;
+ private List<Locale> visibleLocales = new ArrayList<Locale>();
+ private boolean editable;
+
+ 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;
+
+ public PropertyKeySelectionTree(IViewSite viewSite, IWorkbenchPartSite site, Composite parent, int style,
+ String projectName, String resources, List<Locale> locales) {
+ super(parent, style);
+ this.site = site;
+ resourceBundle = resources;
+
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ manager = ResourceBundleManager.getManager(projectName);
+ 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(manager.getResourceBundle(resourceBundle), visibleLocales,
+ manager, 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(manager.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();
+
+ // update content provider
+ contentProvider.setLocales(visibleLocales);
+ contentProvider.setBundleGroup(manager.getResourceBundle(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>();
+ sortInfo = new SortInfo();
+ visibleLocales.clear();
+ if (resourceBundle != null) {
+ for (Locale l : manager.getProvidedLocales(resourceBundle)) {
+ if (l == null) {
+ locSorted.put("Default", null);
+ } else {
+ locSorted.put(l.getDisplayName(uiLocale), l);
+ }
+ }
+ }
+
+ for (String lString : locSorted.keySet()) {
+ visibleLocales.add(locSorted.get(lString));
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ }
+
+ protected void constructWidget() {
+ basicLayout = new TreeColumnLayout();
+ this.setLayout(basicLayout);
+
+ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
+ Tree tree = treeViewer.getTree();
+
+ if (resourceBundle != null) {
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // create tree-columns
+ constructTreeColumns(tree);
+ } else {
+ tree.setHeaderVisible(false);
+ tree.setLinesVisible(false);
+ }
+
+ makeActions();
+ hookDoubleClickAction();
+
+ // register messages table as selection provider
+ site.setSelectionProvider(treeViewer);
+ }
+
+ protected void constructTreeColumns(Tree tree) {
+ tree.removeAll();
+ //tree.getColumns().length;
+
+ // construct key-column
+ keyColumn = new TreeColumn(tree, SWT.NONE);
+ keyColumn.setText("Key");
+ keyColumn.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(keyColumn, new ColumnWeightData(KEY_COLUMN_WEIGHT));
+
+ if (visibleLocales != null) {
+ 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);
+ IMessage message = messagesBundle.getMessage(activeKey);
+ if (message != null) {
+ message.setText(String.valueOf(value));
+ message.setComment(comment);
+ }
+ // TODO: find a better way
+ setTreeStructure();
+
+ }
+ }
+ }
+ }
+
+ @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);
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(uiLocale);
+
+ col.setText(displayName);
+ col.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+ });
+ basicLayout.setColumnData(col, new ColumnWeightData(LOCALE_COLUMN_WEIGHT));
+ }
+ }
+ }
+
+ protected void updateSorter(int idx) {
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ sorter.setSortInfo(sortInfo);
+ treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
+ setTreeStructure();
+ treeViewer.refresh();
+ }
+
+ @Override
+ public boolean setFocus() {
+ return treeViewer.getControl().setFocus();
+ }
+
+ /*** DRAG AND DROP ***/
+ protected void hookDragAndDrop() {
+ //KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource (treeViewer);
+ KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
+ MessagesDragSource source = new MessagesDragSource(treeViewer, this.resourceBundle);
+ MessagesDropTarget target = new MessagesDropTarget(treeViewer, manager, 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();
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject()).addMessagesEditorListener(editorListener);
+ }
+
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
+
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
+ }
+
+ protected void unregisterListeners() {
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject()).removeMessagesEditorListener(editorListener);
+ }
+ treeViewer.removeSelectionChangedListener(selectionChangedListener);
+ }
+
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
+ treeViewer.addSelectionChangedListener(listener);
+ selectionChangedListener = listener;
+ }
+
+ @Override
+ public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
+ if (event.getType() != ResourceBundleChangedEvent.MODIFIED
+ || !event.getBundle().equals(this.getResourceBundle()))
+ return;
+
+ if (Display.getCurrent() != null) {
+ refreshViewer(event, true);
+ return;
+ }
+
+ Display.getDefault().asyncExec(new Runnable() {
+
+ public void run() {
+ refreshViewer(event, true);
+ }
+ });
+ }
+
+ private void refreshViewer(ResourceBundleChangedEvent event, boolean computeVisibleLocales) {
+ //manager.loadResourceBundle(resourceBundle);
+ if (computeVisibleLocales) {
+ refreshContent(event);
+ }
+
+ // Display.getDefault().asyncExec(new Runnable() {
+ // public void run() {
+ treeViewer.refresh();
+ // }
+ // });
+ }
+
+ public StructuredViewer getViewer() {
+ return this.treeViewer;
+ }
+
+ public void setSearchString(String pattern) {
+ matcher.setPattern(pattern);
+ treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat : TreeType.Tree;
+ labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
+ // WTF?
+ treeType = treeType.equals(TreeType.Tree) && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
+ treeViewer.refresh();
+ }
+
+ public SortInfo getSortInfo() {
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ sortInfo.setVisibleLocales(visibleLocales);
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
+ treeViewer.refresh();
+ }
+ }
+
+ public String getSearchString() {
+ return matcher.getPattern();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public ResourceBundleManager getManager() {
+ return this.manager;
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void editSelectedItem() {
+ EditorUtils.openEditor(site.getPage(), manager.getRandomFile(resourceBundle),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR);
+ }
+
+ public void deleteSelectedItems() {
+ List<String> keys = new ArrayList<String>();
+
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ addKeysToRemove((IKeyTreeNode)elem, keys);
+ }
+ }
+ }
+
+ try {
+ manager.removeResourceBundleEntry(getResourceBundle(), keys);
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ }
+ }
+
+ private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
+ keys.add(node.getMessageKey());
+ for (IKeyTreeNode ktn : node.getChildren()) {
+ addKeysToRemove(ktn, keys);
+ }
+ }
+
+ public void addNewItem() {
+ //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
+
+ 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) {
+ newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
+ break;
+ }
+ }
+ }
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(Display.getDefault()
+ .getActiveShell(), manager, newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]"
+ : "", "", getResourceBundle(), "");
+ if (dialog.open() != InputDialog.OK)
+ return;
+ }
+
+ public void setMatchingPrecision(float value) {
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ private class MessagesEditorListener implements IMessagesEditorListener {
+ @Override
+ public void onSave() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onModify() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+ }
+}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
new file mode 100644
index 00000000..544d52bf
--- /dev/null
+++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
@@ -0,0 +1,233 @@
+package org.eclipselabs.tapiji.tools.core.ui.widgets;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.IElementComparer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
+
+
+public class ResourceSelector extends Composite {
+
+ public static final int DISPLAY_KEYS = 0;
+ public static final int DISPLAY_TEXT = 1;
+
+ private Locale displayLocale;
+ private int displayMode;
+ private String resourceBundle;
+ private ResourceBundleManager manager;
+ private boolean showTree;
+
+ private TreeViewer viewer;
+ private TreeColumnLayout basicLayout;
+ private TreeColumn entries;
+ private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>();
+
+ // Viewer model
+ private TreeType treeType = TreeType.Tree;
+ private StyledCellLabelProvider labelProvider;
+
+ public ResourceSelector(Composite parent,
+ int style,
+ ResourceBundleManager manager,
+ String resourceBundle,
+ int displayMode,
+ Locale displayLocale,
+ boolean showTree) {
+ super(parent, style);
+ this.manager = manager;
+ this.resourceBundle = resourceBundle;
+ this.displayMode = displayMode;
+ this.displayLocale = displayLocale;
+ this.showTree = showTree;
+ this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
+
+ initLayout (this);
+ initViewer (this);
+
+ updateViewer (true);
+ }
+
+ protected void updateContentProvider (IMessagesBundleGroup group) {
+ // define input of treeviewer
+ if (!showTree || displayMode == DISPLAY_TEXT) {
+ treeType = TreeType.Flat;
+ }
+
+ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle));
+ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setBundleGroup(manager.getResourceBundle(resourceBundle));
+ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ if (viewer.getInput() == null) {
+ viewer.setUseHashlookup(true);
+ }
+
+// viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer.getExpandedTreePaths();
+ viewer.setInput(model);
+ viewer.refresh();
+ viewer.setExpandedTreePaths(expandedTreePaths);
+ }
+
+ protected void updateViewer (boolean updateContent) {
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+
+ if (group == null)
+ return;
+
+ if (displayMode == DISPLAY_TEXT) {
+ labelProvider = new ValueKeyTreeLabelProvider(group.getMessagesBundle(displayLocale));
+ treeType = TreeType.Flat;
+ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ } else {
+ labelProvider = new ResKeyTreeLabelProvider(null);
+ treeType = TreeType.Tree;
+ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ }
+
+ viewer.setLabelProvider(labelProvider);
+ if (updateContent)
+ updateContentProvider(group);
+ }
+
+ protected void initLayout (Composite parent) {
+ basicLayout = new TreeColumnLayout();
+ parent.setLayout(basicLayout);
+ }
+
+ protected void initViewer (Composite parent) {
+ viewer = new TreeViewer (parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
+ Tree table = viewer.getTree();
+
+ // Init table-columns
+ entries = new TreeColumn (table, SWT.NONE);
+ basicLayout.setColumnData(entries, new ColumnWeightData(1));
+
+ viewer.setContentProvider(new ResKeyTreeContentProvider());
+ viewer.addSelectionChangedListener(new ISelectionChangedListener() {
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ ISelection selection = event.getSelection();
+ String selectionSummary = "";
+ String selectedKey = "";
+
+ if (selection instanceof IStructuredSelection) {
+ Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection).iterator();
+ if (itSel.hasNext()) {
+ IKeyTreeNode selItem = itSel.next();
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ selectedKey = selItem.getMessageKey();
+
+ if (group == null)
+ return;
+ Iterator<Locale> itLocales = manager.getProvidedLocales(resourceBundle).iterator();
+ while (itLocales.hasNext()) {
+ Locale l = itLocales.next();
+ try {
+ selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayLanguage()) + ":\n";
+ selectionSummary += "\t" + group.getMessagesBundle(l).getMessage(selItem.getMessageKey()).getValue() + "\n";
+ } catch (Exception e) {}
+ }
+ }
+ }
+
+ // construct ResourceSelectionEvent
+ ResourceSelectionEvent e = new ResourceSelectionEvent(selectedKey, selectionSummary);
+ fireSelectionChanged(e);
+ }
+ });
+
+ // we need this to keep the tree expanded
+ viewer.setComparer(new IElementComparer() {
+
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
+ }
+
+ public Locale getDisplayLocale() {
+ return displayLocale;
+ }
+
+ public void setDisplayLocale(Locale displayLocale) {
+ this.displayLocale = displayLocale;
+ updateViewer(false);
+ }
+
+ public int getDisplayMode() {
+ return displayMode;
+ }
+
+ public void setDisplayMode(int displayMode) {
+ this.displayMode = displayMode;
+ updateViewer(true);
+ }
+
+ public void setResourceBundle(String resourceBundle) {
+ this.resourceBundle = resourceBundle;
+ updateViewer(true);
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void addSelectionChangedListener (IResourceSelectionListener l) {
+ listeners.add(l);
+ }
+
+ public void removeSelectionChangedListener (IResourceSelectionListener l) {
+ listeners.remove(l);
+ }
+
+ private void fireSelectionChanged (ResourceSelectionEvent event) {
+ Iterator<IResourceSelectionListener> itResList = listeners.iterator();
+ while (itResList.hasNext()) {
+ itResList.next().selectionChanged(event);
+ }
+ }
+
+}
|
64b71912f58781431f08455d51b07676f9bf122e
|
Mylyn Reviews
|
TBR: Fixed artifact ids in pom
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/pom.xml b/tbr/org.eclipse.mylyn.reviews.tasks.core/pom.xml
index e3dcc82a..64f05b6c 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/pom.xml
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/pom.xml
@@ -8,7 +8,7 @@
<version>0.7.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.mylyn.reviews</groupId>
- <artifactId>org.eclipse.mylyn.tasks.core</artifactId>
+ <artifactId>org.eclipse.mylyn.reviews.tasks.core</artifactId>
<version>0.7.0-SNAPSHOT</version>
<packaging>eclipse-plugin</packaging>
<build>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml
index a652c89f..7e5eda1a 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml
@@ -8,7 +8,7 @@
<version>0.7.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.mylyn.reviews</groupId>
- <artifactId>org.eclipse.mylyn.tasks.dsl</artifactId>
+ <artifactId>org.eclipse.mylyn.reviews.tasks.dsl</artifactId>
<version>0.7.0-SNAPSHOT</version>
<packaging>eclipse-plugin</packaging>
<build>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/pom.xml b/tbr/org.eclipse.mylyn.reviews.tasks.ui/pom.xml
index bc8ce6d6..b949fdbc 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/pom.xml
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/pom.xml
@@ -8,7 +8,7 @@
<version>0.7.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.mylyn.reviews</groupId>
- <artifactId>org.eclipse.mylyn.tasks.ui</artifactId>
+ <artifactId>org.eclipse.mylyn.reviews.tasks.ui</artifactId>
<version>0.7.0-SNAPSHOT</version>
<packaging>eclipse-plugin</packaging>
<build>
|
9da487e0fdbf657f9b401e62d165ab13105488a0
|
hadoop
|
YARN-3853. Add docker container runtime support to- LinuxContainterExecutor. Contributed by Sidharta Seethana.--(cherry picked from commit 3e6fce91a471b4a5099de109582e7c6417e8a822)--Conflicts:-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 993828da00951..724ddd0eea536 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -98,6 +98,10 @@ Release 2.8.0 - UNRELEASED
YARN-3852. Add docker container support to container-executor
(Abin Shahab via vvasudev)
+ YARN-3853. Add docker container runtime support to LinuxContainterExecutor.
+ (Sidharta Seethana via vvasudev)
+
+
IMPROVEMENTS
YARN-644. Basic null check is not performed on passed in arguments before
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java
index 79f9b0d2910f0..68bfbbfdd148b 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java
@@ -24,8 +24,10 @@
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashSet;
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.locks.ReentrantReadWriteLock;
@@ -39,6 +41,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
@@ -160,7 +163,7 @@ public abstract void deleteAsUser(DeletionAsUserContext ctx)
* @return true if container is still alive
* @throws IOException
*/
- public abstract boolean isContainerProcessAlive(ContainerLivenessContext ctx)
+ public abstract boolean isContainerAlive(ContainerLivenessContext ctx)
throws IOException;
/**
@@ -174,6 +177,7 @@ public abstract boolean isContainerProcessAlive(ContainerLivenessContext ctx)
*/
public int reacquireContainer(ContainerReacquisitionContext ctx)
throws IOException, InterruptedException {
+ Container container = ctx.getContainer();
String user = ctx.getUser();
ContainerId containerId = ctx.getContainerId();
@@ -193,10 +197,11 @@ public int reacquireContainer(ContainerReacquisitionContext ctx)
LOG.info("Reacquiring " + containerId + " with pid " + pid);
ContainerLivenessContext livenessContext = new ContainerLivenessContext
.Builder()
+ .setContainer(container)
.setUser(user)
.setPid(pid)
.build();
- while(isContainerProcessAlive(livenessContext)) {
+ while(isContainerAlive(livenessContext)) {
Thread.sleep(1000);
}
@@ -243,9 +248,20 @@ public void writeLaunchEnv(OutputStream out, Map<String, String> environment,
Map<Path, List<String>> resources, List<String> command) throws IOException{
ContainerLaunch.ShellScriptBuilder sb =
ContainerLaunch.ShellScriptBuilder.create();
+ Set<String> whitelist = new HashSet<String>();
+ whitelist.add(YarnConfiguration.NM_DOCKER_CONTAINER_EXECUTOR_IMAGE_NAME);
+ whitelist.add(ApplicationConstants.Environment.HADOOP_YARN_HOME.name());
+ whitelist.add(ApplicationConstants.Environment.HADOOP_COMMON_HOME.name());
+ whitelist.add(ApplicationConstants.Environment.HADOOP_HDFS_HOME.name());
+ whitelist.add(ApplicationConstants.Environment.HADOOP_CONF_DIR.name());
+ whitelist.add(ApplicationConstants.Environment.JAVA_HOME.name());
if (environment != null) {
for (Map.Entry<String,String> env : environment.entrySet()) {
- sb.env(env.getKey().toString(), env.getValue().toString());
+ if (!whitelist.contains(env.getKey())) {
+ sb.env(env.getKey().toString(), env.getValue().toString());
+ } else {
+ sb.whitelistedEnv(env.getKey().toString(), env.getValue().toString());
+ }
}
}
if (resources != null) {
@@ -492,6 +508,7 @@ public void run() {
try {
Thread.sleep(delay);
containerExecutor.signalContainer(new ContainerSignalContext.Builder()
+ .setContainer(container)
.setUser(user)
.setPid(pid)
.setSignal(signal)
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java
index b9be2b110e2d0..5819f2378d669 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java
@@ -430,7 +430,7 @@ public boolean signalContainer(ContainerSignalContext ctx)
}
@Override
- public boolean isContainerProcessAlive(ContainerLivenessContext ctx)
+ public boolean isContainerAlive(ContainerLivenessContext ctx)
throws IOException {
String pid = ctx.getPid();
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java
index d3b5d0a7dda2e..9dffff3037b34 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java
@@ -413,7 +413,7 @@ public boolean signalContainer(ContainerSignalContext ctx)
}
@Override
- public boolean isContainerProcessAlive(ContainerLivenessContext ctx)
+ public boolean isContainerAlive(ContainerLivenessContext ctx)
throws IOException {
String pid = ctx.getPid();
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java
index c60b80b8e97c2..f8e58c1ddddd9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java
@@ -20,15 +20,6 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.regex.Pattern;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
@@ -46,10 +37,14 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
-import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandler;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerModule;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.DelegatingLinuxContainerRuntime;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntime;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerLivenessContext;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerReacquisitionContext;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext;
@@ -60,6 +55,22 @@
import org.apache.hadoop.yarn.server.nodemanager.util.LCEResourcesHandler;
import org.apache.hadoop.yarn.util.ConverterUtils;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*;
+
+/** Container execution for Linux. Provides linux-specific localization
+ * mechanisms, resource management via cgroups and can switch between multiple
+ * container runtimes - e.g Standard "Process Tree", Docker etc
+ */
+
public class LinuxContainerExecutor extends ContainerExecutor {
private static final Log LOG = LogFactory
@@ -73,6 +84,15 @@ public class LinuxContainerExecutor extends ContainerExecutor {
private int containerSchedPriorityAdjustment = 0;
private boolean containerLimitUsers;
private ResourceHandler resourceHandlerChain;
+ private LinuxContainerRuntime linuxContainerRuntime;
+
+ public LinuxContainerExecutor() {
+ }
+
+ // created primarily for testing
+ public LinuxContainerExecutor(LinuxContainerRuntime linuxContainerRuntime) {
+ this.linuxContainerRuntime = linuxContainerRuntime;
+ }
@Override
public void setConf(Configuration conf) {
@@ -87,8 +107,8 @@ public void setConf(Configuration conf) {
if (conf.get(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY) != null) {
containerSchedPriorityIsSet = true;
containerSchedPriorityAdjustment = conf
- .getInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY,
- YarnConfiguration.DEFAULT_NM_CONTAINER_EXECUTOR_SCHED_PRIORITY);
+ .getInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY,
+ YarnConfiguration.DEFAULT_NM_CONTAINER_EXECUTOR_SCHED_PRIORITY);
}
nonsecureLocalUser = conf.get(
YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY,
@@ -122,48 +142,6 @@ String getRunAsUser(String user) {
}
}
-
-
- /**
- * List of commands that the setuid script will execute.
- */
- enum Commands {
- INITIALIZE_CONTAINER(0),
- LAUNCH_CONTAINER(1),
- SIGNAL_CONTAINER(2),
- DELETE_AS_USER(3);
-
- private int value;
- Commands(int value) {
- this.value = value;
- }
- int getValue() {
- return value;
- }
- }
-
- /**
- * Result codes returned from the C container-executor.
- * These must match the values in container-executor.h.
- */
- enum ResultCode {
- OK(0),
- INVALID_USER_NAME(2),
- UNABLE_TO_EXECUTE_CONTAINER_SCRIPT(7),
- INVALID_CONTAINER_PID(9),
- INVALID_CONTAINER_EXEC_PERMISSIONS(22),
- INVALID_CONFIG_FILE(24),
- WRITE_CGROUP_FAILED(27);
-
- private final int value;
- ResultCode(int value) {
- this.value = value;
- }
- int getValue() {
- return value;
- }
- }
-
protected String getContainerExecutorExecutablePath(Configuration conf) {
String yarnHomeEnvVar =
System.getenv(ApplicationConstants.Environment.HADOOP_YARN_HOME.key());
@@ -205,9 +183,9 @@ public void init() throws IOException {
+ " (error=" + exitCode + ")", e);
}
- try {
- Configuration conf = super.getConf();
+ Configuration conf = super.getConf();
+ try {
resourceHandlerChain = ResourceHandlerModule
.getConfiguredResourceHandlerChain(conf);
if (resourceHandlerChain != null) {
@@ -218,9 +196,20 @@ public void init() throws IOException {
throw new IOException("Failed to bootstrap configured resource subsystems!");
}
+ try {
+ if (linuxContainerRuntime == null) {
+ LinuxContainerRuntime runtime = new DelegatingLinuxContainerRuntime();
+
+ runtime.initialize(conf);
+ this.linuxContainerRuntime = runtime;
+ }
+ } catch (ContainerExecutionException e) {
+ throw new IOException("Failed to initialize linux container runtime(s)!");
+ }
+
resourcesHandler.init(this);
}
-
+
@Override
public void startLocalizer(LocalizerStartContext ctx)
throws IOException, InterruptedException {
@@ -240,7 +229,7 @@ public void startLocalizer(LocalizerStartContext ctx)
command.addAll(Arrays.asList(containerExecutorExe,
runAsUser,
user,
- Integer.toString(Commands.INITIALIZE_CONTAINER.getValue()),
+ Integer.toString(PrivilegedOperation.RunAsUserCommand.INITIALIZE_CONTAINER.getValue()),
appId,
nmPrivateContainerTokensPath.toUri().getPath().toString(),
StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
@@ -296,6 +285,7 @@ public int launchContainer(ContainerStartContext ctx) throws IOException {
Path containerWorkDir = ctx.getContainerWorkDir();
List<String> localDirs = ctx.getLocalDirs();
List<String> logDirs = ctx.getLogDirs();
+ Map<Path, List<String>> localizedResources = ctx.getLocalizedResources();
verifyUsernamePattern(user);
String runAsUser = getRunAsUser(user);
@@ -353,50 +343,48 @@ public int launchContainer(ContainerStartContext ctx) throws IOException {
throw new IOException("ResourceHandlerChain.preStart() failed!");
}
- ShellCommandExecutor shExec = null;
-
try {
Path pidFilePath = getPidFilePath(containerId);
if (pidFilePath != null) {
- List<String> command = new ArrayList<String>();
- addSchedPriorityCommand(command);
- command.addAll(Arrays.asList(
- containerExecutorExe, runAsUser, user, Integer
- .toString(Commands.LAUNCH_CONTAINER.getValue()), appId,
- containerIdStr, containerWorkDir.toString(),
- nmPrivateContainerScriptPath.toUri().getPath().toString(),
- nmPrivateTokensPath.toUri().getPath().toString(),
- pidFilePath.toString(),
- StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
- localDirs),
- StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
- logDirs),
- resourcesOptions));
+ List<String> prefixCommands= new ArrayList<>();
+ ContainerRuntimeContext.Builder builder = new ContainerRuntimeContext
+ .Builder(container);
+
+ addSchedPriorityCommand(prefixCommands);
+ if (prefixCommands.size() > 0) {
+ builder.setExecutionAttribute(CONTAINER_LAUNCH_PREFIX_COMMANDS,
+ prefixCommands);
+ }
+
+ builder.setExecutionAttribute(LOCALIZED_RESOURCES, localizedResources)
+ .setExecutionAttribute(RUN_AS_USER, runAsUser)
+ .setExecutionAttribute(USER, user)
+ .setExecutionAttribute(APPID, appId)
+ .setExecutionAttribute(CONTAINER_ID_STR, containerIdStr)
+ .setExecutionAttribute(CONTAINER_WORK_DIR, containerWorkDir)
+ .setExecutionAttribute(NM_PRIVATE_CONTAINER_SCRIPT_PATH,
+ nmPrivateContainerScriptPath)
+ .setExecutionAttribute(NM_PRIVATE_TOKENS_PATH, nmPrivateTokensPath)
+ .setExecutionAttribute(PID_FILE_PATH, pidFilePath)
+ .setExecutionAttribute(LOCAL_DIRS, localDirs)
+ .setExecutionAttribute(LOG_DIRS, logDirs)
+ .setExecutionAttribute(RESOURCES_OPTIONS, resourcesOptions);
if (tcCommandFile != null) {
- command.add(tcCommandFile);
+ builder.setExecutionAttribute(TC_COMMAND_FILE, tcCommandFile);
}
- String[] commandArray = command.toArray(new String[command.size()]);
- shExec = new ShellCommandExecutor(commandArray, null, // NM's cwd
- container.getLaunchContext().getEnvironment()); // sanitized env
- if (LOG.isDebugEnabled()) {
- LOG.debug("launchContainer: " + Arrays.toString(commandArray));
- }
- shExec.execute();
- if (LOG.isDebugEnabled()) {
- logOutput(shExec.getOutput());
- }
+ linuxContainerRuntime.launchContainer(builder.build());
} else {
LOG.info("Container was marked as inactive. Returning terminated error");
return ExitCode.TERMINATED.getExitCode();
}
- } catch (ExitCodeException e) {
- int exitCode = shExec.getExitCode();
+ } catch (ContainerExecutionException e) {
+ int exitCode = e.getExitCode();
LOG.warn("Exit code from container " + containerId + " is : " + exitCode);
// 143 (SIGTERM) and 137 (SIGKILL) exit codes means the container was
// terminated/killed forcefully. In all other cases, log the
- // container-executor's output
+ // output
if (exitCode != ExitCode.FORCE_KILLED.getExitCode()
&& exitCode != ExitCode.TERMINATED.getExitCode()) {
LOG.warn("Exception from container-launch with container ID: "
@@ -406,13 +394,13 @@ public int launchContainer(ContainerStartContext ctx) throws IOException {
builder.append("Exception from container-launch.\n");
builder.append("Container id: " + containerId + "\n");
builder.append("Exit code: " + exitCode + "\n");
- if (!Optional.fromNullable(e.getMessage()).or("").isEmpty()) {
- builder.append("Exception message: " + e.getMessage() + "\n");
+ if (!Optional.fromNullable(e.getErrorOutput()).or("").isEmpty()) {
+ builder.append("Exception message: " + e.getErrorOutput() + "\n");
}
builder.append("Stack trace: "
+ StringUtils.stringifyException(e) + "\n");
- if (!shExec.getOutput().isEmpty()) {
- builder.append("Shell output: " + shExec.getOutput() + "\n");
+ if (!e.getOutput().isEmpty()) {
+ builder.append("Shell output: " + e.getOutput() + "\n");
}
String diagnostics = builder.toString();
logOutput(diagnostics);
@@ -435,10 +423,7 @@ public int launchContainer(ContainerStartContext ctx) throws IOException {
"containerId: " + containerId + ". Exception: " + e);
}
}
- if (LOG.isDebugEnabled()) {
- LOG.debug("Output from LinuxContainerExecutor's launchContainer follows:");
- logOutput(shExec.getOutput());
- }
+
return 0;
}
@@ -476,6 +461,7 @@ public int reacquireContainer(ContainerReacquisitionContext ctx)
@Override
public boolean signalContainer(ContainerSignalContext ctx)
throws IOException {
+ Container container = ctx.getContainer();
String user = ctx.getUser();
String pid = ctx.getPid();
Signal signal = ctx.getSignal();
@@ -483,30 +469,27 @@ public boolean signalContainer(ContainerSignalContext ctx)
verifyUsernamePattern(user);
String runAsUser = getRunAsUser(user);
- String[] command =
- new String[] { containerExecutorExe,
- runAsUser,
- user,
- Integer.toString(Commands.SIGNAL_CONTAINER.getValue()),
- pid,
- Integer.toString(signal.getValue()) };
- ShellCommandExecutor shExec = new ShellCommandExecutor(command);
- if (LOG.isDebugEnabled()) {
- LOG.debug("signalContainer: " + Arrays.toString(command));
- }
+ ContainerRuntimeContext runtimeContext = new ContainerRuntimeContext
+ .Builder(container)
+ .setExecutionAttribute(RUN_AS_USER, runAsUser)
+ .setExecutionAttribute(USER, user)
+ .setExecutionAttribute(PID, pid)
+ .setExecutionAttribute(SIGNAL, signal)
+ .build();
+
try {
- shExec.execute();
- } catch (ExitCodeException e) {
- int ret_code = shExec.getExitCode();
- if (ret_code == ResultCode.INVALID_CONTAINER_PID.getValue()) {
+ linuxContainerRuntime.signalContainer(runtimeContext);
+ } catch (ContainerExecutionException e) {
+ int retCode = e.getExitCode();
+ if (retCode == PrivilegedOperation.ResultCode.INVALID_CONTAINER_PID.getValue()) {
return false;
}
LOG.warn("Error in signalling container " + pid + " with " + signal
- + "; exit = " + ret_code, e);
- logOutput(shExec.getOutput());
+ + "; exit = " + retCode, e);
+ logOutput(e.getOutput());
throw new IOException("Problem signalling container " + pid + " with "
- + signal + "; output: " + shExec.getOutput() + " and exitCode: "
- + ret_code, e);
+ + signal + "; output: " + e.getOutput() + " and exitCode: "
+ + retCode, e);
}
return true;
}
@@ -526,7 +509,8 @@ public void deleteAsUser(DeletionAsUserContext ctx) {
Arrays.asList(containerExecutorExe,
runAsUser,
user,
- Integer.toString(Commands.DELETE_AS_USER.getValue()),
+ Integer.toString(PrivilegedOperation.
+ RunAsUserCommand.DELETE_AS_USER.getValue()),
dirString));
List<String> pathsToDelete = new ArrayList<String>();
if (baseDirs == null || baseDirs.size() == 0) {
@@ -560,13 +544,15 @@ public void deleteAsUser(DeletionAsUserContext ctx) {
}
@Override
- public boolean isContainerProcessAlive(ContainerLivenessContext ctx)
+ public boolean isContainerAlive(ContainerLivenessContext ctx)
throws IOException {
String user = ctx.getUser();
String pid = ctx.getPid();
+ Container container = ctx.getContainer();
// Send a test signal to the process as the user to see if it's alive
return signalContainer(new ContainerSignalContext.Builder()
+ .setContainer(container)
.setUser(user)
.setPid(pid)
.setSignal(Signal.NULL)
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java
index af168c5943bd6..bf00d74dce7ef 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java
@@ -303,6 +303,7 @@ public Integer call() {
exec.activateContainer(containerID, pidFilePath);
ret = exec.launchContainer(new ContainerStartContext.Builder()
.setContainer(container)
+ .setLocalizedResources(localResources)
.setNmPrivateContainerScriptPath(nmPrivateContainerScriptPath)
.setNmPrivateTokensPath(nmPrivateTokensPath)
.setUser(user)
@@ -427,6 +428,7 @@ public void cleanupContainer() throws IOException {
boolean result = exec.signalContainer(
new ContainerSignalContext.Builder()
+ .setContainer(container)
.setUser(user)
.setPid(processId)
.setSignal(signal)
@@ -528,6 +530,8 @@ public static ShellScriptBuilder create() {
public abstract void command(List<String> command) throws IOException;
+ public abstract void whitelistedEnv(String key, String value) throws IOException;
+
public abstract void env(String key, String value) throws IOException;
public final void symlink(Path src, Path dst) throws IOException {
@@ -585,6 +589,11 @@ public void command(List<String> command) {
errorCheck();
}
+ @Override
+ public void whitelistedEnv(String key, String value) {
+ line("export ", key, "=${", key, ":-", "\"", value, "\"}");
+ }
+
@Override
public void env(String key, String value) {
line("export ", key, "=\"", value, "\"");
@@ -626,6 +635,12 @@ public void command(List<String> command) throws IOException {
errorCheck();
}
+ @Override
+ public void whitelistedEnv(String key, String value) throws IOException {
+ lineWithLenCheck("@set ", key, "=", value);
+ errorCheck();
+ }
+
@Override
public void env(String key, String value) throws IOException {
lineWithLenCheck("@set ", key, "=", value);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java
index f220cbd98f7cd..cbbf7a80c0b00 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java
@@ -45,10 +45,12 @@ public enum OperationType {
LAUNCH_CONTAINER(""), //no CLI switch supported yet
SIGNAL_CONTAINER(""), //no CLI switch supported yet
DELETE_AS_USER(""), //no CLI switch supported yet
+ LAUNCH_DOCKER_CONTAINER(""), //no CLI switch supported yet
TC_MODIFY_STATE("--tc-modify-state"),
TC_READ_STATE("--tc-read-state"),
TC_READ_STATS("--tc-read-stats"),
- ADD_PID_TO_CGROUP(""); //no CLI switch supported yet.
+ ADD_PID_TO_CGROUP(""), //no CLI switch supported yet.
+ RUN_DOCKER_CMD("--run-docker");
private final String option;
@@ -62,6 +64,7 @@ public String getOption() {
}
public static final String CGROUP_ARG_PREFIX = "cgroups=";
+ public static final String CGROUP_ARG_NO_TASKS = "none";
private final OperationType opType;
private final List<String> args;
@@ -117,4 +120,45 @@ public boolean equals(Object other) {
public int hashCode() {
return opType.hashCode() + 97 * args.hashCode();
}
+
+ /**
+ * List of commands that the container-executor will execute.
+ */
+ public enum RunAsUserCommand {
+ INITIALIZE_CONTAINER(0),
+ LAUNCH_CONTAINER(1),
+ SIGNAL_CONTAINER(2),
+ DELETE_AS_USER(3),
+ LAUNCH_DOCKER_CONTAINER(4);
+
+ private int value;
+ RunAsUserCommand(int value) {
+ this.value = value;
+ }
+ public int getValue() {
+ return value;
+ }
+ }
+
+ /**
+ * Result codes returned from the C container-executor.
+ * These must match the values in container-executor.h.
+ */
+ public enum ResultCode {
+ OK(0),
+ INVALID_USER_NAME(2),
+ UNABLE_TO_EXECUTE_CONTAINER_SCRIPT(7),
+ INVALID_CONTAINER_PID(9),
+ INVALID_CONTAINER_EXEC_PERMISSIONS(22),
+ INVALID_CONFIG_FILE(24),
+ WRITE_CGROUP_FAILED(27);
+
+ private final int value;
+ ResultCode(int value) {
+ this.value = value;
+ }
+ public int getValue() {
+ return value;
+ }
+ }
}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java
index 20c234d984a0e..3622489a499f9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java
@@ -24,6 +24,9 @@
public class PrivilegedOperationException extends YarnException {
private static final long serialVersionUID = 1L;
+ private Integer exitCode;
+ private String output;
+ private String errorOutput;
public PrivilegedOperationException() {
super();
@@ -33,11 +36,36 @@ public PrivilegedOperationException(String message) {
super(message);
}
+ public PrivilegedOperationException(String message, Integer exitCode,
+ String output, String errorOutput) {
+ super(message);
+ this.exitCode = exitCode;
+ this.output = output;
+ this.errorOutput = errorOutput;
+ }
+
public PrivilegedOperationException(Throwable cause) {
super(cause);
}
+ public PrivilegedOperationException(Throwable cause, Integer exitCode, String
+ output, String errorOutput) {
+ super(cause);
+ this.exitCode = exitCode;
+ this.output = output;
+ this.errorOutput = errorOutput;
+ }
public PrivilegedOperationException(String message, Throwable cause) {
super(message, cause);
}
-}
+
+ public Integer getExitCode() {
+ return exitCode;
+ }
+
+ public String getOutput() {
+ return output;
+ }
+
+ public String getErrorOutput() { return errorOutput; }
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java
index 6fe0f5ce47f3d..1d71938ba2626 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java
@@ -20,6 +20,7 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged;
+import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -101,7 +102,13 @@ public String[] getPrivilegedOperationExecutionCommand(List<String>
}
fullCommand.add(containerExecutorExe);
- fullCommand.add(operation.getOperationType().getOption());
+
+ String cliSwitch = operation.getOperationType().getOption();
+
+ if (!cliSwitch.isEmpty()) {
+ fullCommand.add(cliSwitch);
+ }
+
fullCommand.addAll(operation.getArguments());
String[] fullCommandArray =
@@ -142,6 +149,8 @@ public String executePrivilegedOperation(List<String> prefixCommands,
try {
exec.execute();
if (LOG.isDebugEnabled()) {
+ LOG.debug("command array:");
+ LOG.debug(Arrays.toString(fullCommandArray));
LOG.debug("Privileged Execution Operation Output:");
LOG.debug(exec.getOutput());
}
@@ -152,7 +161,11 @@ public String executePrivilegedOperation(List<String> prefixCommands,
.append(System.lineSeparator()).append(exec.getOutput()).toString();
LOG.warn(logLine);
- throw new PrivilegedOperationException(e);
+
+ //stderr from shell executor seems to be stuffed into the exception
+ //'message' - so, we have to extract it and set it as the error out
+ throw new PrivilegedOperationException(e, e.getExitCode(),
+ exec.getOutput(), e.getMessage());
} catch (IOException e) {
LOG.warn("IOException executing command: ", e);
throw new PrivilegedOperationException(e);
@@ -202,7 +215,7 @@ public String executePrivilegedOperation(PrivilegedOperation operation,
StringBuffer finalOpArg = new StringBuffer(PrivilegedOperation
.CGROUP_ARG_PREFIX);
- boolean noneArgsOnly = true;
+ boolean noTasks = true;
for (PrivilegedOperation op : ops) {
if (!op.getOperationType()
@@ -227,23 +240,24 @@ public String executePrivilegedOperation(PrivilegedOperation operation,
throw new PrivilegedOperationException("Invalid argument: " + arg);
}
- if (tasksFile.equals("none")) {
+ if (tasksFile.equals(PrivilegedOperation.CGROUP_ARG_NO_TASKS)) {
//Don't append to finalOpArg
continue;
}
- if (noneArgsOnly == false) {
+ if (noTasks == false) {
//We have already appended at least one tasks file.
finalOpArg.append(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR);
finalOpArg.append(tasksFile);
} else {
finalOpArg.append(tasksFile);
- noneArgsOnly = false;
+ noTasks = false;
}
}
- if (noneArgsOnly) {
- finalOpArg.append("none"); //there were no tasks file to append
+ if (noTasks) {
+ finalOpArg.append(PrivilegedOperation.CGROUP_ARG_NO_TASKS); //there
+ // were no tasks file to append
}
PrivilegedOperation finalOp = new PrivilegedOperation(
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java
index 70dc8181de888..6020bc1379fd1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java
@@ -78,6 +78,14 @@ public String createCGroup(CGroupController controller, String cGroupId)
public void deleteCGroup(CGroupController controller, String cGroupId) throws
ResourceHandlerException;
+ /**
+ * Gets the relative path for the cgroup, independent of a controller, for a
+ * given cgroup id.
+ * @param cGroupId - id of the cgroup
+ * @return path for the cgroup relative to the root of (any) controller.
+ */
+ public String getRelativePathForCGroup(String cGroupId);
+
/**
* Gets the full path for the cgroup, given a controller and a cgroup id
* @param controller - controller type for the cgroup
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java
index ff5612133990e..0d71a9da83cf5 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java
@@ -147,9 +147,9 @@ static Map<CGroupController, String> initializeControllerPathsFromMtab(
} else {
String error =
new StringBuffer("Mount point Based on mtab file: ")
- .append(mtab)
- .append(". Controller mount point not writable for: ")
- .append(name).toString();
+ .append(mtab)
+ .append(". Controller mount point not writable for: ")
+ .append(name).toString();
LOG.error(error);
throw new ResourceHandlerException(error);
@@ -271,6 +271,12 @@ public void mountCGroupController(CGroupController controller)
}
}
+ @Override
+ public String getRelativePathForCGroup(String cGroupId) {
+ return new StringBuffer(cGroupPrefix).append("/")
+ .append(cGroupId).toString();
+ }
+
@Override
public String getPathForCGroup(CGroupController controller, String cGroupId) {
return new StringBuffer(getControllerPath(controller))
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DefaultLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DefaultLinuxContainerRuntime.java
new file mode 100644
index 0000000000000..633fa668ae411
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DefaultLinuxContainerRuntime.java
@@ -0,0 +1,148 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext;
+
+import java.util.List;
+
+import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*;
+
[email protected]
[email protected]
+public class DefaultLinuxContainerRuntime implements LinuxContainerRuntime {
+ private static final Log LOG = LogFactory
+ .getLog(DefaultLinuxContainerRuntime.class);
+ private Configuration conf;
+ private final PrivilegedOperationExecutor privilegedOperationExecutor;
+
+ public DefaultLinuxContainerRuntime(PrivilegedOperationExecutor
+ privilegedOperationExecutor) {
+ this.privilegedOperationExecutor = privilegedOperationExecutor;
+ }
+
+ @Override
+ public void initialize(Configuration conf)
+ throws ContainerExecutionException {
+ this.conf = conf;
+ }
+
+ @Override
+ public void prepareContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ //nothing to do here at the moment.
+ }
+
+ @Override
+ public void launchContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ PrivilegedOperation launchOp = new PrivilegedOperation(
+ PrivilegedOperation.OperationType.LAUNCH_CONTAINER, (String) null);
+
+ //All of these arguments are expected to be available in the runtime context
+ launchOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER),
+ ctx.getExecutionAttribute(USER),
+ Integer.toString(PrivilegedOperation.
+ RunAsUserCommand.LAUNCH_CONTAINER.getValue()),
+ ctx.getExecutionAttribute(APPID),
+ ctx.getExecutionAttribute(CONTAINER_ID_STR),
+ ctx.getExecutionAttribute(CONTAINER_WORK_DIR).toString(),
+ ctx.getExecutionAttribute(NM_PRIVATE_CONTAINER_SCRIPT_PATH).toUri()
+ .getPath(),
+ ctx.getExecutionAttribute(NM_PRIVATE_TOKENS_PATH).toUri().getPath(),
+ ctx.getExecutionAttribute(PID_FILE_PATH).toString(),
+ StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
+ ctx.getExecutionAttribute(LOCAL_DIRS)),
+ StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
+ ctx.getExecutionAttribute(LOG_DIRS)),
+ ctx.getExecutionAttribute(RESOURCES_OPTIONS));
+
+ String tcCommandFile = ctx.getExecutionAttribute(TC_COMMAND_FILE);
+
+ if (tcCommandFile != null) {
+ launchOp.appendArgs(tcCommandFile);
+ }
+
+ //List<String> -> stored as List -> fetched/converted to List<String>
+ //we can't do better here thanks to type-erasure
+ @SuppressWarnings("unchecked")
+ List<String> prefixCommands = (List<String>) ctx.getExecutionAttribute(
+ CONTAINER_LAUNCH_PREFIX_COMMANDS);
+
+ try {
+ privilegedOperationExecutor.executePrivilegedOperation(prefixCommands,
+ launchOp, null, container.getLaunchContext().getEnvironment(),
+ false);
+ } catch (PrivilegedOperationException e) {
+ LOG.warn("Launch container failed. Exception: ", e);
+
+ throw new ContainerExecutionException("Launch container failed", e
+ .getExitCode(), e.getOutput(), e.getErrorOutput());
+ }
+ }
+
+ @Override
+ public void signalContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ PrivilegedOperation signalOp = new PrivilegedOperation(
+ PrivilegedOperation.OperationType.SIGNAL_CONTAINER, (String) null);
+
+ signalOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER),
+ ctx.getExecutionAttribute(USER),
+ Integer.toString(PrivilegedOperation.RunAsUserCommand
+ .SIGNAL_CONTAINER.getValue()),
+ ctx.getExecutionAttribute(PID),
+ Integer.toString(ctx.getExecutionAttribute(SIGNAL).getValue()));
+
+ try {
+ PrivilegedOperationExecutor executor = PrivilegedOperationExecutor
+ .getInstance(conf);
+
+ executor.executePrivilegedOperation(null,
+ signalOp, null, container.getLaunchContext().getEnvironment(),
+ false);
+ } catch (PrivilegedOperationException e) {
+ LOG.warn("Signal container failed. Exception: ", e);
+
+ throw new ContainerExecutionException("Signal container failed", e
+ .getExitCode(), e.getOutput(), e.getErrorOutput());
+ }
+ }
+
+ @Override
+ public void reapContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DelegatingLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DelegatingLinuxContainerRuntime.java
new file mode 100644
index 0000000000000..a59415fff3fcd
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DelegatingLinuxContainerRuntime.java
@@ -0,0 +1,110 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext;
+
+import java.util.Map;
+
[email protected]
[email protected]
+public class DelegatingLinuxContainerRuntime implements LinuxContainerRuntime {
+ private static final Log LOG = LogFactory
+ .getLog(DelegatingLinuxContainerRuntime.class);
+ private DefaultLinuxContainerRuntime defaultLinuxContainerRuntime;
+ private DockerLinuxContainerRuntime dockerLinuxContainerRuntime;
+
+ @Override
+ public void initialize(Configuration conf)
+ throws ContainerExecutionException {
+ PrivilegedOperationExecutor privilegedOperationExecutor =
+ PrivilegedOperationExecutor.getInstance(conf);
+
+ defaultLinuxContainerRuntime = new DefaultLinuxContainerRuntime(
+ privilegedOperationExecutor);
+ defaultLinuxContainerRuntime.initialize(conf);
+ dockerLinuxContainerRuntime = new DockerLinuxContainerRuntime(
+ privilegedOperationExecutor);
+ dockerLinuxContainerRuntime.initialize(conf);
+ }
+
+ private LinuxContainerRuntime pickContainerRuntime(Container container) {
+ Map<String, String> env = container.getLaunchContext().getEnvironment();
+ LinuxContainerRuntime runtime;
+
+ if (DockerLinuxContainerRuntime.isDockerContainerRequested(env)){
+ runtime = dockerLinuxContainerRuntime;
+ } else {
+ runtime = defaultLinuxContainerRuntime;
+ }
+
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Using container runtime: " + runtime.getClass()
+ .getSimpleName());
+ }
+
+ return runtime;
+ }
+
+ @Override
+ public void prepareContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ LinuxContainerRuntime runtime = pickContainerRuntime(container);
+
+ runtime.prepareContainer(ctx);
+ }
+
+ @Override
+ public void launchContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ LinuxContainerRuntime runtime = pickContainerRuntime(container);
+
+ runtime.launchContainer(ctx);
+ }
+
+ @Override
+ public void signalContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ LinuxContainerRuntime runtime = pickContainerRuntime(container);
+
+ runtime.signalContainer(ctx);
+ }
+
+ @Override
+ public void reapContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ LinuxContainerRuntime runtime = pickContainerRuntime(container);
+
+ runtime.reapContainer(ctx);
+ }
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DockerLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DockerLinuxContainerRuntime.java
new file mode 100644
index 0000000000000..2430a7878e82f
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DockerLinuxContainerRuntime.java
@@ -0,0 +1,273 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandler;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerModule;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerClient;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerRunCommand;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext;
+
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*;
+
[email protected]
[email protected]
+public class DockerLinuxContainerRuntime implements LinuxContainerRuntime {
+ private static final Log LOG = LogFactory.getLog(
+ DockerLinuxContainerRuntime.class);
+
+ @InterfaceAudience.Private
+ public static final String ENV_DOCKER_CONTAINER_IMAGE =
+ "YARN_CONTAINER_RUNTIME_DOCKER_IMAGE";
+ @InterfaceAudience.Private
+ public static final String ENV_DOCKER_CONTAINER_IMAGE_FILE =
+ "YARN_CONTAINER_RUNTIME_DOCKER_IMAGE_FILE";
+ @InterfaceAudience.Private
+ public static final String ENV_DOCKER_CONTAINER_RUN_OVERRIDE_DISABLE =
+ "YARN_CONTAINER_RUNTIME_DOCKER_RUN_OVERRIDE_DISABLE";
+
+
+ private Configuration conf;
+ private DockerClient dockerClient;
+ private PrivilegedOperationExecutor privilegedOperationExecutor;
+
+ public static boolean isDockerContainerRequested(
+ Map<String, String> env) {
+ if (env == null) {
+ return false;
+ }
+
+ String type = env.get(ContainerRuntimeConstants.ENV_CONTAINER_TYPE);
+
+ return type != null && type.equals("docker");
+ }
+
+ public DockerLinuxContainerRuntime(PrivilegedOperationExecutor
+ privilegedOperationExecutor) {
+ this.privilegedOperationExecutor = privilegedOperationExecutor;
+ }
+
+ @Override
+ public void initialize(Configuration conf)
+ throws ContainerExecutionException {
+ this.conf = conf;
+ dockerClient = new DockerClient(conf);
+ }
+
+ @Override
+ public void prepareContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+
+ }
+
+ public void addCGroupParentIfRequired(String resourcesOptions,
+ String containerIdStr, DockerRunCommand runCommand)
+ throws ContainerExecutionException {
+ if (resourcesOptions.equals(
+ (PrivilegedOperation.CGROUP_ARG_PREFIX + PrivilegedOperation
+ .CGROUP_ARG_NO_TASKS))) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("no resource restrictions specified. not using docker's "
+ + "cgroup options");
+ }
+ } else {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("using docker's cgroups options");
+ }
+
+ try {
+ CGroupsHandler cGroupsHandler = ResourceHandlerModule
+ .getCGroupsHandler(conf);
+ String cGroupPath = "/" + cGroupsHandler.getRelativePathForCGroup(
+ containerIdStr);
+
+ if (LOG.isInfoEnabled()) {
+ LOG.info("using cgroup parent: " + cGroupPath);
+ }
+
+ runCommand.setCGroupParent(cGroupPath);
+ } catch (ResourceHandlerException e) {
+ LOG.warn("unable to use cgroups handler. Exception: ", e);
+ throw new ContainerExecutionException(e);
+ }
+ }
+ }
+
+
+ @Override
+ public void launchContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ Map<String, String> environment = container.getLaunchContext()
+ .getEnvironment();
+ String imageName = environment.get(ENV_DOCKER_CONTAINER_IMAGE);
+
+ if (imageName == null) {
+ throw new ContainerExecutionException(ENV_DOCKER_CONTAINER_IMAGE
+ + " not set!");
+ }
+
+ String containerIdStr = container.getContainerId().toString();
+ String runAsUser = ctx.getExecutionAttribute(RUN_AS_USER);
+ Path containerWorkDir = ctx.getExecutionAttribute(CONTAINER_WORK_DIR);
+ //List<String> -> stored as List -> fetched/converted to List<String>
+ //we can't do better here thanks to type-erasure
+ @SuppressWarnings("unchecked")
+ List<String> localDirs = ctx.getExecutionAttribute(LOCAL_DIRS);
+ @SuppressWarnings("unchecked")
+ List<String> logDirs = ctx.getExecutionAttribute(LOG_DIRS);
+ @SuppressWarnings("unchecked")
+ DockerRunCommand runCommand = new DockerRunCommand(containerIdStr,
+ runAsUser, imageName)
+ .detachOnRun()
+ .setContainerWorkDir(containerWorkDir.toString())
+ .setNetworkType("host")
+ .addMountLocation("/etc/passwd", "/etc/password:ro");
+ List<String> allDirs = new ArrayList<>(localDirs);
+
+ allDirs.add(containerWorkDir.toString());
+ allDirs.addAll(logDirs);
+ for (String dir: allDirs) {
+ runCommand.addMountLocation(dir, dir);
+ }
+
+ String resourcesOpts = ctx.getExecutionAttribute(RESOURCES_OPTIONS);
+
+ /** Disabling docker's cgroup parent support for the time being. Docker
+ * needs to use a more recent libcontainer that supports net_cls. In
+ * addition we also need to revisit current cgroup creation in YARN.
+ */
+ //addCGroupParentIfRequired(resourcesOpts, containerIdStr, runCommand);
+
+ Path nmPrivateContainerScriptPath = ctx.getExecutionAttribute(
+ NM_PRIVATE_CONTAINER_SCRIPT_PATH);
+
+ String disableOverride = environment.get(
+ ENV_DOCKER_CONTAINER_RUN_OVERRIDE_DISABLE);
+
+ if (disableOverride != null && disableOverride.equals("true")) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("command override disabled");
+ }
+ } else {
+ List<String> overrideCommands = new ArrayList<>();
+ Path launchDst =
+ new Path(containerWorkDir, ContainerLaunch.CONTAINER_SCRIPT);
+
+ overrideCommands.add("bash");
+ overrideCommands.add(launchDst.toUri().getPath());
+ runCommand.setOverrideCommandWithArgs(overrideCommands);
+ }
+
+ String commandFile = dockerClient.writeCommandToTempFile(runCommand,
+ containerIdStr);
+ PrivilegedOperation launchOp = new PrivilegedOperation(
+ PrivilegedOperation.OperationType.LAUNCH_DOCKER_CONTAINER, (String)
+ null);
+
+ launchOp.appendArgs(runAsUser, ctx.getExecutionAttribute(USER),
+ Integer.toString(PrivilegedOperation
+ .RunAsUserCommand.LAUNCH_DOCKER_CONTAINER.getValue()),
+ ctx.getExecutionAttribute(APPID),
+ containerIdStr, containerWorkDir.toString(),
+ nmPrivateContainerScriptPath.toUri().getPath(),
+ ctx.getExecutionAttribute(NM_PRIVATE_TOKENS_PATH).toUri().getPath(),
+ ctx.getExecutionAttribute(PID_FILE_PATH).toString(),
+ StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
+ localDirs),
+ StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR,
+ logDirs),
+ commandFile,
+ resourcesOpts);
+
+ String tcCommandFile = ctx.getExecutionAttribute(TC_COMMAND_FILE);
+
+ if (tcCommandFile != null) {
+ launchOp.appendArgs(tcCommandFile);
+ }
+
+ try {
+ privilegedOperationExecutor.executePrivilegedOperation(null,
+ launchOp, null, container.getLaunchContext().getEnvironment(),
+ false);
+ } catch (PrivilegedOperationException e) {
+ LOG.warn("Launch container failed. Exception: ", e);
+
+ throw new ContainerExecutionException("Launch container failed", e
+ .getExitCode(), e.getOutput(), e.getErrorOutput());
+ }
+ }
+
+ @Override
+ public void signalContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+ Container container = ctx.getContainer();
+ PrivilegedOperation signalOp = new PrivilegedOperation(
+ PrivilegedOperation.OperationType.SIGNAL_CONTAINER, (String) null);
+
+ signalOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER),
+ ctx.getExecutionAttribute(USER),
+ Integer.toString(PrivilegedOperation
+ .RunAsUserCommand.SIGNAL_CONTAINER.getValue()),
+ ctx.getExecutionAttribute(PID),
+ Integer.toString(ctx.getExecutionAttribute(SIGNAL).getValue()));
+
+ try {
+ PrivilegedOperationExecutor executor = PrivilegedOperationExecutor
+ .getInstance(conf);
+
+ executor.executePrivilegedOperation(null,
+ signalOp, null, container.getLaunchContext().getEnvironment(),
+ false);
+ } catch (PrivilegedOperationException e) {
+ LOG.warn("Signal container failed. Exception: ", e);
+
+ throw new ContainerExecutionException("Signal container failed", e
+ .getExitCode(), e.getOutput(), e.getErrorOutput());
+ }
+ }
+
+ @Override
+ public void reapContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException {
+
+ }
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntime.java
new file mode 100644
index 0000000000000..38aea9d7ba899
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntime.java
@@ -0,0 +1,38 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntime;
+
+/** Linux-specific container runtime implementations must implement this
+ * interface.
+ */
+
[email protected]
[email protected]
+public interface LinuxContainerRuntime extends ContainerRuntime {
+ void initialize(Configuration conf) throws ContainerExecutionException;
+}
+
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntimeConstants.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntimeConstants.java
new file mode 100644
index 0000000000000..d2069a9356697
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntimeConstants.java
@@ -0,0 +1,69 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime;
+
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext.Attribute;
+
+import java.util.List;
+import java.util.Map;
+
+public final class LinuxContainerRuntimeConstants {
+ private LinuxContainerRuntimeConstants() {
+ }
+
+ public static final Attribute<Map> LOCALIZED_RESOURCES = Attribute
+ .attribute(Map.class, "localized_resources");
+ public static final Attribute<List> CONTAINER_LAUNCH_PREFIX_COMMANDS =
+ Attribute.attribute(List.class, "container_launch_prefix_commands");
+ public static final Attribute<String> RUN_AS_USER =
+ Attribute.attribute(String.class, "run_as_user");
+ public static final Attribute<String> USER = Attribute.attribute(String.class,
+ "user");
+ public static final Attribute<String> APPID =
+ Attribute.attribute(String.class, "appid");
+ public static final Attribute<String> CONTAINER_ID_STR = Attribute
+ .attribute(String.class, "container_id_str");
+ public static final Attribute<Path> CONTAINER_WORK_DIR = Attribute
+ .attribute(Path.class, "container_work_dir");
+ public static final Attribute<Path> NM_PRIVATE_CONTAINER_SCRIPT_PATH =
+ Attribute.attribute(Path.class, "nm_private_container_script_path");
+ public static final Attribute<Path> NM_PRIVATE_TOKENS_PATH = Attribute
+ .attribute(Path.class, "nm_private_tokens_path");
+ public static final Attribute<Path> PID_FILE_PATH = Attribute.attribute(
+ Path.class, "pid_file_path");
+ public static final Attribute<List> LOCAL_DIRS = Attribute.attribute(
+ List.class, "local_dirs");
+ public static final Attribute<List> LOG_DIRS = Attribute.attribute(
+ List.class, "log_dirs");
+ public static final Attribute<String> RESOURCES_OPTIONS = Attribute.attribute(
+ String.class, "resources_options");
+ public static final Attribute<String> TC_COMMAND_FILE = Attribute.attribute(
+ String.class, "tc_command_file");
+ public static final Attribute<String> CGROUP_RELATIVE_PATH = Attribute
+ .attribute(String.class, "cgroup_relative_path");
+
+ public static final Attribute<String> PID = Attribute.attribute(
+ String.class, "pid");
+ public static final Attribute<ContainerExecutor.Signal> SIGNAL = Attribute
+ .attribute(ContainerExecutor.Signal.class, "signal");
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerClient.java
new file mode 100644
index 0000000000000..faf955f8eea61
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerClient.java
@@ -0,0 +1,82 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.Writer;
+
[email protected]
[email protected]
+public final class DockerClient {
+ private static final Log LOG = LogFactory.getLog(DockerClient.class);
+ private static final String TMP_FILE_PREFIX = "docker.";
+ private static final String TMP_FILE_SUFFIX = ".cmd";
+ private final String tmpDirPath;
+
+ public DockerClient(Configuration conf) throws ContainerExecutionException {
+
+ String tmpDirBase = conf.get("hadoop.tmp.dir");
+ if (tmpDirBase == null) {
+ throw new ContainerExecutionException("hadoop.tmp.dir not set!");
+ }
+ tmpDirPath = tmpDirBase + "/nm-docker-cmds";
+
+ File tmpDir = new File(tmpDirPath);
+ if (!(tmpDir.exists() || tmpDir.mkdirs())) {
+ LOG.warn("Unable to create directory: " + tmpDirPath);
+ throw new ContainerExecutionException("Unable to create directory: " +
+ tmpDirPath);
+ }
+ }
+
+ public String writeCommandToTempFile(DockerCommand cmd, String filePrefix)
+ throws ContainerExecutionException {
+ File dockerCommandFile = null;
+ try {
+ dockerCommandFile = File.createTempFile(TMP_FILE_PREFIX + filePrefix,
+ TMP_FILE_SUFFIX, new
+ File(tmpDirPath));
+
+ Writer writer = new OutputStreamWriter(new FileOutputStream(dockerCommandFile),
+ "UTF-8");
+ PrintWriter printWriter = new PrintWriter(writer);
+ printWriter.print(cmd.getCommandWithArguments());
+ printWriter.close();
+
+ return dockerCommandFile.getAbsolutePath();
+ } catch (IOException e) {
+ LOG.warn("Unable to write docker command to temporary file!");
+ throw new ContainerExecutionException(e);
+ }
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerCommand.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerCommand.java
new file mode 100644
index 0000000000000..3b76a5cca40ce
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerCommand.java
@@ -0,0 +1,66 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.util.StringUtils;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
[email protected]
[email protected]
+
+/** Represents a docker sub-command
+ * e.g 'run', 'load', 'inspect' etc.,
+ */
+
+public abstract class DockerCommand {
+ private final String command;
+ private final List<String> commandWithArguments;
+
+ protected DockerCommand(String command) {
+ this.command = command;
+ this.commandWithArguments = new ArrayList<>();
+ commandWithArguments.add(command);
+ }
+
+ /** Returns the docker sub-command string being used
+ * e.g 'run'
+ */
+ public final String getCommandOption() {
+ return this.command;
+ }
+
+ /** Add command commandWithArguments - this method is only meant for use by
+ * sub-classes
+ * @param arguments to be added
+ */
+ protected final void addCommandArguments(String... arguments) {
+ this.commandWithArguments.addAll(Arrays.asList(arguments));
+ }
+
+ public String getCommandWithArguments() {
+ return StringUtils.join(" ", commandWithArguments);
+ }
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerLoadCommand.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerLoadCommand.java
new file mode 100644
index 0000000000000..e4d92e08bc168
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerLoadCommand.java
@@ -0,0 +1,30 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker;
+
+public class DockerLoadCommand extends DockerCommand {
+ private static final String LOAD_COMMAND = "load";
+
+ public DockerLoadCommand(String localImageFile) {
+ super(LOAD_COMMAND);
+ super.addCommandArguments("--i=" + localImageFile);
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerRunCommand.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerRunCommand.java
new file mode 100644
index 0000000000000..f9a890e9d3041
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerRunCommand.java
@@ -0,0 +1,107 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker;
+
+import org.apache.hadoop.util.StringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class DockerRunCommand extends DockerCommand {
+ private static final String RUN_COMMAND = "run";
+ private final String image;
+ private List<String> overrrideCommandWithArgs;
+
+ /** The following are mandatory: */
+ public DockerRunCommand(String containerId, String user, String image) {
+ super(RUN_COMMAND);
+ super.addCommandArguments("--name=" + containerId, "--user=" + user);
+ this.image = image;
+ }
+
+ public DockerRunCommand removeContainerOnExit() {
+ super.addCommandArguments("--rm");
+ return this;
+ }
+
+ public DockerRunCommand detachOnRun() {
+ super.addCommandArguments("-d");
+ return this;
+ }
+
+ public DockerRunCommand setContainerWorkDir(String workdir) {
+ super.addCommandArguments("--workdir=" + workdir);
+ return this;
+ }
+
+ public DockerRunCommand setNetworkType(String type) {
+ super.addCommandArguments("--net=" + type);
+ return this;
+ }
+
+ public DockerRunCommand addMountLocation(String sourcePath, String
+ destinationPath) {
+ super.addCommandArguments("-v", sourcePath + ":" + destinationPath);
+ return this;
+ }
+
+ public DockerRunCommand setCGroupParent(String parentPath) {
+ super.addCommandArguments("--cgroup-parent=" + parentPath);
+ return this;
+ }
+
+ public DockerRunCommand addDevice(String sourceDevice, String
+ destinationDevice) {
+ super.addCommandArguments("--device=" + sourceDevice + ":" +
+ destinationDevice);
+ return this;
+ }
+
+ public DockerRunCommand enableDetach() {
+ super.addCommandArguments("--detach=true");
+ return this;
+ }
+
+ public DockerRunCommand disableDetach() {
+ super.addCommandArguments("--detach=false");
+ return this;
+ }
+
+ public DockerRunCommand setOverrideCommandWithArgs(
+ List<String> overrideCommandWithArgs) {
+ this.overrrideCommandWithArgs = overrideCommandWithArgs;
+ return this;
+ }
+
+ @Override
+ public String getCommandWithArguments() {
+ List<String> argList = new ArrayList<>();
+
+ argList.add(super.getCommandWithArguments());
+ argList.add(image);
+
+ if (overrrideCommandWithArgs != null) {
+ argList.addAll(overrrideCommandWithArgs);
+ }
+
+ return StringUtils.join(" ", argList);
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerExecutionException.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerExecutionException.java
new file mode 100644
index 0000000000000..1fbece2205e27
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerExecutionException.java
@@ -0,0 +1,85 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.yarn.exceptions.YarnException;
+
+/** Exception caused in a container runtime impl. 'Runtime' is not used in
+ * the class name to avoid confusion with a java RuntimeException
+ */
+
[email protected]
[email protected]
+public class ContainerExecutionException extends YarnException {
+ private static final long serialVersionUID = 1L;
+ private static final Integer EXIT_CODE_UNSET = -1;
+ private static final String OUTPUT_UNSET = "<unknown>";
+
+ private Integer exitCode;
+ private String output;
+ private String errorOutput;
+
+ public ContainerExecutionException(String message) {
+ super(message);
+ exitCode = EXIT_CODE_UNSET;
+ output = OUTPUT_UNSET;
+ errorOutput = OUTPUT_UNSET;
+ }
+
+ public ContainerExecutionException(Throwable throwable) {
+ super(throwable);
+ exitCode = EXIT_CODE_UNSET;
+ output = OUTPUT_UNSET;
+ errorOutput = OUTPUT_UNSET;
+ }
+
+
+ public ContainerExecutionException(String message, Integer exitCode, String
+ output, String errorOutput) {
+ super(message);
+ this.exitCode = exitCode;
+ this.output = output;
+ this.errorOutput = errorOutput;
+ }
+
+ public ContainerExecutionException(Throwable cause, Integer exitCode, String
+ output, String errorOutput) {
+ super(cause);
+ this.exitCode = exitCode;
+ this.output = output;
+ this.errorOutput = errorOutput;
+ }
+
+ public Integer getExitCode() {
+ return exitCode;
+ }
+
+ public String getOutput() {
+ return output;
+ }
+
+ public String getErrorOutput() {
+ return errorOutput;
+ }
+
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntime.java
new file mode 100644
index 0000000000000..e05f3fcb12c52
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntime.java
@@ -0,0 +1,50 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+
+/** An abstraction for various container runtime implementations. Examples
+ * include Process Tree, Docker, Appc runtimes etc., These implementations
+ * are meant for low-level OS container support - dependencies on
+ * higher-level nodemananger constructs should be avoided.
+ */
+
[email protected]
[email protected]
+public interface ContainerRuntime {
+ /** Prepare a container to be ready for launch */
+ void prepareContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException;
+
+ /** Launch a container. */
+ void launchContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException;
+
+ /** Signal a container - request to terminate, status check etc., */
+ void signalContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException;
+
+ /** Any container cleanup that may be required. */
+ void reapContainer(ContainerRuntimeContext ctx)
+ throws ContainerExecutionException;
+}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeConstants.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeConstants.java
new file mode 100644
index 0000000000000..4473856a2d6ef
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeConstants.java
@@ -0,0 +1,33 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime;
+
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+
+public class ContainerRuntimeConstants {
+
+ /* Switch container runtimes. Work in progress: These
+ * parameters may be changed/removed in the future. */
+
+ @Private
+ public static final String ENV_CONTAINER_TYPE =
+ "YARN_CONTAINER_RUNTIME_TYPE";
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeContext.java
new file mode 100644
index 0000000000000..4194b99300683
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeContext.java
@@ -0,0 +1,105 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
[email protected]
[email protected]
+public final class ContainerRuntimeContext {
+ private final Container container;
+ private final Map<Attribute<?>, Object> executionAttributes;
+
+ /** An attribute class that attempts to provide better type safety as compared
+ * with using a map of string to object.
+ * @param <T>
+ */
+ public static final class Attribute<T> {
+ private final Class<T> valueClass;
+ private final String id;
+
+ private Attribute(Class<T> valueClass, String id) {
+ this.valueClass = valueClass;
+ this.id = id;
+ }
+
+ @Override
+ public int hashCode() {
+ return valueClass.hashCode() + 31 * id.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null || !(obj instanceof Attribute)){
+ return false;
+ }
+
+ Attribute<?> attribute = (Attribute<?>) obj;
+
+ return valueClass.equals(attribute.valueClass) && id.equals(attribute.id);
+ }
+ public static <T> Attribute<T> attribute(Class<T> valueClass, String id) {
+ return new Attribute<T>(valueClass, id);
+ }
+ }
+
+ public static final class Builder {
+ private final Container container;
+ private Map<Attribute<?>, Object> executionAttributes;
+
+ public Builder(Container container) {
+ executionAttributes = new HashMap<>();
+ this.container = container;
+ }
+
+ public <E> Builder setExecutionAttribute(Attribute<E> attribute, E value) {
+ this.executionAttributes.put(attribute, attribute.valueClass.cast(value));
+ return this;
+ }
+
+ public ContainerRuntimeContext build() {
+ return new ContainerRuntimeContext(this);
+ }
+ }
+
+ private ContainerRuntimeContext(Builder builder) {
+ this.container = builder.container;
+ this.executionAttributes = builder.executionAttributes;
+ }
+
+ public Container getContainer() {
+ return this.container;
+ }
+
+ public Map<Attribute<?>, Object> getExecutionAttributes() {
+ return Collections.unmodifiableMap(this.executionAttributes);
+ }
+
+ public <E> E getExecutionAttribute(Attribute<E> attribute) {
+ return attribute.valueClass.cast(executionAttributes.get(attribute));
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java
index acadae9e957c1..43113efb88dd6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java
@@ -22,6 +22,7 @@
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
/**
* Encapsulates information required for container liveness checks.
@@ -30,16 +31,23 @@
@InterfaceAudience.Private
@InterfaceStability.Unstable
public final class ContainerLivenessContext {
+ private final Container container;
private final String user;
private final String pid;
public static final class Builder {
+ private Container container;
private String user;
private String pid;
public Builder() {
}
+ public Builder setContainer(Container container) {
+ this.container = container;
+ return this;
+ }
+
public Builder setUser(String user) {
this.user = user;
return this;
@@ -56,10 +64,15 @@ public ContainerLivenessContext build() {
}
private ContainerLivenessContext(Builder builder) {
+ this.container = builder.container;
this.user = builder.user;
this.pid = builder.pid;
}
+ public Container getContainer() {
+ return this.container;
+ }
+
public String getUser() {
return this.user;
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java
index 8adcab7bf4160..d93cdafd768e2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java
@@ -23,6 +23,7 @@
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.yarn.api.records.ContainerId;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
/**
* Encapsulates information required for container reacquisition.
@@ -31,16 +32,23 @@
@InterfaceAudience.Private
@InterfaceStability.Unstable
public final class ContainerReacquisitionContext {
+ private final Container container;
private final String user;
private final ContainerId containerId;
public static final class Builder {
+ private Container container;
private String user;
private ContainerId containerId;
public Builder() {
}
+ public Builder setContainer(Container container) {
+ this.container = container;
+ return this;
+ }
+
public Builder setUser(String user) {
this.user = user;
return this;
@@ -57,10 +65,15 @@ public ContainerReacquisitionContext build() {
}
private ContainerReacquisitionContext(Builder builder) {
+ this.container = builder.container;
this.user = builder.user;
this.containerId = builder.containerId;
}
+ public Container getContainer() {
+ return this.container;
+ }
+
public String getUser() {
return this.user;
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java
index cc40af534291a..56b571bb23cc1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java
@@ -23,6 +23,7 @@
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.Signal;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
/**
* Encapsulates information required for container signaling.
@@ -31,11 +32,13 @@
@InterfaceAudience.Private
@InterfaceStability.Unstable
public final class ContainerSignalContext {
+ private final Container container;
private final String user;
private final String pid;
private final Signal signal;
public static final class Builder {
+ private Container container;
private String user;
private String pid;
private Signal signal;
@@ -43,6 +46,11 @@ public static final class Builder {
public Builder() {
}
+ public Builder setContainer(Container container) {
+ this.container = container;
+ return this;
+ }
+
public Builder setUser(String user) {
this.user = user;
return this;
@@ -64,11 +72,16 @@ public ContainerSignalContext build() {
}
private ContainerSignalContext(Builder builder) {
+ this.container = builder.container;
this.user = builder.user;
this.pid = builder.pid;
this.signal = builder.signal;
}
+ public Container getContainer() {
+ return this.container;
+ }
+
public String getUser() {
return this.user;
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java
index 7dfff02626af4..ffcc519f8b7ba 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java
@@ -25,7 +25,9 @@
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import java.util.Collections;
import java.util.List;
+import java.util.Map;
/**
* Encapsulates information required for starting/launching containers.
@@ -35,6 +37,7 @@
@InterfaceStability.Unstable
public final class ContainerStartContext {
private final Container container;
+ private final Map<Path, List<String>> localizedResources;
private final Path nmPrivateContainerScriptPath;
private final Path nmPrivateTokensPath;
private final String user;
@@ -45,6 +48,7 @@ public final class ContainerStartContext {
public static final class Builder {
private Container container;
+ private Map<Path, List<String>> localizedResources;
private Path nmPrivateContainerScriptPath;
private Path nmPrivateTokensPath;
private String user;
@@ -61,6 +65,12 @@ public Builder setContainer(Container container) {
return this;
}
+ public Builder setLocalizedResources(Map<Path,
+ List<String>> localizedResources) {
+ this.localizedResources = localizedResources;
+ return this;
+ }
+
public Builder setNmPrivateContainerScriptPath(
Path nmPrivateContainerScriptPath) {
this.nmPrivateContainerScriptPath = nmPrivateContainerScriptPath;
@@ -104,6 +114,7 @@ public ContainerStartContext build() {
private ContainerStartContext(Builder builder) {
this.container = builder.container;
+ this.localizedResources = builder.localizedResources;
this.nmPrivateContainerScriptPath = builder.nmPrivateContainerScriptPath;
this.nmPrivateTokensPath = builder.nmPrivateTokensPath;
this.user = builder.user;
@@ -117,6 +128,14 @@ public Container getContainer() {
return this.container;
}
+ public Map<Path, List<String>> getLocalizedResources() {
+ if (this.localizedResources != null) {
+ return Collections.unmodifiableMap(this.localizedResources);
+ } else {
+ return null;
+ }
+ }
+
public Path getNmPrivateContainerScriptPath() {
return this.nmPrivateContainerScriptPath;
}
@@ -138,10 +157,10 @@ public Path getContainerWorkDir() {
}
public List<String> getLocalDirs() {
- return this.localDirs;
+ return Collections.unmodifiableList(this.localDirs);
}
public List<String> getLogDirs() {
- return this.logDirs;
+ return Collections.unmodifiableList(this.logDirs);
}
}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
index 30c0392b69914..0ef788bcd9819 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
@@ -32,6 +32,8 @@
import java.io.IOException;
import java.io.LineNumberReader;
import java.net.InetSocketAddress;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -50,6 +52,10 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerDiagnosticsUpdateEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.DefaultLinuxContainerRuntime;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntime;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext;
import org.apache.hadoop.yarn.server.nodemanager.executor.DeletionAsUserContext;
@@ -61,11 +67,19 @@
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
+
public class TestLinuxContainerExecutorWithMocks {
private static final Log LOG = LogFactory
.getLog(TestLinuxContainerExecutorWithMocks.class);
+ private static final String MOCK_EXECUTOR =
+ "./src/test/resources/mock-container-executor";
+ private static final String MOCK_EXECUTOR_WITH_ERROR =
+ "./src/test/resources/mock-container-executer-with-error";
+
+ private String tmpMockExecutor;
private LinuxContainerExecutor mockExec = null;
private final File mockParamFile = new File("./params.txt");
private LocalDirsHandlerService dirsHandler;
@@ -88,20 +102,42 @@ private List<String> readMockParams() throws IOException {
reader.close();
return ret;
}
-
+
+ private void setupMockExecutor(String executorPath, Configuration conf)
+ throws IOException {
+ //we'll always use the tmpMockExecutor - since
+ // PrivilegedOperationExecutor can only be initialized once.
+
+ Files.copy(Paths.get(executorPath), Paths.get(tmpMockExecutor),
+ REPLACE_EXISTING);
+
+ File executor = new File(tmpMockExecutor);
+
+ if (!FileUtil.canExecute(executor)) {
+ FileUtil.setExecutable(executor, true);
+ }
+ String executorAbsolutePath = executor.getAbsolutePath();
+ conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH,
+ executorAbsolutePath);
+ }
+
@Before
- public void setup() {
+ public void setup() throws IOException, ContainerExecutionException {
assumeTrue(!Path.WINDOWS);
- File f = new File("./src/test/resources/mock-container-executor");
- if(!FileUtil.canExecute(f)) {
- FileUtil.setExecutable(f, true);
- }
- String executorPath = f.getAbsolutePath();
+
+ tmpMockExecutor = System.getProperty("test.build.data") +
+ "/tmp-mock-container-executor";
+
Configuration conf = new Configuration();
- conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath);
- mockExec = new LinuxContainerExecutor();
+ LinuxContainerRuntime linuxContainerRuntime;
+
+ setupMockExecutor(MOCK_EXECUTOR, conf);
+ linuxContainerRuntime = new DefaultLinuxContainerRuntime(
+ PrivilegedOperationExecutor.getInstance(conf));
dirsHandler = new LocalDirsHandlerService();
dirsHandler.init(conf);
+ linuxContainerRuntime.initialize(conf);
+ mockExec = new LinuxContainerExecutor(linuxContainerRuntime);
mockExec.setConf(conf);
}
@@ -114,7 +150,7 @@ public void tearDown() {
public void testContainerLaunch() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
- LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue());
+ PrivilegedOperation.RunAsUserCommand.LAUNCH_CONTAINER.getValue());
String appId = "APP_ID";
String containerId = "CONTAINER_ID";
Container container = mock(Container.class);
@@ -161,13 +197,8 @@ public void testContainerLaunch() throws IOException {
public void testContainerLaunchWithPriority() throws IOException {
// set the scheduler priority to make sure still works with nice -n prio
- File f = new File("./src/test/resources/mock-container-executor");
- if (!FileUtil.canExecute(f)) {
- FileUtil.setExecutable(f, true);
- }
- String executorPath = f.getAbsolutePath();
Configuration conf = new Configuration();
- conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath);
+ setupMockExecutor(MOCK_EXECUTOR, conf);
conf.setInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY, 2);
mockExec.setConf(conf);
@@ -231,20 +262,25 @@ public void testStartLocalizer() throws IOException {
@Test
- public void testContainerLaunchError() throws IOException {
+ public void testContainerLaunchError()
+ throws IOException, ContainerExecutionException {
// reinitialize executer
- File f = new File("./src/test/resources/mock-container-executer-with-error");
- if (!FileUtil.canExecute(f)) {
- FileUtil.setExecutable(f, true);
- }
- String executorPath = f.getAbsolutePath();
Configuration conf = new Configuration();
- conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath);
+ setupMockExecutor(MOCK_EXECUTOR_WITH_ERROR, conf);
conf.set(YarnConfiguration.NM_LOCAL_DIRS, "file:///bin/echo");
conf.set(YarnConfiguration.NM_LOG_DIRS, "file:///dev/null");
- mockExec = spy(new LinuxContainerExecutor());
+
+ LinuxContainerExecutor exec;
+ LinuxContainerRuntime linuxContainerRuntime = new
+ DefaultLinuxContainerRuntime(PrivilegedOperationExecutor.getInstance
+ (conf));
+
+ linuxContainerRuntime.initialize(conf);
+ exec = new LinuxContainerExecutor(linuxContainerRuntime);
+
+ mockExec = spy(exec);
doAnswer(
new Answer() {
@Override
@@ -263,7 +299,7 @@ public Object answer(InvocationOnMock invocationOnMock)
String appSubmitter = "nobody";
String cmd = String
- .valueOf(LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue());
+ .valueOf(PrivilegedOperation.RunAsUserCommand.LAUNCH_CONTAINER.getValue());
String appId = "APP_ID";
String containerId = "CONTAINER_ID";
Container container = mock(Container.class);
@@ -299,6 +335,7 @@ public Object answer(InvocationOnMock invocationOnMock)
Path pidFile = new Path(workDir, "pid.txt");
mockExec.activateContainer(cId, pidFile);
+
int ret = mockExec.launchContainer(new ContainerStartContext.Builder()
.setContainer(container)
.setNmPrivateContainerScriptPath(scriptPath)
@@ -330,16 +367,23 @@ public void testInit() throws Exception {
}
-
@Test
public void testContainerKill() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
- LinuxContainerExecutor.Commands.SIGNAL_CONTAINER.getValue());
+ PrivilegedOperation.RunAsUserCommand.SIGNAL_CONTAINER.getValue());
ContainerExecutor.Signal signal = ContainerExecutor.Signal.QUIT;
String sigVal = String.valueOf(signal.getValue());
-
+
+ Container container = mock(Container.class);
+ ContainerId cId = mock(ContainerId.class);
+ ContainerLaunchContext context = mock(ContainerLaunchContext.class);
+
+ when(container.getContainerId()).thenReturn(cId);
+ when(container.getLaunchContext()).thenReturn(context);
+
mockExec.signalContainer(new ContainerSignalContext.Builder()
+ .setContainer(container)
.setUser(appSubmitter)
.setPid("1000")
.setSignal(signal)
@@ -353,7 +397,7 @@ public void testContainerKill() throws IOException {
public void testDeleteAsUser() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
- LinuxContainerExecutor.Commands.DELETE_AS_USER.getValue());
+ PrivilegedOperation.RunAsUserCommand.DELETE_AS_USER.getValue());
Path dir = new Path("/tmp/testdir");
Path testFile = new Path("testfile");
Path baseDir0 = new Path("/grid/0/BaseDir");
@@ -395,14 +439,9 @@ public void testDeleteAsUser() throws IOException {
Arrays.asList(YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER,
appSubmitter, cmd, "", baseDir0.toString(), baseDir1.toString()),
readMockParams());
-
- File f = new File("./src/test/resources/mock-container-executer-with-error");
- if (!FileUtil.canExecute(f)) {
- FileUtil.setExecutable(f, true);
- }
- String executorPath = f.getAbsolutePath();
+ ;
Configuration conf = new Configuration();
- conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath);
+ setupMockExecutor(MOCK_EXECUTOR, conf);
mockExec.setConf(conf);
mockExec.deleteAsUser(new DeletionAsUserContext.Builder()
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java
index 8f297ede75a75..849dbabf20ae2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java
@@ -118,7 +118,7 @@ public void testExecutionCommand() {
PrivilegedOperationExecutor exec = PrivilegedOperationExecutor
.getInstance(confWithExecutorPath);
PrivilegedOperation op = new PrivilegedOperation(PrivilegedOperation
- .OperationType.LAUNCH_CONTAINER, (String) null);
+ .OperationType.TC_MODIFY_STATE, (String) null);
String[] cmdArray = exec.getPrivilegedOperationExecutionCommand(null, op);
//No arguments added - so the resulting array should consist of
@@ -127,10 +127,8 @@ public void testExecutionCommand() {
Assert.assertEquals(customExecutorPath, cmdArray[0]);
Assert.assertEquals(op.getOperationType().getOption(), cmdArray[1]);
- //other (dummy) arguments to launch container
- String[] additionalArgs = { "test_user", "yarn", "1", "app_01",
- "container_01", "workdir", "launch_script.sh", "tokens", "pidfile",
- "nm-local-dirs", "nm-log-dirs", "resource-spec" };
+ //other (dummy) arguments to tc modify state
+ String[] additionalArgs = { "cmd_file_1", "cmd_file_2", "cmd_file_3"};
op.appendArgs(additionalArgs);
cmdArray = exec.getPrivilegedOperationExecutionCommand(null, op);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java
new file mode 100644
index 0000000000000..31ed4963341fb
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java
@@ -0,0 +1,219 @@
+/*
+ * *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * /
+ */
+
+package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
+import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+public class TestDockerContainerRuntime {
+ private Configuration conf;
+ PrivilegedOperationExecutor mockExecutor;
+ String containerId;
+ Container container;
+ ContainerId cId;
+ ContainerLaunchContext context;
+ HashMap<String, String> env;
+ String image;
+ String runAsUser;
+ String user;
+ String appId;
+ String containerIdStr = containerId;
+ Path containerWorkDir;
+ Path nmPrivateContainerScriptPath;
+ Path nmPrivateTokensPath;
+ Path pidFilePath;
+ List<String> localDirs;
+ List<String> logDirs;
+ String resourcesOptions;
+
+ @Before
+ public void setup() {
+ String tmpPath = new StringBuffer(System.getProperty("test.build.data"))
+ .append
+ ('/').append("hadoop.tmp.dir").toString();
+
+ conf = new Configuration();
+ conf.set("hadoop.tmp.dir", tmpPath);
+
+ mockExecutor = Mockito
+ .mock(PrivilegedOperationExecutor.class);
+ containerId = "container_id";
+ container = mock(Container.class);
+ cId = mock(ContainerId.class);
+ context = mock(ContainerLaunchContext.class);
+ env = new HashMap<String, String>();
+ image = "busybox:latest";
+
+ env.put(DockerLinuxContainerRuntime.ENV_DOCKER_CONTAINER_IMAGE, image);
+ when(container.getContainerId()).thenReturn(cId);
+ when(cId.toString()).thenReturn(containerId);
+ when(container.getLaunchContext()).thenReturn(context);
+ when(context.getEnvironment()).thenReturn(env);
+
+ runAsUser = "run_as_user";
+ user = "user";
+ appId = "app_id";
+ containerIdStr = containerId;
+ containerWorkDir = new Path("/test_container_work_dir");
+ nmPrivateContainerScriptPath = new Path("/test_script_path");
+ nmPrivateTokensPath = new Path("/test_private_tokens_path");
+ pidFilePath = new Path("/test_pid_file_path");
+ localDirs = new ArrayList<>();
+ logDirs = new ArrayList<>();
+ resourcesOptions = "cgroups:none";
+
+ localDirs.add("/test_local_dir");
+ logDirs.add("/test_log_dir");
+ }
+
+ @Test
+ public void testSelectDockerContainerType() {
+ Map<String, String> envDockerType = new HashMap<>();
+ Map<String, String> envOtherType = new HashMap<>();
+
+ envDockerType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, "docker");
+ envOtherType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, "other");
+
+ Assert.assertEquals(false, DockerLinuxContainerRuntime
+ .isDockerContainerRequested(null));
+ Assert.assertEquals(true, DockerLinuxContainerRuntime
+ .isDockerContainerRequested(envDockerType));
+ Assert.assertEquals(false, DockerLinuxContainerRuntime
+ .isDockerContainerRequested(envOtherType));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testDockerContainerLaunch()
+ throws ContainerExecutionException, PrivilegedOperationException,
+ IOException {
+ DockerLinuxContainerRuntime runtime = new DockerLinuxContainerRuntime(
+ mockExecutor);
+ runtime.initialize(conf);
+
+ ContainerRuntimeContext.Builder builder = new ContainerRuntimeContext
+ .Builder(container);
+
+ builder.setExecutionAttribute(RUN_AS_USER, runAsUser)
+ .setExecutionAttribute(USER, user)
+ .setExecutionAttribute(APPID, appId)
+ .setExecutionAttribute(CONTAINER_ID_STR, containerIdStr)
+ .setExecutionAttribute(CONTAINER_WORK_DIR, containerWorkDir)
+ .setExecutionAttribute(NM_PRIVATE_CONTAINER_SCRIPT_PATH,
+ nmPrivateContainerScriptPath)
+ .setExecutionAttribute(NM_PRIVATE_TOKENS_PATH, nmPrivateTokensPath)
+ .setExecutionAttribute(PID_FILE_PATH, pidFilePath)
+ .setExecutionAttribute(LOCAL_DIRS, localDirs)
+ .setExecutionAttribute(LOG_DIRS, logDirs)
+ .setExecutionAttribute(RESOURCES_OPTIONS, resourcesOptions);
+
+ runtime.launchContainer(builder.build());
+
+ ArgumentCaptor<PrivilegedOperation> opCaptor = ArgumentCaptor.forClass(
+ PrivilegedOperation.class);
+
+ //single invocation expected
+ //due to type erasure + mocking, this verification requires a suppress
+ // warning annotation on the entire method
+ verify(mockExecutor, times(1))
+ .executePrivilegedOperation(anyList(), opCaptor.capture(), any(
+ File.class), any(Map.class), eq(false));
+
+ PrivilegedOperation op = opCaptor.getValue();
+
+ Assert.assertEquals(PrivilegedOperation.OperationType
+ .LAUNCH_DOCKER_CONTAINER, op.getOperationType());
+
+ List<String> args = op.getArguments();
+
+ //This invocation of container-executor should use 13 arguments in a
+ // specific order (sigh.)
+ Assert.assertEquals(13, args.size());
+
+ //verify arguments
+ Assert.assertEquals(runAsUser, args.get(0));
+ Assert.assertEquals(user, args.get(1));
+ Assert.assertEquals(Integer.toString(PrivilegedOperation.RunAsUserCommand
+ .LAUNCH_DOCKER_CONTAINER.getValue()), args.get(2));
+ Assert.assertEquals(appId, args.get(3));
+ Assert.assertEquals(containerId, args.get(4));
+ Assert.assertEquals(containerWorkDir.toString(), args.get(5));
+ Assert.assertEquals(nmPrivateContainerScriptPath.toUri()
+ .toString(), args.get(6));
+ Assert.assertEquals(nmPrivateTokensPath.toUri().getPath(), args.get(7));
+ Assert.assertEquals(pidFilePath.toString(), args.get(8));
+ Assert.assertEquals(localDirs.get(0), args.get(9));
+ Assert.assertEquals(logDirs.get(0), args.get(10));
+ Assert.assertEquals(resourcesOptions, args.get(12));
+
+ String dockerCommandFile = args.get(11);
+
+ //This is the expected docker invocation for this case
+ StringBuffer expectedCommandTemplate = new StringBuffer("run --name=%1$s ")
+ .append("--user=%2$s -d ")
+ .append("--workdir=%3$s ")
+ .append("--net=host -v /etc/passwd:/etc/password:ro ")
+ .append("-v %4$s:%4$s ")
+ .append("-v %5$s:%5$s ")
+ .append("-v %6$s:%6$s ")
+ .append("%7$s ")
+ .append("bash %8$s/launch_container.sh");
+
+ String expectedCommand = String.format(expectedCommandTemplate.toString(),
+ containerId, runAsUser, containerWorkDir, localDirs.get(0),
+ containerWorkDir, logDirs.get(0), image, containerWorkDir);
+
+ List<String> dockerCommands = Files.readAllLines(Paths.get
+ (dockerCommandFile), Charset.forName("UTF-8"));
+
+ Assert.assertEquals(1, dockerCommands.size());
+ Assert.assertEquals(expectedCommand, dockerCommands.get(0));
+ }
+}
|
91749f9c93f0589d0e93e215e068d6b039c2d26a
|
hbase
|
HBASE-10449 Wrong execution pool configuration in- HConnectionManager--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1563878 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
index 79ad7817833a..c467af298a0c 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
@@ -766,22 +766,27 @@ private ExecutorService getBatchPool() {
synchronized (this) {
if (batchPool == null) {
int maxThreads = conf.getInt("hbase.hconnection.threads.max", 256);
- int coreThreads = conf.getInt("hbase.hconnection.threads.core", 0);
+ int coreThreads = conf.getInt("hbase.hconnection.threads.core", 256);
if (maxThreads == 0) {
maxThreads = Runtime.getRuntime().availableProcessors() * 8;
}
- long keepAliveTime = conf.getLong("hbase.hconnection.threads.keepalivetime", 10);
+ if (coreThreads == 0) {
+ coreThreads = Runtime.getRuntime().availableProcessors() * 8;
+ }
+ long keepAliveTime = conf.getLong("hbase.hconnection.threads.keepalivetime", 60);
LinkedBlockingQueue<Runnable> workQueue =
new LinkedBlockingQueue<Runnable>(maxThreads *
conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS));
- this.batchPool = new ThreadPoolExecutor(
+ ThreadPoolExecutor tpe = new ThreadPoolExecutor(
coreThreads,
maxThreads,
keepAliveTime,
TimeUnit.SECONDS,
workQueue,
Threads.newDaemonThreadFactory(toString() + "-shared-"));
+ tpe.allowCoreThreadTimeOut(true);
+ this.batchPool = tpe;
}
this.cleanupPool = true;
}
|
b02e6dc996d3985a8a136f290c4a8810ce05aaab
|
elasticsearch
|
Migrating NodesInfo API to use plugins instead of- singular plugin--In order to be consistent (and because in 1.0 we switched from-parameter driven information to specifzing the metrics as part of the URI)-this patch moves from 'plugin' to 'plugins' in the Nodes Info API.-
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/docs/reference/cluster/nodes-info.asciidoc b/docs/reference/cluster/nodes-info.asciidoc
index 96b5fb5b9e3e9..61d8c1a5a6a1f 100644
--- a/docs/reference/cluster/nodes-info.asciidoc
+++ b/docs/reference/cluster/nodes-info.asciidoc
@@ -17,7 +17,7 @@ The second command selectively retrieves nodes information of only
By default, it just returns all attributes and core settings for a node.
It also allows to get only information on `settings`, `os`, `process`, `jvm`,
-`thread_pool`, `network`, `transport`, `http` and `plugin`:
+`thread_pool`, `network`, `transport`, `http` and `plugins`:
[source,js]
--------------------------------------------------
@@ -30,9 +30,9 @@ curl -XGET 'http://localhost:9200/_nodes/nodeId1,nodeId2/info/jvm,process'
curl -XGET 'http://localhost:9200/_nodes/nodeId1,nodeId2/_all
--------------------------------------------------
-The `all` flag can be set to return all the information - or you can simply omit it.
+The `_all` flag can be set to return all the information - or you can simply omit it.
-`plugin` - if set, the result will contain details about the loaded
+`plugins` - if set, the result will contain details about the loaded
plugins per node:
* `name`: plugin name
diff --git a/rest-api-spec/api/nodes.info.json b/rest-api-spec/api/nodes.info.json
index 4885fa6f9d084..e121e3047aba6 100644
--- a/rest-api-spec/api/nodes.info.json
+++ b/rest-api-spec/api/nodes.info.json
@@ -12,7 +12,7 @@
},
"metric": {
"type": "list",
- "options": ["settings", "os", "process", "jvm", "thread_pool", "network", "transport", "http", "plugin"],
+ "options": ["settings", "os", "process", "jvm", "thread_pool", "network", "transport", "http", "plugins"],
"description": "A comma-separated list of metrics you wish returned. Leave empty to return all."
}
},
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequest.java b/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequest.java
index b9ab8d323e4a7..589471af36dfd 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequest.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequest.java
@@ -38,7 +38,7 @@ public class NodesInfoRequest extends NodesOperationRequest<NodesInfoRequest> {
private boolean network = true;
private boolean transport = true;
private boolean http = true;
- private boolean plugin = true;
+ private boolean plugins = true;
public NodesInfoRequest() {
}
@@ -63,7 +63,7 @@ public NodesInfoRequest clear() {
network = false;
transport = false;
http = false;
- plugin = false;
+ plugins = false;
return this;
}
@@ -79,7 +79,7 @@ public NodesInfoRequest all() {
network = true;
transport = true;
http = true;
- plugin = true;
+ plugins = true;
return this;
}
@@ -205,19 +205,19 @@ public NodesInfoRequest http(boolean http) {
/**
* Should information about plugins be returned
- * @param plugin true if you want info
+ * @param plugins true if you want info
* @return The request
*/
- public NodesInfoRequest plugin(boolean plugin) {
- this.plugin = plugin;
+ public NodesInfoRequest plugins(boolean plugins) {
+ this.plugins = plugins;
return this;
}
/**
* @return true if information about plugins is requested
*/
- public boolean plugin() {
- return plugin;
+ public boolean plugins() {
+ return plugins;
}
@Override
@@ -231,7 +231,7 @@ public void readFrom(StreamInput in) throws IOException {
network = in.readBoolean();
transport = in.readBoolean();
http = in.readBoolean();
- plugin = in.readBoolean();
+ plugins = in.readBoolean();
}
@Override
@@ -245,6 +245,6 @@ public void writeTo(StreamOutput out) throws IOException {
out.writeBoolean(network);
out.writeBoolean(transport);
out.writeBoolean(http);
- out.writeBoolean(plugin);
+ out.writeBoolean(plugins);
}
}
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequestBuilder.java b/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequestBuilder.java
index f119522b3a2d6..c6c0cc19f9cfc 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequestBuilder.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodesInfoRequestBuilder.java
@@ -113,8 +113,11 @@ public NodesInfoRequestBuilder setHttp(boolean http) {
return this;
}
- public NodesInfoRequestBuilder setPlugin(boolean plugin) {
- request().plugin(plugin);
+ /**
+ * Should the node plugins info be returned.
+ */
+ public NodesInfoRequestBuilder setPlugins(boolean plugins) {
+ request().plugins(plugins);
return this;
}
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/node/info/TransportNodesInfoAction.java b/src/main/java/org/elasticsearch/action/admin/cluster/node/info/TransportNodesInfoAction.java
index 735ea418b601d..1392ab9b52685 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/node/info/TransportNodesInfoAction.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/node/info/TransportNodesInfoAction.java
@@ -98,7 +98,7 @@ protected NodeInfo newNodeResponse() {
protected NodeInfo nodeOperation(NodeInfoRequest nodeRequest) throws ElasticsearchException {
NodesInfoRequest request = nodeRequest.request;
return nodeService.info(request.settings(), request.os(), request.process(), request.jvm(), request.threadPool(),
- request.network(), request.transport(), request.http(), request.plugin());
+ request.network(), request.transport(), request.http(), request.plugins());
}
@Override
diff --git a/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java b/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java
index fe22ffb6f6462..35d2ff5fde1c6 100644
--- a/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java
+++ b/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java
@@ -44,7 +44,7 @@
public class RestNodesInfoAction extends BaseRestHandler {
private final SettingsFilter settingsFilter;
- private final static Set<String> ALLOWED_METRICS = Sets.newHashSet("http", "jvm", "network", "os", "plugin", "process", "settings", "thread_pool", "transport");
+ private final static Set<String> ALLOWED_METRICS = Sets.newHashSet("http", "jvm", "network", "os", "plugins", "process", "settings", "thread_pool", "transport");
@Inject
public RestNodesInfoAction(Settings settings, Client client, RestController controller,
@@ -99,7 +99,7 @@ public void handleRequest(final RestRequest request, final RestChannel channel)
nodesInfoRequest.network(metrics.contains("network"));
nodesInfoRequest.transport(metrics.contains("transport"));
nodesInfoRequest.http(metrics.contains("http"));
- nodesInfoRequest.plugin(metrics.contains("plugin"));
+ nodesInfoRequest.plugins(metrics.contains("plugins"));
}
client.admin().cluster().nodesInfo(nodesInfoRequest, new ActionListener<NodesInfoResponse>() {
diff --git a/src/test/java/org/elasticsearch/nodesinfo/SimpleNodesInfoTests.java b/src/test/java/org/elasticsearch/nodesinfo/SimpleNodesInfoTests.java
index 6104a7cf3eeb3..8a3d733e96c1b 100644
--- a/src/test/java/org/elasticsearch/nodesinfo/SimpleNodesInfoTests.java
+++ b/src/test/java/org/elasticsearch/nodesinfo/SimpleNodesInfoTests.java
@@ -129,7 +129,7 @@ public void testNodeInfoPlugin() throws URISyntaxException {
ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus()).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
- NodesInfoResponse response = client().admin().cluster().prepareNodesInfo().clear().setPlugin(true).execute().actionGet();
+ NodesInfoResponse response = client().admin().cluster().prepareNodesInfo().clear().setPlugins(true).execute().actionGet();
logger.info("--> full json answer, status " + response.toString());
assertNodeContainsPlugins(response, server1NodeId,
diff --git a/src/test/java/org/elasticsearch/plugin/PluginManagerTests.java b/src/test/java/org/elasticsearch/plugin/PluginManagerTests.java
index 1cb1dea67b1e8..2d69135f1765e 100644
--- a/src/test/java/org/elasticsearch/plugin/PluginManagerTests.java
+++ b/src/test/java/org/elasticsearch/plugin/PluginManagerTests.java
@@ -143,7 +143,7 @@ private static void downloadAndExtract(String pluginName, String pluginUrl) thro
}
private void assertPluginLoaded(String pluginName) {
- NodesInfoResponse nodesInfoResponse = client().admin().cluster().prepareNodesInfo().clear().setPlugin(true).get();
+ NodesInfoResponse nodesInfoResponse = client().admin().cluster().prepareNodesInfo().clear().setPlugins(true).get();
assertThat(nodesInfoResponse.getNodes().length, equalTo(1));
assertThat(nodesInfoResponse.getNodes()[0].getPlugins().getInfos(), notNullValue());
assertThat(nodesInfoResponse.getNodes()[0].getPlugins().getInfos().size(), equalTo(1));
|
5bd1d57bffc98a94fe7c7687f85a0052de11ecfc
|
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 b7f0cc4e8..b13157eee 100644
--- a/deltaspike/cdictrl/api/pom.xml
+++ b/deltaspike/cdictrl/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml
index 4a8c6a542..a8ab98ebf 100644
--- a/deltaspike/cdictrl/impl-openejb/pom.xml
+++ b/deltaspike/cdictrl/impl-openejb/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/impl-owb/pom.xml b/deltaspike/cdictrl/impl-owb/pom.xml
index d12ad4d3e..1aff43453 100644
--- a/deltaspike/cdictrl/impl-owb/pom.xml
+++ b/deltaspike/cdictrl/impl-owb/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/impl-weld/pom.xml b/deltaspike/cdictrl/impl-weld/pom.xml
index 57117debd..f32ca1344 100644
--- a/deltaspike/cdictrl/impl-weld/pom.xml
+++ b/deltaspike/cdictrl/impl-weld/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/pom.xml b/deltaspike/cdictrl/pom.xml
index 6fe4c8a6d..eea1091e1 100644
--- a/deltaspike/cdictrl/pom.xml
+++ b/deltaspike/cdictrl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/tck/pom.xml b/deltaspike/cdictrl/tck/pom.xml
index 778faeca2..623d079b9 100644
--- a/deltaspike/cdictrl/tck/pom.xml
+++ b/deltaspike/cdictrl/tck/pom.xml
@@ -22,7 +22,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/checkstyle-rules/pom.xml b/deltaspike/checkstyle-rules/pom.xml
index 3ade08b4a..18da99bf7 100644
--- a/deltaspike/checkstyle-rules/pom.xml
+++ b/deltaspike/checkstyle-rules/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>deltaspike-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/core/api/pom.xml b/deltaspike/core/api/pom.xml
index 633ad513e..11717aa22 100644
--- a/deltaspike/core/api/pom.xml
+++ b/deltaspike/core/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>core-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/core/impl/pom.xml b/deltaspike/core/impl/pom.xml
index 092b4d978..3db7f1249 100644
--- a/deltaspike/core/impl/pom.xml
+++ b/deltaspike/core/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>core-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/core/pom.xml b/deltaspike/core/pom.xml
index bd378a314..c36bd601a 100644
--- a/deltaspike/core/pom.xml
+++ b/deltaspike/core/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent-code</artifactId>
- <version>0.4</version>
+ <version>0.5-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 04bd7923c..c19800dc2 100644
--- a/deltaspike/examples/jse-examples/pom.xml
+++ b/deltaspike/examples/jse-examples/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.examples</groupId>
<artifactId>examples-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 519a82758..3e6cfa9e8 100644
--- a/deltaspike/examples/jsf-examples/pom.xml
+++ b/deltaspike/examples/jsf-examples/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.examples</groupId>
<artifactId>examples-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<artifactId>deltaspike-jsf-example</artifactId>
diff --git a/deltaspike/examples/pom.xml b/deltaspike/examples/pom.xml
index 71cb7f6bc..a6836acbb 100644
--- a/deltaspike/examples/pom.xml
+++ b/deltaspike/examples/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
diff --git a/deltaspike/modules/jpa/api/pom.xml b/deltaspike/modules/jpa/api/pom.xml
index a680cff57..b770767d9 100644
--- a/deltaspike/modules/jpa/api/pom.xml
+++ b/deltaspike/modules/jpa/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jpa-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 2b49251fb..ce39da7ec 100644
--- a/deltaspike/modules/jpa/impl/pom.xml
+++ b/deltaspike/modules/jpa/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jpa-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/jpa/pom.xml b/deltaspike/modules/jpa/pom.xml
index d139ab352..615992947 100644
--- a/deltaspike/modules/jpa/pom.xml
+++ b/deltaspike/modules/jpa/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jpa-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 f4cb24183..8492a2541 100644
--- a/deltaspike/modules/jsf/api/pom.xml
+++ b/deltaspike/modules/jsf/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jsf-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 a7da307d1..e23fde094 100644
--- a/deltaspike/modules/jsf/impl/pom.xml
+++ b/deltaspike/modules/jsf/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jsf-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/jsf/pom.xml b/deltaspike/modules/jsf/pom.xml
index b0a975443..117c2f916 100644
--- a/deltaspike/modules/jsf/pom.xml
+++ b/deltaspike/modules/jsf/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jsf-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 dba14d189..abfa1b47a 100644
--- a/deltaspike/modules/partial-bean/api/pom.xml
+++ b/deltaspike/modules/partial-bean/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>partial-bean-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 be9937650..7833c3410 100644
--- a/deltaspike/modules/partial-bean/impl/pom.xml
+++ b/deltaspike/modules/partial-bean/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>partial-bean-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 c6cf172df..cda936091 100644
--- a/deltaspike/modules/partial-bean/pom.xml
+++ b/deltaspike/modules/partial-bean/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>partial-bean-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 eb4ea6b54..04888605e 100644
--- a/deltaspike/modules/pom.xml
+++ b/deltaspike/modules/pom.xml
@@ -23,13 +23,13 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent-code</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../parent/code/pom.xml</relativePath>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 d8a222c15..a89bc91ec 100644
--- a/deltaspike/modules/security/api/pom.xml
+++ b/deltaspike/modules/security/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>security-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-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 52d6642b9..170725256 100644
--- a/deltaspike/modules/security/impl/pom.xml
+++ b/deltaspike/modules/security/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>security-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/security/pom.xml b/deltaspike/modules/security/pom.xml
index 93ac462f1..e3749c514 100644
--- a/deltaspike/modules/security/pom.xml
+++ b/deltaspike/modules/security/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>security-module-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike Security-Module</name>
diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml
index d282fcfac..c2f448e72 100644
--- a/deltaspike/parent/code/pom.xml
+++ b/deltaspike/parent/code/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml
index f1b4eec26..fef94b4ea 100644
--- a/deltaspike/parent/pom.xml
+++ b/deltaspike/parent/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>deltaspike-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml
index 6d45e7197..fb3259919 100644
--- a/deltaspike/pom.xml
+++ b/deltaspike/pom.xml
@@ -36,7 +36,7 @@
-->
<groupId>org.apache.deltaspike</groupId>
<artifactId>deltaspike-project</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike</name>
@@ -49,7 +49,7 @@
<connection>scm:git:https://git-wip-us.apache.org/repos/asf/incubator-deltaspike.git</connection>
<developerConnection>scm:git:https://git-wip-us.apache.org/repos/asf/incubator-deltaspike.git</developerConnection>
<url>https://git-wip-us.apache.org/repos/asf/incubator-deltaspike.git</url>
- <tag>deltaspike-project-0.4</tag>
+ <tag>HEAD</tag>
</scm>
<modules>
diff --git a/deltaspike/test-utils/pom.xml b/deltaspike/test-utils/pom.xml
index 0bc3f9128..effe3e55f 100644
--- a/deltaspike/test-utils/pom.xml
+++ b/deltaspike/test-utils/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.4</version>
+ <version>0.5-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
|
eef90a46040c6b4018b699dfc96cb4bc8bc4e82e
|
hbase
|
HBASE-5927 SSH and DisableTableHandler happening- together does not clear the znode of the region and RIT map (Rajesh)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1339913 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java b/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java
index bf93970186ed..e6796174cfd7 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java
@@ -2124,7 +2124,11 @@ public void unassign(HRegionInfo region, boolean force){
unassign(region, force, null);
}
- private void deleteClosingOrClosedNode(HRegionInfo region) {
+ /**
+ *
+ * @param region regioninfo of znode to be deleted.
+ */
+ public void deleteClosingOrClosedNode(HRegionInfo region) {
try {
if (!ZKAssign.deleteNode(master.getZooKeeper(), region.getEncodedName(),
EventHandler.EventType.M_ZK_REGION_CLOSING)) {
diff --git a/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java b/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
index 06da2ce679e3..dde71b225688 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
@@ -288,10 +288,10 @@ public void process() throws IOException {
if (hris != null) {
List<HRegionInfo> toAssignRegions = new ArrayList<HRegionInfo>();
for (Map.Entry<HRegionInfo, Result> e: hris.entrySet()) {
+ RegionState rit = this.services.getAssignmentManager().isRegionInTransition(e.getKey());
if (processDeadRegion(e.getKey(), e.getValue(),
this.services.getAssignmentManager(),
this.server.getCatalogTracker())) {
- RegionState rit = this.services.getAssignmentManager().isRegionInTransition(e.getKey());
ServerName addressFromAM = this.services.getAssignmentManager()
.getRegionServerOfRegion(e.getKey());
if (rit != null && !rit.isClosing() && !rit.isPendingClose()) {
@@ -308,6 +308,22 @@ public void process() throws IOException {
toAssignRegions.add(e.getKey());
}
}
+ // If the table was partially disabled and the RS went down, we should clear the RIT
+ // and remove the node for the region.
+ // The rit that we use may be stale in case the table was in DISABLING state
+ // but though we did assign we will not be clearing the znode in CLOSING state.
+ // Doing this will have no harm. See HBASE-5927
+ if (rit != null
+ && (rit.isClosing() || rit.isPendingClose())
+ && this.services.getAssignmentManager().getZKTable()
+ .isDisablingOrDisabledTable(rit.getRegion().getTableNameAsString())) {
+ HRegionInfo hri = rit.getRegion();
+ AssignmentManager am = this.services.getAssignmentManager();
+ am.deleteClosingOrClosedNode(hri);
+ am.regionOffline(hri);
+ // To avoid region assignment if table is in disabling or disabled state.
+ toAssignRegions.remove(hri);
+ }
}
// Get all available servers
List<ServerName> availableServers = services.getServerManager()
diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java b/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java
index 32c3009b7e18..36be722b4c6b 100644
--- a/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java
+++ b/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java
@@ -35,6 +35,8 @@
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.ServerLoad;
+import org.apache.hadoop.hbase.master.AssignmentManager.RegionState;
+import org.apache.hadoop.hbase.master.AssignmentManager.RegionState.State;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.RegionTransition;
import org.apache.hadoop.hbase.Server;
@@ -53,6 +55,7 @@
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
+import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.Table;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
import org.apache.hadoop.hbase.util.Bytes;
@@ -399,44 +402,72 @@ public void testShutdownHandler()
AssignmentManager am = new AssignmentManager(this.server,
this.serverManager, ct, balancer, executor, null);
try {
- // Make sure our new AM gets callbacks; once registered, can't unregister.
- // Thats ok because we make a new zk watcher for each test.
- this.watcher.registerListenerFirst(am);
+ processServerShutdownHandler(ct, am);
+ } finally {
+ executor.shutdown();
+ am.shutdown();
+ // Clean up all znodes
+ ZKAssign.deleteAllNodes(this.watcher);
+ }
+ }
- // Need to set up a fake scan of meta for the servershutdown handler
- // Make an RS Interface implementation. Make it so a scanner can go against it.
- ClientProtocol implementation = Mockito.mock(ClientProtocol.class);
- // Get a meta row result that has region up on SERVERNAME_A
- Result r = Mocking.getMetaTableRowResult(REGIONINFO, SERVERNAME_A);
- ScanResponse.Builder builder = ScanResponse.newBuilder();
- builder.setMoreResults(false);
- builder.addResult(ProtobufUtil.toResult(r));
- Mockito.when(implementation.scan(
- (RpcController)Mockito.any(), (ScanRequest)Mockito.any())).
- thenReturn(builder.build());
-
- // Get a connection w/ mocked up common methods.
- HConnection connection =
- HConnectionTestingUtility.getMockedConnectionAndDecorate(HTU.getConfiguration(),
- null, implementation, SERVERNAME_B, REGIONINFO);
-
- // Make it so we can get a catalogtracker from servermanager.. .needed
- // down in guts of server shutdown handler.
- Mockito.when(ct.getConnection()).thenReturn(connection);
- Mockito.when(this.server.getCatalogTracker()).thenReturn(ct);
-
- // Now make a server shutdown handler instance and invoke process.
- // Have it that SERVERNAME_A died.
- DeadServer deadServers = new DeadServer();
- deadServers.add(SERVERNAME_A);
- // I need a services instance that will return the AM
- MasterServices services = Mockito.mock(MasterServices.class);
- Mockito.when(services.getAssignmentManager()).thenReturn(am);
- Mockito.when(services.getServerManager()).thenReturn(this.serverManager);
- ServerShutdownHandler handler = new ServerShutdownHandler(this.server,
- services, deadServers, SERVERNAME_A, false);
- handler.process();
- // The region in r will have been assigned. It'll be up in zk as unassigned.
+ /**
+ * To test closed region handler to remove rit and delete corresponding znode
+ * if region in pending close or closing while processing shutdown of a region
+ * server.(HBASE-5927).
+ *
+ * @throws KeeperException
+ * @throws IOException
+ * @throws ServiceException
+ */
+ @Test
+ public void testSSHWhenDisableTableInProgress() throws KeeperException, IOException,
+ ServiceException {
+ testCaseWithPartiallyDisabledState(Table.State.DISABLING);
+ testCaseWithPartiallyDisabledState(Table.State.DISABLED);
+ }
+
+ private void testCaseWithPartiallyDisabledState(Table.State state) throws KeeperException,
+ IOException, NodeExistsException, ServiceException {
+ // Create and startup an executor. This is used by AssignmentManager
+ // handling zk callbacks.
+ ExecutorService executor = startupMasterExecutor("testSSHWhenDisableTableInProgress");
+ // We need a mocked catalog tracker.
+ CatalogTracker ct = Mockito.mock(CatalogTracker.class);
+ LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(server.getConfiguration());
+ // Create an AM.
+ AssignmentManager am = new AssignmentManager(this.server, this.serverManager, ct, balancer,
+ executor, null);
+ // adding region to regions and servers maps.
+ am.regionOnline(REGIONINFO, SERVERNAME_A);
+ // adding region in pending close.
+ am.regionsInTransition.put(REGIONINFO.getEncodedName(), new RegionState(REGIONINFO,
+ State.PENDING_CLOSE));
+ if (state == Table.State.DISABLING) {
+ am.getZKTable().setDisablingTable(REGIONINFO.getTableNameAsString());
+ } else {
+ am.getZKTable().setDisabledTable(REGIONINFO.getTableNameAsString());
+ }
+ RegionTransition data = RegionTransition.createRegionTransition(EventType.M_ZK_REGION_CLOSING,
+ REGIONINFO.getRegionName(), SERVERNAME_A);
+ // RegionTransitionData data = new
+ // RegionTransitionData(EventType.M_ZK_REGION_CLOSING,
+ // REGIONINFO.getRegionName(), SERVERNAME_A);
+ String node = ZKAssign.getNodeName(this.watcher, REGIONINFO.getEncodedName());
+ // create znode in M_ZK_REGION_CLOSING state.
+ ZKUtil.createAndWatch(this.watcher, node, data.toByteArray());
+ try {
+ processServerShutdownHandler(ct, am);
+ // check znode deleted or not.
+ // In both cases the znode should be deleted.
+ assertTrue("The znode should be deleted.", ZKUtil.checkExists(this.watcher, node) == -1);
+ // check whether in rit or not. In the DISABLING case also the below
+ // assert will be true but the piece of code added for HBASE-5927 will not
+ // do that.
+ if (state == Table.State.DISABLED) {
+ assertTrue("Region state of region in pending close should be removed from rit.",
+ am.regionsInTransition.isEmpty());
+ }
} finally {
executor.shutdown();
am.shutdown();
@@ -444,6 +475,48 @@ public void testShutdownHandler()
ZKAssign.deleteAllNodes(this.watcher);
}
}
+
+ private void processServerShutdownHandler(CatalogTracker ct, AssignmentManager am)
+ throws IOException, ServiceException {
+ // Make sure our new AM gets callbacks; once registered, can't unregister.
+ // Thats ok because we make a new zk watcher for each test.
+ this.watcher.registerListenerFirst(am);
+
+ // Need to set up a fake scan of meta for the servershutdown handler
+ // Make an RS Interface implementation. Make it so a scanner can go against it.
+ ClientProtocol implementation = Mockito.mock(ClientProtocol.class);
+ // Get a meta row result that has region up on SERVERNAME_A
+ Result r = Mocking.getMetaTableRowResult(REGIONINFO, SERVERNAME_A);
+ ScanResponse.Builder builder = ScanResponse.newBuilder();
+ builder.setMoreResults(true);
+ builder.addResult(ProtobufUtil.toResult(r));
+ Mockito.when(implementation.scan(
+ (RpcController)Mockito.any(), (ScanRequest)Mockito.any())).
+ thenReturn(builder.build());
+
+ // Get a connection w/ mocked up common methods.
+ HConnection connection =
+ HConnectionTestingUtility.getMockedConnectionAndDecorate(HTU.getConfiguration(),
+ null, implementation, SERVERNAME_B, REGIONINFO);
+
+ // Make it so we can get a catalogtracker from servermanager.. .needed
+ // down in guts of server shutdown handler.
+ Mockito.when(ct.getConnection()).thenReturn(connection);
+ Mockito.when(this.server.getCatalogTracker()).thenReturn(ct);
+
+ // Now make a server shutdown handler instance and invoke process.
+ // Have it that SERVERNAME_A died.
+ DeadServer deadServers = new DeadServer();
+ deadServers.add(SERVERNAME_A);
+ // I need a services instance that will return the AM
+ MasterServices services = Mockito.mock(MasterServices.class);
+ Mockito.when(services.getAssignmentManager()).thenReturn(am);
+ Mockito.when(services.getServerManager()).thenReturn(this.serverManager);
+ ServerShutdownHandler handler = new ServerShutdownHandler(this.server,
+ services, deadServers, SERVERNAME_A, false);
+ handler.process();
+ // The region in r will have been assigned. It'll be up in zk as unassigned.
+ }
/**
* Create and startup executor pools. Start same set as master does (just
|
08894a81b8ba840c6966aec9d7304769d8412b9d
|
orientdb
|
Fix failed WAL test.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java
index e04e3aa39b5..27178b452c8 100755
--- a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java
+++ b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java
@@ -6,18 +6,10 @@
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Random;
+import java.util.*;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
+import org.testng.annotations.*;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
@@ -1385,6 +1377,7 @@ public void testThirdPageCRCWasIncorrect() throws Exception {
RandomAccessFile rndFile = new RandomAccessFile(new File(testDir, "WriteAheadLogTest.0.wal"), "rw");
rndFile.seek(2 * OWALPage.PAGE_SIZE);
int bt = rndFile.read();
+ rndFile.seek(2 * OWALPage.PAGE_SIZE);
rndFile.write(bt + 1);
rndFile.close();
|
1a86e8349193dfd3504507a4493265dd8b99c9df
|
restlet-framework-java
|
Indexed directories were not properly handled with- the CLAP protocol. Reported by Rob Heittman.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/local/ClapClientHelper.java b/modules/com.noelios.restlet/src/com/noelios/restlet/local/ClapClientHelper.java
index a03a63d982..4664d3fe88 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/local/ClapClientHelper.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/local/ClapClientHelper.java
@@ -125,7 +125,7 @@ protected void handleClassLoader(Request request, Response response,
URL url = classLoader.getResource(Reference.decode(path));
// The ClassLoader returns a directory listing in some cases.
- // As this listing is partial, is it of little value in the context
+ // As this listing is partial, it is of little value in the context
// of the CLAP client, so we have to ignore them.
if (url != null) {
if (url.getProtocol().equals("file")) {
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/local/DirectoryResource.java b/modules/com.noelios.restlet/src/com/noelios/restlet/local/DirectoryResource.java
index bb2842c6ca..cdbccf6174 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/local/DirectoryResource.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/local/DirectoryResource.java
@@ -175,7 +175,8 @@ && getDirectory().getIndexName().length() > 0) {
// Let's try with the facultative index, in case the underlying
// client connector does not handle directory listing.
if (this.targetUri.endsWith("/")) {
- // Append the index name
+ // In this case, the trailing "/" shows that the URIs must
+ // points to a directory
if (getDirectory().getIndexName() != null
&& getDirectory().getIndexName().length() > 0) {
this.directoryUri = this.targetUri;
@@ -190,6 +191,25 @@ && getDirectory().getIndexName().length() > 0) {
this.targetIndex = true;
}
}
+ } else {
+ // Try to determine if this target URI with no trailing "/" is a
+ // directory, in order to force the redirection.
+ // Append the index name
+ if (getDirectory().getIndexName() != null
+ && getDirectory().getIndexName().length() > 0) {
+ this.directoryUri = this.targetUri + "/";
+ this.baseName = getDirectory().getIndexName();
+ this.targetUri = this.directoryUri + this.baseName;
+ contextResponse = getClientDispatcher().get(this.targetUri);
+ if (contextResponse.getEntity() != null) {
+ this.targetDirectory = true;
+ this.directoryRedirection = true;
+ this.directoryContent = new ReferenceList();
+ this.directoryContent
+ .add(new Reference(this.targetUri));
+ this.targetIndex = true;
+ }
+ }
}
}
diff --git a/modules/org.restlet.test/src/org/restlet/test/DirectoryTestCase.java b/modules/org.restlet.test/src/org/restlet/test/DirectoryTestCase.java
index eaa0c1c50e..ca8f1f9776 100644
--- a/modules/org.restlet.test/src/org/restlet/test/DirectoryTestCase.java
+++ b/modules/org.restlet.test/src/org/restlet/test/DirectoryTestCase.java
@@ -198,9 +198,9 @@ private void testDirectory(MyApplication application, Directory directory,
Method.DELETE, null, "6c-1");
assertTrue(response.getStatus()
.equals(Status.REDIRECTION_SEE_OTHER));
- System.out.println(response.getRedirectRef());
- response = handle(application, response.getRedirectRef().getPath(),
- response.getRedirectRef().getPath(), Method.DELETE, null,
+ System.out.println(response.getLocationRef());
+ response = handle(application, response.getLocationRef().getPath(),
+ response.getLocationRef().getPath(), Method.DELETE, null,
"6c-2");
assertTrue(response.getStatus().equals(
Status.CLIENT_ERROR_FORBIDDEN));
|
d074c686b3ba0ba6843d0a25dca5ac991f919e68
|
hadoop
|
HADOOP-6139. Fix the FsShell help messages for rm- and rmr. Contributed by Jakob Homan--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@793098 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 9979aefe66ab8..c70d07c0fbf23 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1011,6 +1011,9 @@ Release 0.20.1 - Unreleased
HADOOP-5920. Fixes a testcase failure for TestJobHistory.
(Amar Kamat via ddas)
+ HADOOP-6139. Fix the FsShell help messages for rm and rmr. (Jakob Homan
+ via szetszwo)
+
Release 0.20.0 - 2009-04-15
INCOMPATIBLE CHANGES
diff --git a/src/java/org/apache/hadoop/fs/FsShell.java b/src/java/org/apache/hadoop/fs/FsShell.java
index 3af28dc13e441..634da87da000e 100644
--- a/src/java/org/apache/hadoop/fs/FsShell.java
+++ b/src/java/org/apache/hadoop/fs/FsShell.java
@@ -1679,7 +1679,6 @@ private static void printUsage(String cmd) {
" [-D <[property=value>]");
} else if ("-ls".equals(cmd) || "-lsr".equals(cmd) ||
"-du".equals(cmd) || "-dus".equals(cmd) ||
- "-rm".equals(cmd) || "-rmr".equals(cmd) ||
"-touchz".equals(cmd) || "-mkdir".equals(cmd) ||
"-text".equals(cmd)) {
System.err.println("Usage: java FsShell" +
@@ -1689,6 +1688,9 @@ private static void printUsage(String cmd) {
" [" + cmd + " [<path>]]");
} else if (Count.matches(cmd)) {
System.err.println(prefix + " [" + Count.USAGE + "]");
+ } else if ("-rm".equals(cmd) || "-rmr".equals(cmd)) {
+ System.err.println("Usage: java FsShell [" + cmd +
+ " [-skipTrash] <src>]");
} else if ("-mv".equals(cmd) || "-cp".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <src> <dst>]");
|
50222da1622de0039fc812624253f85f474d80d4
|
Vala
|
codegen: Support constant unary expressions in field initializers
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala
index 1bee9e52cd..8d6ebddf9d 100644
--- a/codegen/valaccodebasemodule.vala
+++ b/codegen/valaccodebasemodule.vala
@@ -1342,6 +1342,16 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator {
} else if (cexpr is CCodeCastExpression) {
var ccast = (CCodeCastExpression) cexpr;
return is_constant_ccode_expression (ccast.inner);
+ } else if (cexpr is CCodeUnaryExpression) {
+ var cunary = (CCodeUnaryExpression) cexpr;
+ switch (cunary.operator) {
+ case CCodeUnaryOperator.PREFIX_INCREMENT:
+ case CCodeUnaryOperator.PREFIX_DECREMENT:
+ case CCodeUnaryOperator.POSTFIX_INCREMENT:
+ case CCodeUnaryOperator.POSTFIX_DECREMENT:
+ return false;
+ }
+ return is_constant_ccode_expression (cunary.inner);
} else if (cexpr is CCodeBinaryExpression) {
var cbinary = (CCodeBinaryExpression) cexpr;
return is_constant_ccode_expression (cbinary.left) && is_constant_ccode_expression (cbinary.right);
|
b72e82bf7f499f2779b5c944fa19bd154e881537
|
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.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java
index ff7d6c8d..769af13a 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java
@@ -139,11 +139,13 @@ public void updateTaskData(TaskRepository repository, TaskData data, ChangeDetai
int i = 1;
for (ChangeMessage message : changeDetail.getMessages()) {
TaskCommentMapper mapper = new TaskCommentMapper();
- AccountInfo author = changeDetail.getAccounts().get(message.getAuthor());
- IRepositoryPerson person = repository.createPerson((author.getPreferredEmail() != null) ? author.getPreferredEmail()
- : author.getId() + ""); //$NON-NLS-1$
- person.setName(author.getFullName());
- mapper.setAuthor(person);
+ if (message.getAuthor() != null) {
+ AccountInfo author = changeDetail.getAccounts().get(message.getAuthor());
+ IRepositoryPerson person = repository.createPerson((author.getPreferredEmail() != null) ? author.getPreferredEmail()
+ : author.getId() + ""); //$NON-NLS-1$
+ person.setName(author.getFullName());
+ mapper.setAuthor(person);
+ }
mapper.setText(message.getMessage());
mapper.setCreationDate(message.getWrittenOn());
mapper.setNumber(i);
diff --git a/gerrit/org.eclipse.mylyn.gerrit.tests/pom.xml b/gerrit/org.eclipse.mylyn.gerrit.tests/pom.xml
index 35dfcf3a..64974e38 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.tests/pom.xml
+++ b/gerrit/org.eclipse.mylyn.gerrit.tests/pom.xml
@@ -15,14 +15,6 @@
<groupId>org.sonatype.tycho</groupId>
<artifactId>maven-osgi-source-plugin</artifactId>
</plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-pmd-plugin</artifactId>
- </plugin>
</plugins>
</build>
</project>
diff --git a/pom.xml b/pom.xml
index d85cacf5..f6b807a0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -112,6 +112,11 @@
<ws>win32</ws>
<arch>x86</arch>
</environment>
+ <environment>
+ <os>win32</os>
+ <ws>win32</ws>
+ <arch>x86_64</arch>
+ </environment>
<environment>
<os>linux</os>
<ws>gtk</ws>
@@ -122,6 +127,11 @@
<ws>gtk</ws>
<arch>x86_64</arch>
</environment>
+ <environment>
+ <os>macosx</os>
+ <ws>cocoa</ws>
+ <arch>x86_64</arch>
+ </environment>
</environments>
</configuration>
</plugin>
@@ -153,7 +163,7 @@
</execution>
</executions>
</plugin>
- <plugin>
+ <plugin>
<groupId>org.sonatype.tycho</groupId>
<artifactId>maven-osgi-packaging-plugin</artifactId>
<version>${tycho-version}</version>
@@ -182,7 +192,7 @@
<configuration>
<findbugsXmlOutput>true</findbugsXmlOutput>
<failOnError>false</failOnError>
- <skip>true</skip>
+ <skip>true</skip>
</configuration>
<executions>
<execution>
@@ -202,7 +212,7 @@
<targetJdk>1.5</targetJdk>
<format>xml</format>
<failOnViolation>false</failOnViolation>
- <skip>true</skip>
+ <skip>true</skip>
</configuration>
<executions>
<execution>
diff --git a/releng/reviews-target-definition/mylyn-reviews-e3.5.target b/releng/reviews-target-definition/mylyn-reviews-e3.5.target
index 59b461c3..856a1f05 100644
--- a/releng/reviews-target-definition/mylyn-reviews-e3.5.target
+++ b/releng/reviews-target-definition/mylyn-reviews-e3.5.target
@@ -12,16 +12,16 @@
<unit id="org.eclipse.emf.databinding.feature.group" version="1.1.0.v200906151043"/>
<repository location="http://download.eclipse.org/egit/updates"/>
<unit id="org.eclipse.jgit.feature.group" version="0.10.1"/>
-<repository location="http://download.eclipse.org/tools/orbit/committers/drops/I20110118151342/repository/"/>
+<repository location="http://download.eclipse.org/tools/orbit/committers/drops/S20110124210048/repository/"/>
<unit id="com.google.gwt.user" version="2.0.4.v20100709-0658"/>
<unit id="org.apache.commons.io" version="1.4.0.v20081110-1000"/>
<unit id="com.google.gson" version="1.6.0.v201101131530"/>
<unit id="com.google.gwtjsonrpc" version="1.2.2.v201101101830"/>
<unit id="com.google.gwtorm" version="1.1.4.v201101121000"/>
<unit id="com.google.gwt.user" version="2.0.4.v20100709-0658"/>
-<unit id="com.google.gerrit.prettify" version="2.1.5.v201101170600"/>
+<unit id="com.google.gerrit.prettify" version="2.1.5.v201101181500"/>
<unit id="com.google.gerrit.reviewdb" version="2.1.5.v201101121030"/>
-<unit id="com.google.gerrit.common" version="2.1.5.v201101131540"/>
+<unit id="com.google.gerrit.common" version="2.1.5.v201101200205"/>
<unit id="org.eclipse.mylyn_feature.feature.group" version="3.5.0.I20110104-0100-e3x"/>
<repository location="http://download.eclipse.org/tools/mylyn/update/weekly"/>
<unit id="org.eclipse.mylyn.bugzilla_feature.feature.group" version="3.5.0.I20110104-0100-e3x"/>
diff --git a/releng/reviews-target-definition/mylyn-reviews-e3.6.target b/releng/reviews-target-definition/mylyn-reviews-e3.6.target
index 0572bb0e..03536923 100644
--- a/releng/reviews-target-definition/mylyn-reviews-e3.6.target
+++ b/releng/reviews-target-definition/mylyn-reviews-e3.6.target
@@ -12,16 +12,16 @@
<unit id="org.eclipse.emf.databinding.feature.group" version="1.2.0.v20100914-1218"/>
<repository location="http://download.eclipse.org/egit/updates"/>
<unit id="org.eclipse.jgit.feature.group" version="0.10.1"/>
-<repository location="http://download.eclipse.org/tools/orbit/committers/drops/I20110118151342/repository/"/>
+<repository location="http://download.eclipse.org/tools/orbit/committers/drops/S20110124210048/repository/"/>
<unit id="com.google.gwt.user" version="2.0.4.v20100709-0658"/>
<unit id="org.apache.commons.io" version="1.4.0.v20081110-1000"/>
<unit id="com.google.gson" version="1.6.0.v201101131530"/>
<unit id="com.google.gwtjsonrpc" version="1.2.2.v201101101830"/>
<unit id="com.google.gwtorm" version="1.1.4.v201101121000"/>
<unit id="com.google.gwt.user" version="2.0.4.v20100709-0658"/>
-<unit id="com.google.gerrit.prettify" version="2.1.5.v201101170600"/>
+<unit id="com.google.gerrit.prettify" version="2.1.5.v201101181500"/>
<unit id="com.google.gerrit.reviewdb" version="2.1.5.v201101121030"/>
-<unit id="com.google.gerrit.common" version="2.1.5.v201101131540"/>
+<unit id="com.google.gerrit.common" version="2.1.5.v201101200205"/>
<unit id="org.eclipse.mylyn_feature.feature.group" version="3.5.0.I20110104-0100-e3x"/>
<repository location="http://download.eclipse.org/tools/mylyn/update/weekly"/>
<unit id="org.eclipse.mylyn.bugzilla_feature.feature.group" version="3.5.0.I20110104-0100-e3x"/>
diff --git a/releng/reviews-target-definition/mylyn-reviews-e3.7.target b/releng/reviews-target-definition/mylyn-reviews-e3.7.target
index 5478a5bd..16c71bbd 100644
--- a/releng/reviews-target-definition/mylyn-reviews-e3.7.target
+++ b/releng/reviews-target-definition/mylyn-reviews-e3.7.target
@@ -14,16 +14,16 @@
<unit id="org.eclipse.xtext.runtime.feature.group" version="1.0.1.v201008251220"/>
<repository location="http://download.eclipse.org/egit/updates"/>
<unit id="org.eclipse.jgit.feature.group" version="0.10.1"/>
-<repository location="http://download.eclipse.org/tools/orbit/committers/drops/I20110118151342/repository/"/>
+<repository location="http://download.eclipse.org/tools/orbit/committers/drops/S20110124210048/repository/"/>
<unit id="com.google.gwt.user" version="2.0.4.v20100709-0658"/>
<unit id="org.apache.commons.io" version="1.4.0.v20081110-1000"/>
<unit id="com.google.gson" version="1.6.0.v201101131530"/>
<unit id="com.google.gwtjsonrpc" version="1.2.2.v201101101830"/>
<unit id="com.google.gwtorm" version="1.1.4.v201101121000"/>
<unit id="com.google.gwt.user" version="2.0.4.v20100709-0658"/>
-<unit id="com.google.gerrit.prettify" version="2.1.5.v201101170600"/>
+<unit id="com.google.gerrit.prettify" version="2.1.5.v201101181500"/>
<unit id="com.google.gerrit.reviewdb" version="2.1.5.v201101121030"/>
-<unit id="com.google.gerrit.common" version="2.1.5.v201101131540"/>
+<unit id="com.google.gerrit.common" version="2.1.5.v201101200205"/>
<unit id="org.eclipse.mylyn_feature.feature.group" version="3.5.0.I20110104-0100-e3x"/>
<repository location="http://download.eclipse.org/tools/mylyn/update/weekly"/>
<unit id="org.eclipse.mylyn.bugzilla_feature.feature.group" version="3.5.0.I20110104-0100-e3x"/>
|
9cea634f7d4276b87821f3ab7c160fa67b2c85b1
|
hadoop
|
HDFS-2414. Fix TestDFSRollback to avoid spurious- failures. Contributed by Todd Lipcon.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1180540 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 465458bec402c..1fd1b345d4870 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1032,6 +1032,8 @@ Release 0.23.0 - Unreleased
HDFS-2412. Add backwards-compatibility layer for renamed FSConstants
class (todd)
+ HDFS-2414. Fix TestDFSRollback to avoid spurious failures. (todd)
+
BREAKDOWN OF HDFS-1073 SUBTASKS
HDFS-1521. Persist transaction ID on disk between NN restarts.
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java
index cdf3665af181c..687f5633ff655 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java
@@ -37,6 +37,7 @@
import org.apache.hadoop.hdfs.server.namenode.FSImageTestUtil;
import org.apache.hadoop.util.StringUtils;
+import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
/**
@@ -263,10 +264,14 @@ public void testRollback() throws Exception {
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
for (File f : baseDirs) {
- UpgradeUtilities.corruptFile(new File(f,"VERSION"));
+ UpgradeUtilities.corruptFile(
+ new File(f,"VERSION"),
+ "layoutVersion".getBytes(Charsets.UTF_8),
+ "xxxxxxxxxxxxx".getBytes(Charsets.UTF_8));
}
startNameNodeShouldFail(StartupOption.ROLLBACK,
"file VERSION has layoutVersion missing");
+
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with old layout version in previous", numDirs);
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgrade.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgrade.java
index 251f23dee706d..a308c230cb0ac 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgrade.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgrade.java
@@ -39,6 +39,7 @@
import org.junit.Ignore;
import org.junit.Test;
+import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import static org.junit.Assert.*;
@@ -303,7 +304,10 @@ public void testUpgrade() throws Exception {
log("NameNode upgrade with corrupt version file", numDirs);
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
for (File f : baseDirs) {
- UpgradeUtilities.corruptFile(new File (f,"VERSION"));
+ UpgradeUtilities.corruptFile(
+ new File(f,"VERSION"),
+ "layoutVersion".getBytes(Charsets.UTF_8),
+ "xxxxxxxxxxxxx".getBytes(Charsets.UTF_8));
}
startNameNodeShouldFail(StartupOption.UPGRADE);
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/UpgradeUtilities.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/UpgradeUtilities.java
index 337fa8a17c07c..0b6bceafafcfe 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/UpgradeUtilities.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/UpgradeUtilities.java
@@ -24,10 +24,8 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.RandomAccessFile;
import java.net.URI;
import java.util.Arrays;
-import java.util.Random;
import java.util.Collections;
import java.util.zip.CRC32;
import org.apache.hadoop.conf.Configuration;
@@ -53,6 +51,10 @@
import org.apache.hadoop.hdfs.server.namenode.NNStorage;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
+import com.google.common.base.Preconditions;
+import com.google.common.io.Files;
+import com.google.common.primitives.Bytes;
+
/**
* This class defines a number of static helper methods used by the
* DFS Upgrade unit tests. By default, a singleton master populated storage
@@ -483,20 +485,26 @@ public static void createBlockPoolVersionFile(File bpDir,
* @throws IllegalArgumentException if the given file is not a file
* @throws IOException if an IOException occurs while reading or writing the file
*/
- public static void corruptFile(File file) throws IOException {
+ public static void corruptFile(File file,
+ byte[] stringToCorrupt,
+ byte[] replacement) throws IOException {
+ Preconditions.checkArgument(replacement.length == stringToCorrupt.length);
if (!file.isFile()) {
throw new IllegalArgumentException(
- "Given argument is not a file:" + file);
+ "Given argument is not a file:" + file);
}
- RandomAccessFile raf = new RandomAccessFile(file,"rws");
- Random random = new Random();
- for (long i = 0; i < raf.length(); i++) {
- raf.seek(i);
- if (random.nextBoolean()) {
- raf.writeByte(random.nextInt());
- }
+ byte[] data = Files.toByteArray(file);
+ int index = Bytes.indexOf(data, stringToCorrupt);
+ if (index == -1) {
+ throw new IOException(
+ "File " + file + " does not contain string " +
+ new String(stringToCorrupt));
+ }
+
+ for (int i = 0; i < stringToCorrupt.length; i++) {
+ data[index + i] = replacement[i];
}
- raf.close();
+ Files.write(data, file);
}
/**
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/FSImageTestUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/FSImageTestUtil.java
index 4a8edb8475a89..ce9b224f22c0f 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/FSImageTestUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/FSImageTestUtil.java
@@ -29,6 +29,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
@@ -233,11 +234,49 @@ public static void assertParallelFilesAreIdentical(List<File> dirs,
// recurse
assertParallelFilesAreIdentical(sameNameList, ignoredFileNames);
} else {
- assertFileContentsSame(sameNameList.toArray(new File[0]));
+ if ("VERSION".equals(sameNameList.get(0).getName())) {
+ assertPropertiesFilesSame(sameNameList.toArray(new File[0]));
+ } else {
+ assertFileContentsSame(sameNameList.toArray(new File[0]));
+ }
}
}
}
+ /**
+ * Assert that a set of properties files all contain the same data.
+ * We cannot simply check the md5sums here, since Properties files
+ * contain timestamps -- thus, two properties files from the same
+ * saveNamespace operation may actually differ in md5sum.
+ * @param propFiles the files to compare
+ * @throws IOException if the files cannot be opened or read
+ * @throws AssertionError if the files differ
+ */
+ public static void assertPropertiesFilesSame(File[] propFiles)
+ throws IOException {
+ Set<Map.Entry<Object, Object>> prevProps = null;
+
+ for (File f : propFiles) {
+ Properties props;
+ FileInputStream is = new FileInputStream(f);
+ try {
+ props = new Properties();
+ props.load(is);
+ } finally {
+ IOUtils.closeStream(is);
+ }
+ if (prevProps == null) {
+ prevProps = props.entrySet();
+ } else {
+ Set<Entry<Object,Object>> diff =
+ Sets.symmetricDifference(prevProps, props.entrySet());
+ if (!diff.isEmpty()) {
+ fail("Properties file " + f + " differs from " + propFiles[0]);
+ }
+ }
+ }
+ }
+
/**
* Assert that all of the given paths have the exact same
* contents
|
39982c0bc8abc5b7bfa8731f6df65037727297f4
|
tapiji
|
Renames branch 'master_tmp' to 'master'.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.apache.commons.io/.classpath b/org.apache.commons.io/.classpath
new file mode 100644
index 00000000..f2d41466
--- /dev/null
+++ b/org.apache.commons.io/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry exported="true" kind="lib" path=""/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.apache.commons.io/.project b/org.apache.commons.io/.project
new file mode 100644
index 00000000..b4ddad64
--- /dev/null
+++ b/org.apache.commons.io/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.apache.commons.io</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs b/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..2f1261fd
--- /dev/null
+++ b/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Sat Apr 21 11:12:43 CEST 2012
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.apache.commons.io/META-INF/LICENSE.txt b/org.apache.commons.io/META-INF/LICENSE.txt
new file mode 100644
index 00000000..43e91eb0
--- /dev/null
+++ b/org.apache.commons.io/META-INF/LICENSE.txt
@@ -0,0 +1,203 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/org.apache.commons.io/META-INF/MANIFEST.MF b/org.apache.commons.io/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..79a52482
--- /dev/null
+++ b/org.apache.commons.io/META-INF/MANIFEST.MF
@@ -0,0 +1,12 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Apache Commons IO
+Bundle-SymbolicName: org.apache.commons.io
+Bundle-Version: 1.0.0
+Export-Package: org.apache.commons.io,
+ org.apache.commons.io.comparator,
+ org.apache.commons.io.filefilter,
+ org.apache.commons.io.input,
+ org.apache.commons.io.monitor,
+ org.apache.commons.io.output
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.apache.commons.io/META-INF/NOTICE.txt b/org.apache.commons.io/META-INF/NOTICE.txt
new file mode 100644
index 00000000..7632eb8e
--- /dev/null
+++ b/org.apache.commons.io/META-INF/NOTICE.txt
@@ -0,0 +1,6 @@
+Apache Commons IO
+Copyright 2002-2012 The Apache Software Foundation
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).
+
diff --git a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties
new file mode 100644
index 00000000..b3e76eb3
--- /dev/null
+++ b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties
@@ -0,0 +1,5 @@
+#Generated by Maven
+#Tue Apr 10 11:00:26 EDT 2012
+version=2.3
+groupId=commons-io
+artifactId=commons-io
diff --git a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml
new file mode 100644
index 00000000..bae10d22
--- /dev/null
+++ b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml
@@ -0,0 +1,346 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-parent</artifactId>
+ <version>24</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.3</version>
+ <name>Commons IO</name>
+
+ <inceptionYear>2002</inceptionYear>
+ <description>
+The Commons IO library contains utility classes, stream implementations, file filters,
+file comparators, endian transformation classes, and much more.
+ </description>
+
+ <url>http://commons.apache.org/io/</url>
+
+ <issueManagement>
+ <system>jira</system>
+ <url>http://issues.apache.org/jira/browse/IO</url>
+ </issueManagement>
+
+ <distributionManagement>
+ <site>
+ <id>apache.website</id>
+ <name>Apache Commons IO Site</name>
+ <url>${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid}</url>
+ </site>
+ </distributionManagement>
+
+ <scm>
+ <connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/io/trunk</connection>
+ <developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/io/trunk</developerConnection>
+ <url>http://svn.apache.org/viewvc/commons/proper/io/trunk</url>
+ </scm>
+
+ <developers>
+ <developer>
+ <name>Scott Sanders</name>
+ <id>sanders</id>
+ <email>[email protected]</email>
+ <organization></organization>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>dIon Gillard</name>
+ <id>dion</id>
+ <email>[email protected]</email>
+ <organization></organization>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Nicola Ken Barozzi</name>
+ <id>nicolaken</id>
+ <email>[email protected]</email>
+ <organization></organization>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Henri Yandell</name>
+ <id>bayard</id>
+ <email>[email protected]</email>
+ <organization></organization>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Stephen Colebourne</name>
+ <id>scolebourne</id>
+ <organization></organization>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ <timezone>0</timezone>
+ </developer>
+ <developer>
+ <name>Jeremias Maerki</name>
+ <id>jeremias</id>
+ <email>[email protected]</email>
+ <organization />
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ <timezone>+1</timezone>
+ </developer>
+ <developer>
+ <name>Matthew Hawthorne</name>
+ <id>matth</id>
+ <email>[email protected]</email>
+ <organization />
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Martin Cooper</name>
+ <id>martinc</id>
+ <email>[email protected]</email>
+ <organization />
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Rob Oxspring</name>
+ <id>roxspring</id>
+ <email>[email protected]</email>
+ <organization />
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Jochen Wiedmann</name>
+ <id>jochen</id>
+ <email>[email protected]</email>
+ </developer>
+ <developer>
+ <name>Niall Pemberton</name>
+ <id>niallp</id>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Jukka Zitting</name>
+ <id>jukka</id>
+ <roles>
+ <role>Java Developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <name>Gary Gregory</name>
+ <id>ggregory</id>
+ <email>[email protected]</email>
+ <url>http://www.garygregory.com</url>
+ <timezone>-5</timezone>
+ </developer>
+ </developers>
+
+ <contributors>
+ <contributor>
+ <name>Rahul Akolkar</name>
+ </contributor>
+ <contributor>
+ <name>Jason Anderson</name>
+ </contributor>
+ <contributor>
+ <name>Nathan Beyer</name>
+ </contributor>
+ <contributor>
+ <name>Emmanuel Bourg</name>
+ </contributor>
+ <contributor>
+ <name>Chris Eldredge</name>
+ </contributor>
+ <contributor>
+ <name>Magnus Grimsell</name>
+ </contributor>
+ <contributor>
+ <name>Jim Harrington</name>
+ </contributor>
+ <contributor>
+ <name>Thomas Ledoux</name>
+ </contributor>
+ <contributor>
+ <name>Andy Lehane</name>
+ </contributor>
+ <contributor>
+ <name>Marcelo Liberato</name>
+ </contributor>
+ <contributor>
+ <name>Alban Peignier</name>
+ <email>alban.peignier at free.fr</email>
+ </contributor>
+ <contributor>
+ <name>Ian Springer</name>
+ </contributor>
+ <contributor>
+ <name>Masato Tezuka</name>
+ </contributor>
+ <contributor>
+ <name>James Urie</name>
+ </contributor>
+ <contributor>
+ <name>Frank W. Zammetti</name>
+ </contributor>
+ </contributors>
+
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.10</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <properties>
+ <maven.compile.source>1.6</maven.compile.source>
+ <maven.compile.target>1.6</maven.compile.target>
+ <commons.componentid>io</commons.componentid>
+ <commons.rc.version>RC1</commons.rc.version>
+ <commons.release.version>2.3</commons.release.version>
+ <commons.release.desc>(requires JDK 1.6+)</commons.release.desc>
+ <commons.release.2.version>2.2</commons.release.2.version>
+ <commons.release.2.desc>(requires JDK 1.5+)</commons.release.2.desc>
+ <commons.jira.id>IO</commons.jira.id>
+ <commons.jira.pid>12310477</commons.jira.pid>
+ <!-- temporary override of parent -->
+ <commons.clirr.version>2.4</commons.clirr.version>
+ </properties>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <!-- Temporarily needed until CP25 is available -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>clirr-maven-plugin</artifactId>
+ <version>${commons.clirr.version}</version>
+ <configuration>
+ <minSeverity>${minSeverity}</minSeverity>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <forkMode>pertest</forkMode>
+ <!-- limit memory size see IO-161 -->
+ <argLine>-Xmx25M</argLine>
+ <includes>
+ <!-- Only include test classes, not test data -->
+ <include>**/*Test*.class</include>
+ </includes>
+ <excludes>
+ <exclude>**/*AbstractTestCase*</exclude>
+ <exclude>**/testtools/**</exclude>
+
+ <!-- http://jira.codehaus.org/browse/SUREFIRE-44 -->
+ <exclude>**/*$*</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/bin.xml</descriptor>
+ <descriptor>src/main/assembly/src.xml</descriptor>
+ </descriptors>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>2.9.1</version>
+ <configuration>
+ <configLocation>${basedir}/checkstyle.xml</configLocation>
+ <enableRulesSummary>false</enableRulesSummary>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>2.4.0</version>
+ <configuration>
+ <threshold>Normal</threshold>
+ <effort>Default</effort>
+ <excludeFilterFile>${basedir}/findbugs-exclude-filter.xml</excludeFilterFile>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-changes-plugin</artifactId>
+ <version>${commons.changes.version}</version>
+ <configuration>
+ <xmlPath>${basedir}/src/changes/changes.xml</xmlPath>
+ <columnNames>Fix Version,Key,Component,Summary,Type,Resolution,Status</columnNames>
+ <!-- Sort cols have to be reversed in JIRA 4 -->
+ <sortColumnNames>Key DESC,Type,Fix Version DESC</sortColumnNames>
+ <resolutionIds>Fixed</resolutionIds>
+ <statusIds>Resolved,Closed</statusIds>
+ <!-- Don't include sub-task -->
+ <typeIds>Bug,New Feature,Task,Improvement,Wish,Test</typeIds>
+ <maxEntries>300</maxEntries>
+ </configuration>
+ <reportSets>
+ <reportSet>
+ <reports>
+ <report>changes-report</report>
+ <report>jira-report</report>
+ </reports>
+ </reportSet>
+ </reportSets>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.rat</groupId>
+ <artifactId>apache-rat-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <exclude>src/test/resources/**/*.bin</exclude>
+ <exclude>.pmd</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+</project>
diff --git a/org.apache.commons.io/build.properties b/org.apache.commons.io/build.properties
new file mode 100644
index 00000000..1ac73bad
--- /dev/null
+++ b/org.apache.commons.io/build.properties
@@ -0,0 +1,3 @@
+output.. = .
+bin.includes = META-INF/,\
+ org/
diff --git a/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class b/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class
new file mode 100644
index 00000000..8bebf2de
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/Charsets.class b/org.apache.commons.io/org/apache/commons/io/Charsets.class
new file mode 100644
index 00000000..88a74baf
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/Charsets.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/CopyUtils.class b/org.apache.commons.io/org/apache/commons/io/CopyUtils.class
new file mode 100644
index 00000000..6de1db52
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/CopyUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class
new file mode 100644
index 00000000..ed333c99
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class
new file mode 100644
index 00000000..db7fc482
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/EndianUtils.class b/org.apache.commons.io/org/apache/commons/io/EndianUtils.class
new file mode 100644
index 00000000..f4b0af54
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/EndianUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaner.class b/org.apache.commons.io/org/apache/commons/io/FileCleaner.class
new file mode 100644
index 00000000..17ee0f8b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileCleaner.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class
new file mode 100644
index 00000000..6c0a2d53
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class
new file mode 100644
index 00000000..063d71c0
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class
new file mode 100644
index 00000000..f793406b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class
new file mode 100644
index 00000000..49b9d33c
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class
new file mode 100644
index 00000000..8731c9c9
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileExistsException.class b/org.apache.commons.io/org/apache/commons/io/FileExistsException.class
new file mode 100644
index 00000000..8eef129b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileExistsException.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class b/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class
new file mode 100644
index 00000000..68888e3a
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileUtils.class b/org.apache.commons.io/org/apache/commons/io/FileUtils.class
new file mode 100644
index 00000000..f2d4c17c
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FileUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class b/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class
new file mode 100644
index 00000000..059b648a
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/HexDump.class b/org.apache.commons.io/org/apache/commons/io/HexDump.class
new file mode 100644
index 00000000..c88a861e
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/HexDump.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/IOCase.class b/org.apache.commons.io/org/apache/commons/io/IOCase.class
new file mode 100644
index 00000000..26f6e6da
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/IOCase.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class b/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class
new file mode 100644
index 00000000..e0835d50
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/IOUtils.class b/org.apache.commons.io/org/apache/commons/io/IOUtils.class
new file mode 100644
index 00000000..725d4f68
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/IOUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/LineIterator.class b/org.apache.commons.io/org/apache/commons/io/LineIterator.class
new file mode 100644
index 00000000..08221a75
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/LineIterator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class b/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class
new file mode 100644
index 00000000..1eddd012
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class b/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class
new file mode 100644
index 00000000..5719a356
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class
new file mode 100644
index 00000000..a3e8b2e2
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class
new file mode 100644
index 00000000..b5774654
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class
new file mode 100644
index 00000000..19e76e80
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class
new file mode 100644
index 00000000..6718ac63
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class
new file mode 100644
index 00000000..11a85482
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class
new file mode 100644
index 00000000..b12636e8
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class
new file mode 100644
index 00000000..ed030680
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class
new file mode 100644
index 00000000..4effb1be
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class
new file mode 100644
index 00000000..f616dc37
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class
new file mode 100644
index 00000000..ad506044
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class
new file mode 100644
index 00000000..f00eaae1
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class
new file mode 100644
index 00000000..f02c5716
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class
new file mode 100644
index 00000000..601b4d26
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class
new file mode 100644
index 00000000..26665156
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class
new file mode 100644
index 00000000..9d6a2977
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class
new file mode 100644
index 00000000..903e3ab2
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class
new file mode 100644
index 00000000..049d673f
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class
new file mode 100644
index 00000000..89f1b8a6
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class
new file mode 100644
index 00000000..79377308
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class
new file mode 100644
index 00000000..f5b36c5b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class
new file mode 100644
index 00000000..ed3ca02d
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class
new file mode 100644
index 00000000..9165c54b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class
new file mode 100644
index 00000000..4c8efb7f
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class
new file mode 100644
index 00000000..c602e578
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class
new file mode 100644
index 00000000..406c5058
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class
new file mode 100644
index 00000000..413a5f08
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class
new file mode 100644
index 00000000..e1cd2877
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class
new file mode 100644
index 00000000..74a1b5ce
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class
new file mode 100644
index 00000000..8001d9ee
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class
new file mode 100644
index 00000000..c2fa2b41
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class
new file mode 100644
index 00000000..df634ec6
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class
new file mode 100644
index 00000000..f213e1c6
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class
new file mode 100644
index 00000000..2a162e39
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class
new file mode 100644
index 00000000..75ab2b8d
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class
new file mode 100644
index 00000000..c6726689
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class
new file mode 100644
index 00000000..b46d8845
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class
new file mode 100644
index 00000000..3b186d4e
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class
new file mode 100644
index 00000000..3aa01980
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class
new file mode 100644
index 00000000..ed86c824
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class
new file mode 100644
index 00000000..d56d99d4
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class
new file mode 100644
index 00000000..cba1c0fc
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class
new file mode 100644
index 00000000..7280e831
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class
new file mode 100644
index 00000000..89c5b5d0
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class
new file mode 100644
index 00000000..77110a09
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class
new file mode 100644
index 00000000..e391e3a0
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class
new file mode 100644
index 00000000..c1c62315
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class
new file mode 100644
index 00000000..fe780a58
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/NullReader.class b/org.apache.commons.io/org/apache/commons/io/input/NullReader.class
new file mode 100644
index 00000000..f6ce8309
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/NullReader.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class
new file mode 100644
index 00000000..bcb63360
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class b/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class
new file mode 100644
index 00000000..0e88acc8
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class
new file mode 100644
index 00000000..33b0e11a
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class
new file mode 100644
index 00000000..e7a796ca
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class
new file mode 100644
index 00000000..ddb4de84
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class
new file mode 100644
index 00000000..2f4819a2
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class
new file mode 100644
index 00000000..15ccb85c
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class
new file mode 100644
index 00000000..2e3c7571
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/Tailer.class b/org.apache.commons.io/org/apache/commons/io/input/Tailer.class
new file mode 100644
index 00000000..100e2959
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/Tailer.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class b/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class
new file mode 100644
index 00000000..a0f1b7d9
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class b/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class
new file mode 100644
index 00000000..44b075de
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class
new file mode 100644
index 00000000..534db867
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class
new file mode 100644
index 00000000..9a82342f
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class
new file mode 100644
index 00000000..d0d2cf4b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class
new file mode 100644
index 00000000..90ffd926
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class
new file mode 100644
index 00000000..e3f7f582
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class
new file mode 100644
index 00000000..d7694004
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class
new file mode 100644
index 00000000..d3f0cf7a
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class
new file mode 100644
index 00000000..eb8bd5de
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class
new file mode 100644
index 00000000..06c9873e
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class
new file mode 100644
index 00000000..e0279aaa
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class
new file mode 100644
index 00000000..734579ba
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class
new file mode 100644
index 00000000..c8dd34de
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class
new file mode 100644
index 00000000..65d60dd8
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class
new file mode 100644
index 00000000..a27ea22b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class
new file mode 100644
index 00000000..64eb167b
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class b/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class
new file mode 100644
index 00000000..c40975b5
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class b/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class
new file mode 100644
index 00000000..92f1a8f6
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class
new file mode 100644
index 00000000..c9a9e1d9
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class b/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class
new file mode 100644
index 00000000..7794b638
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class
new file mode 100644
index 00000000..e0619cc9
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class b/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class
new file mode 100644
index 00000000..93a958c3
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class b/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class
new file mode 100644
index 00000000..190828ef
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class
new file mode 100644
index 00000000..52b5a498
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class
new file mode 100644
index 00000000..7de3c99f
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class
new file mode 100644
index 00000000..370a0322
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class
new file mode 100644
index 00000000..ec9e6770
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class b/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class
new file mode 100644
index 00000000..c2b8e394
Binary files /dev/null and b/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class differ
diff --git a/org.eclipse.babel.core/META-INF/MANIFEST.MF b/org.eclipse.babel.core/META-INF/MANIFEST.MF
index ddee7a2a..6fb3206e 100644
--- a/org.eclipse.babel.core/META-INF/MANIFEST.MF
+++ b/org.eclipse.babel.core/META-INF/MANIFEST.MF
@@ -4,23 +4,28 @@ Bundle-Name: Babel Core Plug-in
Bundle-SymbolicName: org.eclipse.babel.core;singleton:=true
Bundle-Version: 0.8.0.qualifier
Export-Package: org.eclipse.babel.core.configuration;uses:="org.eclipse.babel.core.message.resource.ser",
- org.eclipse.babel.core.message;
+ org.eclipse.babel.core.factory,
+ org.eclipse.babel.core.message,
+ org.eclipse.babel.core.message.checks;uses:="org.eclipse.babel.core.message.checks.proximity,org.eclipselabs.tapiji.translator.rbe.babel.bundle",
+ org.eclipse.babel.core.message.checks.internal,
+ org.eclipse.babel.core.message.checks.proximity,
+ org.eclipse.babel.core.message.internal;
uses:="org.eclipse.babel.core.message.resource,
org.eclipse.babel.core.message.strategy,
org.eclipse.core.resources,
org.eclipselabs.tapiji.translator.rbe.babel.bundle",
- org.eclipse.babel.core.message.checks;uses:="org.eclipse.babel.core.message.checks.proximity,org.eclipselabs.tapiji.translator.rbe.babel.bundle",
- org.eclipse.babel.core.message.checks.proximity,
org.eclipse.babel.core.message.manager;uses:="org.eclipse.core.resources,org.eclipselabs.tapiji.translator.rbe.babel.bundle",
- org.eclipse.babel.core.message.resource;uses:="org.eclipse.babel.core.message,org.eclipse.babel.core.message.resource.ser,org.eclipse.core.resources",
+ org.eclipse.babel.core.message.resource,
+ org.eclipse.babel.core.message.resource.internal;uses:="org.eclipse.babel.core.message,org.eclipse.babel.core.message.resource.ser,org.eclipse.core.resources",
org.eclipse.babel.core.message.resource.ser;uses:="org.eclipselabs.tapiji.translator.rbe.babel.bundle",
org.eclipse.babel.core.message.strategy;uses:="org.eclipse.babel.core.message.resource.ser,org.eclipse.babel.core.message,org.eclipse.core.resources",
- org.eclipse.babel.core.message.tree;uses:="org.eclipse.babel.core.message,org.eclipselabs.tapiji.translator.rbe.babel.bundle",
+ org.eclipse.babel.core.message.tree,
+ org.eclipse.babel.core.message.tree.internal,
org.eclipse.babel.core.message.tree.visitor;uses:="org.eclipse.babel.core.message,org.eclipselabs.tapiji.translator.rbe.babel.bundle",
org.eclipse.babel.core.util;uses:="org.eclipse.core.resources"
Require-Bundle: org.eclipse.core.databinding,
org.eclipse.core.resources,
org.eclipse.core.runtime,
- org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.2";visibility:=reexport,
- org.eclipse.jdt.core;bundle-version="3.6.2"
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
+ org.eclipse.jdt.core;bundle-version="3.6.2";resolution:=optional,
+ org.eclipselabs.tapiji.translator.rap.supplemental;bundle-version="0.0.2";resolution:=optional
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.eclipse.babel.core/schema/babelConfiguration.exsd b/org.eclipse.babel.core/schema/babelConfiguration.exsd
index 559ed5da..97a39619 100644
--- a/org.eclipse.babel.core/schema/babelConfiguration.exsd
+++ b/org.eclipse.babel.core/schema/babelConfiguration.exsd
@@ -1,12 +1,12 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
-<schema targetNamespace="at.allianz.gfb.core.base" xmlns="http://www.w3.org/2001/XMLSchema">
+<schema targetNamespace="org.eclipse.babel.core" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
<appinfo>
- <meta.schema plugin="at.allianz.gfb.core.base" id="IAddressSchemaConfigurator" name="IAddressSchemaConfigurator"/>
+ <meta.schema plugin="org.eclipse.babel.core" id="babelConfiguration" name="babelConfiguration"/>
</appinfo>
<documentation>
- [Enter description of this extension point.]
+ Xpt, which is implemented by TapiJI to provide access to TapiJIPreferences.
</documentation>
</annotation>
@@ -98,5 +98,22 @@
</documentation>
</annotation>
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ /*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - creation
+ ******************************************************************************/
+ </documentation>
+ </annotation>
</schema>
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 452726db..66639ae7 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,13 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+
package org.eclipse.babel.core.configuration;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
import org.eclipse.babel.core.message.resource.ser.IPropertiesSerializerConfig;
+import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
/**
+ * Singelton, which provides information regarding the configuration of:
+ * <li>TapiJI Preference Page: interface is {@link IConfiguration}</li>
+ * <li>Serializing {@link MessagesBundleGroup} to property file</li>
+ * <li>Deserializing {@link MessagesBundleGroup} from property file</li>
+ * <br><br>
*
* @author Alexej Strelzow
*/
@@ -41,6 +60,9 @@ private IConfiguration getConfig() {
return null;
}
+ /**
+ * @return The singleton instance
+ */
public static ConfigurationManager getInstance() {
if (INSTANCE == null) {
INSTANCE = new ConfigurationManager();
@@ -48,22 +70,37 @@ public static ConfigurationManager getInstance() {
return INSTANCE;
}
+ /**
+ * @return TapiJI configuration
+ */
public IConfiguration getConfiguration() {
return this.config;
}
+ /**
+ * @return Config needed for {@link PropertiesSerializer}
+ */
public IPropertiesSerializerConfig getSerializerConfig() {
return serializerConfig;
}
+ /**
+ * @param serializerConfig The config for serialization
+ */
public void setSerializerConfig(IPropertiesSerializerConfig serializerConfig) {
this.serializerConfig = serializerConfig;
}
+ /**
+ * @return Config needed for {@link PropertiesDeserializer}
+ */
public IPropertiesDeserializerConfig getDeserializerConfig() {
return deserializerConfig;
}
+ /**
+ * @param serializerConfig The config for deserialization
+ */
public void setDeserializerConfig(
IPropertiesDeserializerConfig deserializerConfig) {
this.deserializerConfig = deserializerConfig;
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 8cec088f..ba1770bc 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,8 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+
package org.eclipse.babel.core.configuration;
+import org.eclipse.babel.core.message.internal.AbstractMessageModel;
+
+/**
+ * Contains following two <b>dirty</b> workaround flags:
+ * <li><b>fireEnabled:</b> deactivates {@link PropertyChangeEvent}-fire in {@link AbstractMessageModel}</li>
+ * <li><b>editorModificationEnabled:</b> prevents <code>EclipsePropertiesEditorResource#setText</code></li>
+ * <br><br>
+ * <b>We need to get rid of this somehow!!!!!!!!!</b>
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
public final class DirtyHack {
- private static boolean fireEnabled = true; // no property-fire calls in in AbstractMessageModel
+ private static boolean fireEnabled = true; // no property-fire calls in AbstractMessageModel
private static boolean editorModificationEnabled = true; // no setText in EclipsePropertiesEditorResource
// set this, if you serialize!
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 b0c1c069..4b8b26b1 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,21 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+
package org.eclipse.babel.core.configuration;
/**
+ * Interface to TapiJI preference page.
*
* @author Alexej Strelzow
*/
public interface IConfiguration {
boolean getAuditSameValue();
+
boolean getAuditMissingValue();
+
boolean getAuditMissingLanguage();
+
boolean getAuditRb();
+
boolean getAuditResource();
+
String getNonRbPattern();
-
-// convertStringToList(String)
-// convertListToString(List<CheckItem>)
-// addPropertyChangeListener(IPropertyChangeListener)
-// removePropertyChangeListener(IPropertyChangeListener)
-
+
}
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
new file mode 100644
index 00000000..b7c1bcd0
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+
+package org.eclipse.babel.core.factory;
+
+import java.util.Locale;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.internal.Message;
+
+/**
+ * Factory class for creating a {@link IMessage}
+ *
+ * @author Alexej Strelzow
+ */
+public class MessageFactory {
+
+ static Logger logger = Logger.getLogger(MessageFactory.class.getSimpleName());
+
+ /**
+ * @param key The key of the message
+ * @param locale The {@link Locale}
+ * @return An instance of {@link IMessage}
+ */
+ public static IMessage createMessage(String key, Locale locale) {
+ String l = locale == null ? "[default]" : locale.toString();
+ logger.log(Level.INFO, "createMessage, key: " + key + " locale: " + l);
+
+ return new Message(key, locale);
+ }
+
+}
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 a779ae45..2ac01f85 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,13 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+
package org.eclipse.babel.core.factory;
import java.io.File;
import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.babel.core.message.strategy.PropertiesFileGroupStrategy;
import org.eclipse.core.resources.IResource;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+/**
+ * Factory class for creating a {@link MessagesBundleGroup} with a {@link PropertiesFileGroupStrategy}.
+ * This is in use when we work with TapiJI only and not with <code>EclipsePropertiesEditorResource</code>.
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
public class MessagesBundleGroupFactory {
public static IMessagesBundleGroup createBundleGroup(IResource resource) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/AbstractIFileChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/AbstractIFileChangeListener.java
deleted file mode 100644
index 17e471e2..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/AbstractIFileChangeListener.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-
-/**
- * Same functionality than an {@link IResourceChangeListener} but listens to
- * a single file at a time. Subscribed and unsubscribed directly on
- * the MessageEditorPlugin.
- *
- * @author Hugues Malphettes
- */
-public abstract class AbstractIFileChangeListener {
-
- /**
- * Takes a IResourceChangeListener and wraps it into an AbstractIFileChangeListener.
- * <p>
- * Delegates the listenedFileChanged calls to the underlying
- * IResourceChangeListener#resourceChanged.
- * </p>
- * @param rcl
- * @param listenedFile
- * @return
- */
- public static AbstractIFileChangeListener wrapResourceChangeListener(
- final IResourceChangeListener rcl, IFile listenedFile) {
- return new AbstractIFileChangeListener(listenedFile) {
- public void listenedFileChanged(IResourceChangeEvent event) {
- rcl.resourceChanged(event);
- }
- };
- }
-
-
- //we use a string to be certain that no memory will leak from this class:
- //there is nothing to do a priori to dispose of this class.
- private final String listenedFileFullPath;
-
- /**
- * @param listenedFile The file this object listens to. It is final.
- */
- public AbstractIFileChangeListener(IFile listenedFile) {
- listenedFileFullPath = listenedFile.getFullPath().toString();
- }
-
- /**
- * @return The file listened to. It is final.
- */
- public final String getListenedFileFullPath() {
- return listenedFileFullPath;
- }
-
- /**
- * @param event The change event. It is guaranteed that this
- * event's getResource() method returns the file that this object listens to.
- */
- public abstract void listenedFileChanged(IResourceChangeEvent event);
-
- /**
- * Interface implemented by the MessageEditorPlugin.
- * <p>
- * Describes the registry of file change listeners.
- *
- * </p>
- */
- public interface IFileChangeListenerRegistry {
- /**
- * @param rcl Adds a subscriber to a resource change event.
- */
- public void subscribe(AbstractIFileChangeListener fileChangeListener);
-
- /**
- * @param rcl Removes a subscriber to a resource change event.
- */
- public void unsubscribe(AbstractIFileChangeListener fileChangeListener);
- }
-
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/AbstractMessageModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/AbstractMessageModel.java
deleted file mode 100644
index 19e2df4e..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/AbstractMessageModel.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-import java.io.Serializable;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.util.BabelUtils;
-
-
-/**
- * A convenience base class for observable message-related classes.
- * This class follows the conventions and recommendations as described
- * in the <a href="http://java.sun.com/products/javabeans/docs/spec.html">SUN
- * JavaBean specifications</a>.
- *
- * @author Pascal Essiembre ([email protected])
- * @author Karsten Lentzsch ([email protected])
- */
-public abstract class AbstractMessageModel implements Serializable {
- /** Handles <code>PropertyChangeListeners</code>. */
- private transient PropertyChangeSupport changeSupport;
-
- /**
- * Adds a PropertyChangeListener to the listener list. The listener is
- * registered for all properties of this class.<p>
- * Adding a <code>null</code> listener has no effect.
- *
- * @param listener the PropertyChangeListener to be added
- */
- /*default*/ final synchronized void addPropertyChangeListener(
- final PropertyChangeListener listener) {
- if (listener == null) {
- return;
- }
- if (changeSupport == null) {
- changeSupport = new PropertyChangeSupport(this);
- }
- changeSupport.addPropertyChangeListener(listener);
- }
-
- /**
- * Removes a PropertyChangeListener from the listener list. This method
- * should be used to remove PropertyChangeListeners that were registered
- * for all bound properties of this class.<p>
- * Removing a <code>null</code> listener has no effect.
- *
- * @param listener the PropertyChangeListener to be removed
- */
- /*default*/ final synchronized void removePropertyChangeListener(
- final PropertyChangeListener listener) {
- if (listener == null || changeSupport == null) {
- return;
- }
- changeSupport.removePropertyChangeListener(listener);
- }
-
- /**
- * Returns an array of all the property change listeners registered on
- * this component.
- *
- * @return all of this component's <code>PropertyChangeListener</code>s
- * or an empty array if no property change
- * listeners are currently registered
- */
- /*default*/ final synchronized
- PropertyChangeListener[] getPropertyChangeListeners() {
- if (changeSupport == null) {
- return new PropertyChangeListener[0];
- }
- return changeSupport.getPropertyChangeListeners();
- }
-
- /**
- * Support for reporting bound property changes for Object properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final Object oldValue,
- final Object newValue) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(propertyName, oldValue, newValue);
- }
-
- /**
- * Support for reporting bound property changes for boolean properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final boolean oldValue,
- final boolean newValue) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(propertyName, oldValue, newValue);
- }
-
- /**
- * Support for reporting bound property changes for events.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param event the event that triggered the change
- */
- protected final void firePropertyChange(
- final PropertyChangeEvent event) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(event);
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final double oldValue,
- final double newValue) {
- firePropertyChange(
- propertyName, new Double(oldValue), new Double(newValue));
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final float oldValue,
- final float newValue) {
- firePropertyChange(
- propertyName, new Float(oldValue), new Float(newValue));
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final int oldValue,
- final int newValue) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(propertyName, oldValue, newValue);
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final long oldValue,
- final long newValue) {
- firePropertyChange(
- propertyName, new Long(oldValue), new Long(newValue));
- }
-
- /**
- * Checks and answers if the two objects are both <code>null</code>
- * or equal.
- *
- * @param o1 the first object to compare
- * @param o2 the second object to compare
- * @return boolean true if and only if both objects are <code>null</code>
- * or equal
- */
- protected final boolean equals(final Object o1, final Object o2) {
- return BabelUtils.equals(o1, o2);
- }
-}
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
new file mode 100644
index 00000000..779af4a0
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java
@@ -0,0 +1,85 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - extended API
+ ******************************************************************************/
+package org.eclipse.babel.core.message;
+
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.internal.Message;
+
+/**
+ * Interface, implemented by {@link Message}. A message is an abstraction of a
+ * key-value pair, which can be found in resource bundles (1 row).
+ * <br><br>
+ *
+ * @author Martin Reiterer, Alexej Strelzow
+ */
+public interface IMessage {
+
+ /**
+ * Gets the message key attribute.
+ * @return Returns the key.
+ */
+ String getKey();
+
+ /**
+ * Gets the message text.
+ * @return Returns the text.
+ */
+ String getValue();
+
+ /**
+ * Gets the message locale.
+ * @return Returns the locale
+ */
+ Locale getLocale();
+
+ /**
+ * Gets the comment associated with this message (<code>null</code> if
+ * no comments).
+ * @return Returns the comment.
+ */
+ String getComment();
+
+ /**
+ * Gets whether this message is active or not.
+ * @return <code>true</code> if this message is active.
+ */
+ boolean isActive();
+
+ /**
+ * @return The toString representation
+ */
+ String toString();
+
+ /**
+ * Sets whether the message is active or not. An inactive message is
+ * one that we continue to keep track of, but will not be picked
+ * up by internationalization mechanism (e.g. <code>ResourceBundle</code>).
+ * Typically, those are commented (i.e. //) key/text pairs in a
+ * *.properties file.
+ * @param active The active to set.
+ */
+ void setActive(boolean active);
+
+ /**
+ * Sets the message comment.
+ * @param comment The comment to set.
+ */
+ void setComment(String comment);
+
+ /**
+ * Sets the actual message text.
+ * @param text The text to set.
+ */
+ void setText(String test);
+
+}
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
new file mode 100644
index 00000000..c3c6c911
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java
@@ -0,0 +1,126 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - extended API
+ ******************************************************************************/
+package org.eclipse.babel.core.message;
+
+import java.util.Collection;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.internal.MessageException;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+
+/**
+ * Interface, implemented by {@link MessagesBundle}. A messages bundle is an abstraction of a
+ * resource bundle (the *.properties-file).
+ * <br><br>
+ *
+ * @author Martin Reiterer, Alexej Strelzow
+ */
+public interface IMessagesBundle {
+
+ /**
+ * Called before this object will be discarded.
+ */
+ void dispose();
+
+ /**
+ * Renames a message key.
+ * @param sourceKey the message key to rename
+ * @param targetKey the new key for the message
+ * @throws MessageException if the target key already exists
+ */
+ void renameMessageKey(String sourceKey, String targetKey);
+
+ /**
+ * Removes a message from this messages bundle.
+ * @param messageKey the key of the message to remove
+ */
+ void removeMessage(String messageKey);
+
+ /**
+ * Duplicates a message.
+ * @param sourceKey the message key to duplicate
+ * @param targetKey the new message key
+ * @throws MessageException if the target key already exists
+ */
+ void duplicateMessage(String sourceKey, String targetKey);
+
+ /**
+ * Gets the locale for the messages bundle (<code>null</code> assumes
+ * the default system locale).
+ * @return Returns the locale.
+ */
+ Locale getLocale();
+
+ /**
+ * Gets all message keys making up this messages bundle.
+ * @return message keys
+ */
+ String[] getKeys();
+
+ /**
+ * Returns the value to the given key, if the key exists.
+ * @param key, the key of a message.
+ * @return The value to the given key.
+ */
+ String getValue(String key);
+
+ /**
+ * Obtains the set of <code>Message</code> objects in this bundle.
+ * @return a collection of <code>Message</code> objects in this bundle
+ */
+ Collection<IMessage> getMessages();
+
+ /**
+ * Gets a message.
+ * @param key a message key
+ * @return a message
+ */
+ IMessage getMessage(String key);
+
+ /**
+ * Adds an empty message.
+ * @param key the new message key
+ */
+ void addMessage(IMessage message);
+
+ /**
+ * Removes messages from this messages bundle.
+ * @param messageKeys the keys of the messages to remove
+ */
+ void removeMessages(String[] messageKeys);
+
+ /**
+ * Sets the comment for this messages bundle.
+ * @param comment The comment to set.
+ */
+ void setComment(String comment);
+
+ /**
+ * Gets the overall comment, or description, for this messages bundle..
+ * @return Returns the comment.
+ */
+ String getComment();
+
+ /**
+ * Gets the underlying messages resource implementation.
+ * @return
+ */
+ IMessagesResource getResource();
+
+ /**
+ * Removes a message from this messages bundle and adds it's parent key to bundle.
+ * E.g.: key = a.b.c gets deleted, a.b gets added with a default message
+ * @param messageKey the key of the message to remove
+ */
+ void removeMessageAddParentKey(String key);
+}
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
new file mode 100644
index 00000000..13177f4b
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - extended API
+ ******************************************************************************/
+package org.eclipse.babel.core.message;
+
+import java.util.Collection;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.internal.MessageException;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.strategy.PropertiesFileGroupStrategy;
+
+/**
+ * Interface, implemented by {@link MessagesBundleGroup}. A messages bundle
+ * group is an abstraction of a group of resource bundles. <br>
+ * <br>
+ *
+ * @author Martin Reiterer, Alexej Strelzow
+ */
+public interface IMessagesBundleGroup {
+
+ /**
+ * Returns a collection of all bundles in this group.
+ * @return the bundles in this group
+ */
+ Collection<IMessagesBundle> getMessagesBundles();
+
+ /**
+ * Returns true if the supplied key is already existing in this group.
+ * @param key The key that shall be tested.
+ * @return true <=> The key is already existing.
+ */
+ boolean containsKey(String key);
+
+ /**
+ * Gets all messages associated with the given message key.
+ * @param key a message key
+ * @return messages
+ */
+ IMessage[] getMessages(String key);
+
+ /**
+ * Gets the message matching given key and locale.
+ * @param locale The locale for which to retrieve the message
+ * @param key The key matching entry to retrieve the message
+ * @return a message
+ */
+ IMessage getMessage(String key, Locale locale);
+
+ /**
+ * Gets the messages bundle matching given locale.
+ * @param locale The locale of bundle to retreive
+ * @return a bundle
+ */
+ IMessagesBundle getMessagesBundle(Locale locale);
+
+ /**
+ * Removes messages matching the given key from all messages bundle.
+ * @param key The key of messages to remove
+ */
+ void removeMessages(String messageKey);
+
+ /**
+ * Is the given key found in this bundle group.
+ * @param key The key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ boolean isKey(String key);
+
+ /**
+ * Adds a messages bundle to this group.
+ * @param locale The locale of the bundle
+ * @param messagesBundle bundle to add
+ * @throws MessageException if a messages bundle for the same locale already exists.
+ */
+ void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
+
+ /**
+ * Gets all keys from all messages bundles.
+ * @return all keys from all messages bundles
+ */
+ String[] getMessageKeys();
+
+ /**
+ * Adds an empty message to every messages bundle of this group with the
+ * given.
+ * @param key The message key
+ */
+ void addMessages(String key);
+
+ /**
+ * Gets the number of messages bundles in this group.
+ * @return the number of messages bundles in this group
+ */
+ int getMessagesBundleCount();
+
+ /**
+ * Gets this messages bundle group name. That is the name, which is used
+ * for the tab of the MultiPageEditorPart.
+ * @return bundle group name
+ */
+ String getName();
+
+ /**
+ * Gets the unique id of the bundle group. That is usually: <directory>"."<default-filename>.
+ * The default filename is without the suffix (e.g. _en, or _en_GB).
+ * @return The unique identifier for the resource bundle group
+ */
+ String getResourceBundleId();
+
+ /**
+ * @return <code>true</code> if the bundle group has {@link PropertiesFileGroupStrategy} as strategy,
+ * else <code>false</code>. This is the case, when only TapiJI edits the resource bundles and no
+ * have been opened.
+ */
+ boolean hasPropertiesFileGroupStrategy();
+
+ /**
+ * Whether the given key is found in this messages bundle group.
+ * @param key The key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ public boolean isMessageKey(String key);
+
+ /**
+ * Gets the name of the project, the resource bundle group is in.
+ * @return The project name
+ */
+ public String getProjectName();
+
+ /**
+ * Removes the {@link IMessagesBundle} from the group.
+ * @param messagesBundle The bundle to remove.
+ */
+ public void removeMessagesBundle(IMessagesBundle messagesBundle);
+
+ /**
+ * Called before this object will be discarded. Disposes the underlying
+ * MessageBundles
+ */
+ public void dispose();
+
+ /**
+ * Removes messages matching the given key from all messages bundle and add
+ * it's parent key to bundles.
+ *
+ * @param key The key of messages to remove
+ */
+ void removeMessagesAddParentKey(String key);
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroupListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroupListener.java
deleted file mode 100644
index d9bc54cf..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroupListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-
-/**
- * A listener for changes on a {@link MessagesBundleGroup}.
- * @author Pascal Essiembre ([email protected])
- * @see MessagesBundleGroup
- */
-public interface IMessagesBundleGroupListener extends IMessagesBundleListener {
-
- /**
- * A message key has been added.
- * @param key the added key
- */
- void keyAdded(String key);
- /**
- * A message key has been removed.
- * @param key the removed key
- */
- void keyRemoved(String key);
- /**
- * A messages bundle has been added.
- * @param messagesBundle the messages bundle
- */
- void messagesBundleAdded(MessagesBundle messagesBundle);
- /**
- * A messages bundle has been removed.
- * @param messagesBundle the messages bundle
- */
- void messagesBundleRemoved(MessagesBundle messagesBundle);
- /**
- * A messages bundle was modified.
- * @param messagesBundle the messages bundle
- */
- void messagesBundleChanged(
- MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
-
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleListener.java
deleted file mode 100644
index 7b40117a..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleListener.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-
-/**
- * A listener for changes on a {@link MessagesBundle}.
- * @author Pascal Essiembre ([email protected])
- * @see MessagesBundle
- */
-public interface IMessagesBundleListener extends PropertyChangeListener {
- /**
- * A message was added.
- * @param messagesBundle the messages bundle on which the message was added.
- * @param message the message
- */
- void messageAdded(MessagesBundle messagesBundle, Message message);
- /**
- * A message was removed.
- * @param messagesBundle the messages bundle on which the message was
- * removed.
- * @param message the message
- */
- void messageRemoved(MessagesBundle messagesBundle, Message message);
- /**
- * A message was changed.
- * @param messagesBundle the messages bundle on which the message was
- * changed.
- * @param message the message
- */
- void messageChanged(
- MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java
new file mode 100644
index 00000000..70f8650d
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.java
@@ -0,0 +1,30 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+
+package org.eclipse.babel.core.message;
+
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+
+/**
+ * Listener being notified when a {@link IMessagesResource} content changes.
+ *
+ * @author Pascal Essiembre
+ */
+public interface IMessagesResourceChangeListener {
+
+ /**
+ * Method called when the messages resource has changed.
+ *
+ * @param resource
+ * the resource that changed
+ */
+ void resourceChanged(IMessagesResource resource);
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/Message.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/Message.java
deleted file mode 100644
index ecb023c0..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/Message.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeListener;
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-
-/**
- * A single entry in a <code>MessagesBundle</code>.
- *
- * @author Pascal Essiembre ([email protected])
- * @see MessagesBundle
- * @see MessagesBundleGroup
- */
-public final class Message extends AbstractMessageModel implements IMessage {
-
- /** For serialisation. */
- private static final long serialVersionUID = 1160670351341655427L;
-
- public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
- public static final String PROPERTY_ACTIVE = "active"; //$NON-NLS-1$
- public static final String PROPERTY_TEXT = "text"; //$NON-NLS-1$
-
- /** Entry unique identifier. */
- private final String key;
- /** Entry locale. */
- private final Locale locale;
- /** Entry comment. */
- private String comment;
- /** Whether this entry is commented out or not. */
- private boolean active = true;
- /** Entry text. */
- private String text;
-
- /**
- * Constructor. Key and locale arguments are <code>null</code> safe.
- * @param key unique identifier within a messages bundle
- * @param locale the message locale
- */
- public Message(final String key, final Locale locale) {
- super();
- this.key = (key == null ? "" : key); //$NON-NLS-1$
- this.locale = locale;
- }
-
-
-
- /**
- * Sets the message comment.
- * @param comment The comment to set.
- */
- public void setComment(String comment) {
- Object oldValue = this.comment;
- this.comment = comment;
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
- }
-
- public void setComment(String comment, boolean silent) {
- Object oldValue = this.comment;
- this.comment = comment;
- if (!silent) {
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
- }
- }
-
- /**
- * Sets whether the message is active or not. An inactive message is
- * one that we continue to keep track of, but will not be picked
- * up by internationalisation mechanism (e.g. <code>ResourceBundle</code>).
- * Typically, those are commented (i.e. //) key/text pairs in a
- * *.properties file.
- * @param active The active to set.
- */
- public void setActive(boolean active) {
- boolean oldValue = this.active;
- this.active = active;
- firePropertyChange(PROPERTY_ACTIVE, oldValue, active);
- }
-
- /**
- * Sets the actual message text.
- * @param text The text to set.
- */
- public void setText(String text) {
- Object oldValue = this.text;
- this.text = text;
- firePropertyChange(PROPERTY_TEXT, oldValue, text);
- }
-
- public void setText(String text, boolean silent) {
- Object oldValue = this.text;
- this.text = text;
- if (!silent) {
- firePropertyChange(PROPERTY_TEXT, oldValue, text);
- }
- }
-
- /**
- * Gets the comment associated with this message (<code>null</code> if
- * no comments).
- * @return Returns the comment.
- */
- public String getComment() {
- return comment;
- }
- /**
- * Gets the message key attribute.
- * @return Returns the key.
- */
- public String getKey() {
- return key;
- }
-
- /**
- * Gets the message text.
- * @return Returns the text.
- */
- public String getValue() {
- return text;
- }
-
- /**
- * Gets the message locale.
- * @return Returns the locale
- */
- public Locale getLocale() {
- return locale;
- }
-
- /**
- * Gets whether this message is active or not.
- * @return <code>true</code> if this message is active.
- */
- public boolean isActive() {
- return active;
- }
-
- /**
- * Copies properties of the given message to this message.
- * The properties copied over are all properties but the
- * message key and locale.
- * @param message
- */
- protected void copyFrom(IMessage message) {
- setComment(message.getComment());
- setActive(message.isActive());
- setText(message.getValue());
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof Message)) {
- return false;
- }
- Message entry = (Message) obj;
- return equals(key, entry.key)
- && equals(locale, entry.locale)
- && active == entry.active
- && equals(text, entry.text)
- && equals(comment, entry.comment);
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "Message=[[key=" + key //$NON-NLS-1$
- + "][text=" + text //$NON-NLS-1$
- + "][comment=" + comment //$NON-NLS-1$
- + "][active=" + active //$NON-NLS-1$
- + "]]"; //$NON-NLS-1$
- }
-
- public final synchronized void addMessageListener(
- final PropertyChangeListener listener) {
- addPropertyChangeListener(listener);
- }
- public final synchronized void removeMessageListener(
- final PropertyChangeListener listener) {
- removePropertyChangeListener(listener);
- }
- public final synchronized PropertyChangeListener[] getMessageListeners() {
- return getPropertyChangeListeners();
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessageException.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessageException.java
deleted file mode 100644
index f9ba699b..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessageException.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-/**
- * Exception thrown when a message-related operation raised a problem.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessageException extends RuntimeException {
-
- /** For serialisation. */
- private static final long serialVersionUID = 5702621096263524623L;
-
- /**
- * Creates a new <code>MessageException</code>.
- */
- public MessageException() {
- super();
- }
-
- /**
- * Creates a new <code>MessageException</code>.
- * @param message exception message
- */
- public MessageException(String message) {
- super(message);
- }
-
- /**
- * Creates a new <code>MessageException</code>.
- * @param message exception message
- * @param cause root cause
- */
- public MessageException(String message, Throwable cause) {
- super(message, cause);
- }
-
- /**
- * Creates a new <code>MessageException</code>.
- * @param cause root cause
- */
- public MessageException(Throwable cause) {
- super(cause);
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundle.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundle.java
deleted file mode 100644
index 0d179c4f..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundle.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResourceChangeListener;
-
-/**
- * For a given scope, all messages for a national language.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundle extends AbstractMessageModel
- implements IMessagesResourceChangeListener, IMessagesBundle {
-
- private static final long serialVersionUID = -331515196227475652L;
-
- public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
- public static final String PROPERTY_MESSAGES_COUNT =
- "messagesCount"; //$NON-NLS-1$
-
- private static final IMessagesBundleListener[] EMPTY_MSG_BUNDLE_LISTENERS =
- new IMessagesBundleListener[] {};
- private final Collection<String> orderedKeys = new ArrayList<String>();
- private final Map<String, IMessage> keyedMessages = new HashMap<String, IMessage>();
-
- private final IMessagesResource resource;
-
- private final PropertyChangeListener messageListener =
- new PropertyChangeListener(){
- public void propertyChange(PropertyChangeEvent event) {
- fireMessageChanged(event);
- }
- };
- private String comment;
-
- /**
- * Creates a new <code>MessagesBundle</code>.
- * @param resource the messages bundle resource
- */
- public MessagesBundle(IMessagesResource resource) {
- super();
- this.resource = resource;
- readFromResource();
- // Handle resource changes
- resource.addMessagesResourceChangeListener(
- new IMessagesResourceChangeListener(){
- public void resourceChanged(IMessagesResource changedResource) {
- readFromResource();
- }
- });
- // Handle bundle changes
- addMessagesBundleListener(new MessagesBundleAdapter() {
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- writetoResource();
- }
- public void propertyChange(PropertyChangeEvent evt) {
- writetoResource();
- }
- });
- }
-
- /**
- * Called before this object will be discarded.
- */
- public void dispose() {
- this.resource.dispose();
- }
-
- /**
- * Gets the underlying messages resource implementation.
- * @return
- */
- public IMessagesResource getResource() {
- return resource;
- }
-
- public int getMessagesCount() {
- return keyedMessages.size();
- }
-
- /**
- * Gets the locale for the messages bundle (<code>null</code> assumes
- * the default system locale).
- * @return Returns the locale.
- */
- public Locale getLocale() {
- return resource.getLocale();
- }
-
- /**
- * Gets the overall comment, or description, for this messages bundle..
- * @return Returns the comment.
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the comment for this messages bundle.
- * @param comment The comment to set.
- */
- public void setComment(String comment) {
- Object oldValue = this.comment;
- this.comment = comment;
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource
- * .IMessagesResourceChangeListener#resourceChanged(
- * org.eclipse.babel.core.message.resource.IMessagesResource)
- */
- public void resourceChanged(IMessagesResource changedResource) {
- this.resource.deserialize(this);
- }
-
- /**
- * Adds a message to this messages bundle. If the message already exists
- * its properties are updated and no new message is added.
- * @param message the message to add
- */
- public void addMessage(IMessage message) {
- Message m = (Message) message;
- int oldCount = getMessagesCount();
- if (!orderedKeys.contains(m.getKey())) {
- orderedKeys.add(m.getKey());
- }
- if (!keyedMessages.containsKey(m.getKey())) {
- keyedMessages.put(m.getKey(), m);
- m.addMessageListener(messageListener);
- firePropertyChange(
- PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
- fireMessageAdded(m);
- } else {
- // Entry already exists, update it.
- Message matchingEntry = (Message) keyedMessages.get(m.getKey());
- matchingEntry.copyFrom(m);
- }
- }
- /**
- * Removes a message from this messages bundle.
- * @param messageKey the key of the message to remove
- */
- public void removeMessage(String messageKey) {
- int oldCount = getMessagesCount();
- orderedKeys.remove(messageKey);
- Message message = (Message) keyedMessages.get(messageKey);
- if (message != null) {
- message.removePropertyChangeListener(messageListener);
- keyedMessages.remove(messageKey);
- firePropertyChange(
- PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
- fireMessageRemoved(message);
- }
- }
- /**
- * Removes messages from this messages bundle.
- * @param messageKeys the keys of the messages to remove
- */
- public void removeMessages(String[] messageKeys) {
- for (int i = 0; i < messageKeys.length; i++) {
- removeMessage(messageKeys[i]);
- }
- }
-
- /**
- * Renames a message key.
- * @param sourceKey the message key to rename
- * @param targetKey the new key for the message
- * @throws MessageException if the target key already exists
- */
- public void renameMessageKey(String sourceKey, String targetKey) {
- if (getMessage(targetKey) != null) {
- throw new MessageException(
- "Cannot rename: target key already exists."); //$NON-NLS-1$
- }
- IMessage sourceEntry = getMessage(sourceKey);
- if (sourceEntry != null) {
- Message targetEntry = new Message(targetKey, getLocale());
- targetEntry.copyFrom(sourceEntry);
- removeMessage(sourceKey);
- addMessage(targetEntry);
- }
- }
- /**
- * Duplicates a message.
- * @param sourceKey the message key to duplicate
- * @param targetKey the new message key
- * @throws MessageException if the target key already exists
- */
- public void duplicateMessage(String sourceKey, String targetKey) {
- if (getMessage(sourceKey) != null) {
- throw new MessageException(
- "Cannot duplicate: target key already exists."); //$NON-NLS-1$
- }
- IMessage sourceEntry = getMessage(sourceKey);
- if (sourceEntry != null) {
- Message targetEntry = new Message(targetKey, getLocale());
- targetEntry.copyFrom(sourceEntry);
- addMessage(targetEntry);
- }
- }
-
- /**
- * Gets a message.
- * @param key a message key
- * @return a message
- */
- public IMessage getMessage(String key) {
- return keyedMessages.get(key);
- }
-
- /**
- * Adds an empty message.
- * @param key the new message key
- */
- public void addMessage(String key) {
- addMessage(new Message(key, getLocale()));
- }
-
- /**
- * Gets all message keys making up this messages bundle.
- * @return message keys
- */
- public String[] getKeys() {
- return orderedKeys.toArray(BabelUtils.EMPTY_STRINGS);
- }
-
- /**
- * Obtains the set of <code>Message</code> objects in this bundle.
- * @return a collection of <code>Message</code> objects in this bundle
- */
- public Collection<IMessage> getMessages() {
- return keyedMessages.values();
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- String str = "MessagesBundle=[[locale=" + getLocale() //$NON-NLS-1$
- + "][comment=" + comment //$NON-NLS-1$
- + "][entries="; //$NON-NLS-1$
- for (IMessage message : getMessages()) {
- str += message.toString();
- }
- str += "]]"; //$NON-NLS-1$
- return str;
- }
-
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- final int PRIME = 31;
- int result = 1;
- result = PRIME * result + ((comment == null) ? 0 : comment.hashCode());
- result = PRIME * result + ((messageListener == null)
- ? 0 : messageListener.hashCode());
- result = PRIME * result + ((keyedMessages == null)
- ? 0 : keyedMessages.hashCode());
- result = PRIME * result + ((orderedKeys == null)
- ? 0 : orderedKeys.hashCode());
- result = PRIME * result + ((resource == null)
- ? 0 : resource.hashCode());
- return result;
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof MessagesBundle)) {
- return false;
- }
- MessagesBundle messagesBundle = (MessagesBundle) obj;
- return equals(comment, messagesBundle.comment)
- && equals(keyedMessages, messagesBundle.keyedMessages);
- }
-
- public final synchronized void addMessagesBundleListener(
- final IMessagesBundleListener listener) {
- addPropertyChangeListener(listener);
- }
- public final synchronized void removeMessagesBundleListener(
- final IMessagesBundleListener listener) {
- removePropertyChangeListener(listener);
- }
- public final synchronized IMessagesBundleListener[]
- getMessagesBundleListeners() {
- //TODO find more efficient way to avoid class cast.
- return Arrays.asList(
- getPropertyChangeListeners()).toArray(
- EMPTY_MSG_BUNDLE_LISTENERS);
- }
-
-
- private void readFromResource() {
- this.resource.deserialize(this);
- }
- private void writetoResource() {
- this.resource.serialize(this);
- }
-
- private void fireMessageAdded(Message message) {
- IMessagesBundleListener[] listeners = getMessagesBundleListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleListener listener = listeners[i];
- listener.messageAdded(this, message);
- }
- }
- private void fireMessageRemoved(Message message) {
- IMessagesBundleListener[] listeners = getMessagesBundleListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleListener listener = listeners[i];
- listener.messageRemoved(this, message);
- }
- }
- private void fireMessageChanged(PropertyChangeEvent event) {
- IMessagesBundleListener[] listeners = getMessagesBundleListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleListener listener = listeners[i];
- listener.messageChanged(this, event);
- }
- }
-
- public String getValue(String key) {
- return getMessage(key).getValue();
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleAdapter.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleAdapter.java
deleted file mode 100644
index 7fb621b8..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleAdapter.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-
-/**
- * An adapter class for a {@link IMessagesBundleListener}. Methods
- * implementation do nothing.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundleAdapter implements IMessagesBundleListener {
-
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleListener#messageAdded(
- * org.eclipse.babel.core.message.MessagesBundle,
- * org.eclipse.babel.core.message.Message)
- */
- public void messageAdded(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleListener
- * #messageChanged(org.eclipse.babel.core.message.MessagesBundle,
- * java.beans.PropertyChangeEvent)
- */
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleListener
- * #messageRemoved(org.eclipse.babel.core.message.MessagesBundle,
- * org.eclipse.babel.core.message.Message)
- */
- public void messageRemoved(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see java.beans.PropertyChangeListener#propertyChange(
- * java.beans.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent evt) {
- // do nothing
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java
deleted file mode 100644
index df850e16..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java
+++ /dev/null
@@ -1,511 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy;
-import org.eclipse.babel.core.message.strategy.PropertiesFileGroupStrategy;
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-/**
- * Grouping of all messages bundle of the same kind.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundleGroup extends AbstractMessageModel implements IMessagesBundleGroup {
-
- private String projectName;
-
- private static final IMessagesBundleGroupListener[]
- EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {};
- private static final Message[] EMPTY_MESSAGES = new Message[] {};
-
- public static final String PROPERTY_MESSAGES_BUNDLE_COUNT =
- "messagesBundleCount"; //$NON-NLS-1$
- public static final String PROPERTY_KEY_COUNT =
- "keyCount"; //$NON-NLS-1$
-
- /** For serialization. */
- private static final long serialVersionUID = -1977849534191384324L;
- /** Bundles forming the group (key=Locale; value=MessagesBundle). */
- private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>();
- private final Set<String> keys = new TreeSet<String>();
- private final IMessagesBundleListener messagesBundleListener =
- new MessagesBundleListener();
-
- private final IMessagesBundleGroupStrategy groupStrategy;
- private static final Locale[] EMPTY_LOCALES = new Locale[] {};
- private final String name;
- private final String resourceBundleId;
-
- /**
- * Creates a new messages bundle group.
- * @param groupStrategy a IMessagesBundleGroupStrategy instance
- */
- public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) {
- super();
- this.groupStrategy = groupStrategy;
- this.name = groupStrategy.createMessagesBundleGroupName();
- this.resourceBundleId = groupStrategy.createMessagesBundleId();
-
- this.projectName = groupStrategy.getProjectName();
-
- MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
- if (bundles != null) {
- for (int i = 0; i < bundles.length; i++) {
- addMessagesBundle(bundles[i]);
- }
- }
-
- RBManager.getInstance(this.projectName).notifyMessagesBundleCreated(this);
- }
-
- /**
- * Called before this object will be discarded.
- * Disposes the underlying MessageBundles
- */
- public void dispose() {
- for (IMessagesBundle mb : getMessagesBundles()) {
- try {
- mb.dispose();
- } catch (Throwable t) {
- //FIXME: remove debug:
- System.err.println("Error disposing message-bundle " +
- ((MessagesBundle)mb).getResource().getResourceLocationLabel());
- //disregard crashes: this is a best effort to dispose things.
- }
- }
-
- RBManager.getInstance(this.projectName).notifyMessagesBundleDeleted(this);
- }
-
-
- /**
- * Gets the messages bundle matching given locale.
- * @param locale locale of bundle to retreive
- * @return a bundle
- */
- public IMessagesBundle getMessagesBundle(Locale locale) {
- return localeBundles.get(locale);
- }
-
- /**
- * Gets the messages bundle matching given source object. A source
- * object being a context-specific concrete underlying implementation of a
- * <code>MessagesBundle</code> as per defined in
- * <code>IMessageResource</code>.
- * @param source the source object to match
- * @return a messages bundle
- * @see IMessagesResource
- */
- public MessagesBundle getMessagesBundle(Object source) {
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- if (equals(source, ((MessagesBundle)messagesBundle).getResource().getSource())) {
- return (MessagesBundle) messagesBundle;
- }
- }
- return null;
- }
-
- /**
- * Adds an empty <code>MessagesBundle</code> to this group for the
- * given locale.
- * @param locale locale for the new bundle added
- */
- public void addMessagesBundle(Locale locale) {
- addMessagesBundle(groupStrategy.createMessagesBundle(locale));
- }
-
- /**
- * Gets all locales making up this messages bundle group.
- */
- public Locale[] getLocales() {
- return localeBundles.keySet().toArray(EMPTY_LOCALES);
- }
-
- /**
- * Gets all messages associated with the given message key.
- * @param key a message key
- * @return messages
- */
- public IMessage[] getMessages(String key) {
- List<IMessage> messages = new ArrayList<IMessage>();
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- IMessage message = messagesBundle.getMessage(key);
- if (message != null) {
- messages.add(message);
- }
- }
- return messages.toArray(EMPTY_MESSAGES);
- }
-
- /**
- * Gets the message matching given key and locale.
- * @param locale locale for which to retrieve the message
- * @param key key matching entry to retrieve the message
- * @return a message
- */
- public IMessage getMessage(String key, Locale locale) {
- IMessagesBundle messagesBundle = getMessagesBundle(locale);
- if (messagesBundle != null) {
- return messagesBundle.getMessage(key);
- }
- return null;
- }
-
-
- /**
- * Adds a messages bundle to this group.
- * @param messagesBundle bundle to add
- * @throws MessageException if a messages bundle for the same locale
- * already exists.
- */
- public void addMessagesBundle(IMessagesBundle messagesBundle) {
- addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
- }
-
- public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) {
- MessagesBundle mb = (MessagesBundle) messagesBundle;
- if (localeBundles.get(mb.getLocale()) != null) {
- throw new MessageException(
- "A bundle with the same locale already exists."); //$NON-NLS-1$
- }
-
- int oldBundleCount = localeBundles.size();
- localeBundles.put(mb.getLocale(), mb);
-
- firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT,
- oldBundleCount, localeBundles.size());
- fireMessagesBundleAdded(mb);
-
- String[] bundleKeys = mb.getKeys();
- for (int i = 0; i < bundleKeys.length; i++) {
- String key = bundleKeys[i];
- if (!keys.contains(key)) {
- int oldKeyCount = keys.size();
- keys.add(key);
- firePropertyChange(
- PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
- fireKeyAdded(key);
- }
- }
- mb.addMessagesBundleListener(messagesBundleListener);
-
- }
-
- public void removeMessagesBundle(IMessagesBundle messagesBundle) {
- Locale locale = messagesBundle.getLocale();
-
- if (localeBundles.containsKey(locale)) {
- localeBundles.remove(locale);
- }
-
- // which keys should I not remove?
- Set<String> keysNotToRemove = new TreeSet<String>();
-
- for (String key : messagesBundle.getKeys()) {
- for (IMessagesBundle bundle : localeBundles.values()) {
- if (bundle.getMessage(key) != null) {
- keysNotToRemove.add(key);
- }
- }
- }
-
- // remove keys
- for (String keyToRemove : messagesBundle.getKeys()) {
- if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
- keys.remove(keyToRemove);
- }
- }
- }
-
- /**
- * Gets this messages bundle group name.
- * @return bundle group name
- */
- public String getName() {
- return name;
- }
-
- /**
- * Adds an empty message to every messages bundle of this group with the
- * given.
- * @param key message key
- */
- public void addMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- ((MessagesBundle)msgBundle).addMessage(key);
- }
- }
-
- /**
- * Renames a key in all messages bundles forming this group.
- * @param sourceKey the message key to rename
- * @param targetKey the new message name
- */
- public void renameMessageKeys(String sourceKey, String targetKey) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.renameMessageKey(
- sourceKey, targetKey);
- }
- }
-
- /**
- * Removes messages matching the given key from all messages bundle.
- * @param key key of messages to remove
- */
- public void removeMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.removeMessage(key);
- }
- }
-
- /**
- * Sets whether messages matching the <code>key</code> are active or not.
- * @param key key of messages
- */
- public void setMessagesActive(String key, boolean active) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- IMessage entry = msgBundle.getMessage(key);
- if (entry != null) {
- entry.setActive(active);
- }
- }
- }
-
- /**
- * Duplicates each messages matching the <code>sourceKey</code> to
- * the <code>newKey</code>.
- * @param sourceKey original key
- * @param targetKey new key
- * @throws MessageException if a target key already exists
- */
- public void duplicateMessages(String sourceKey, String targetKey) {
- if (sourceKey.equals(targetKey)) {
- return;
- }
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.duplicateMessage(
- sourceKey, targetKey);
- }
- }
-
- /**
- * Returns a collection of all bundles in this group.
- * @return the bundles in this group
- */
- public Collection<IMessagesBundle> getMessagesBundles() {
- return localeBundles.values();
- }
-
- /**
- * Gets all keys from all messages bundles.
- * @return all keys from all messages bundles
- */
- public String[] getMessageKeys() {
- return keys.toArray(BabelUtils.EMPTY_STRINGS);
- }
-
- /**
- * Whether the given key is found in this messages bundle group.
- * @param key the key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
- public boolean isMessageKey(String key) {
- return keys.contains(key);
- }
-
- /**
- * Gets the number of messages bundles in this group.
- * @return the number of messages bundles in this group
- */
- public int getMessagesBundleCount() {
- return localeBundles.size();
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof MessagesBundleGroup)) {
- return false;
- }
- MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
- return equals(localeBundles, messagesBundleGroup.localeBundles);
- }
-
- public final synchronized void addMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- addPropertyChangeListener(listener);
- }
- public final synchronized void removeMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- removePropertyChangeListener(listener);
- }
- public final synchronized IMessagesBundleGroupListener[]
- getMessagesBundleGroupListeners() {
- //TODO find more efficient way to avoid class cast.
- return Arrays.asList(
- getPropertyChangeListeners()).toArray(
- EMPTY_GROUP_LISTENERS);
- }
-
-
- private void fireKeyAdded(String key) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyAdded(key);
- }
- }
- private void fireKeyRemoved(String key) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyRemoved(key);
- }
- }
- private void fireMessagesBundleAdded(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleAdded(messagesBundle);
- }
- }
- private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleRemoved(messagesBundle);
- }
- }
-
- /**
- * Returns true if the supplied key is already existing in this group.
- *
- * @param key The key that shall be tested.
- *
- * @return true <=> The key is already existing.
- */
- public boolean containsKey(String key) {
- for (Locale locale : localeBundles.keySet()) {
- IMessagesBundle messagesBundle = localeBundles.get(locale);
- for (String k : messagesBundle.getKeys()) {
- if (k.equals(key)) {
- return true;
- } else {
- continue;
- }
- }
- }
- return false;
- }
-
- /**
- * Is the given key found in this bundle group.
- * @param key the key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
- public boolean isKey(String key) {
- return keys.contains(key);
- }
-
-
-
- public String getResourceBundleId() {
- return resourceBundleId;
- }
-
- public String getProjectName() {
- return this.projectName;
- }
-
- /**
- * Class listening for changes in underlying messages bundle and
- * relays them to the listeners for MessagesBundleGroup.
- */
- private class MessagesBundleListener implements IMessagesBundleListener {
- public void messageAdded(MessagesBundle messagesBundle,
- Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageAdded(messagesBundle, message);
- if (getMessages(message.getKey()).length == 1) {
- keys.add(message.getKey());
- firePropertyChange(
- PROPERTY_KEY_COUNT, oldCount, keys.size());
- fireKeyAdded(message.getKey());
- }
- }
- }
- public void messageRemoved(MessagesBundle messagesBundle,
- Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageRemoved(messagesBundle, message);
- int keyMessagesCount = getMessages(message.getKey()).length;
- if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
- keys.remove(message.getKey());
- firePropertyChange(
- PROPERTY_KEY_COUNT, oldCount, keys.size());
- fireKeyRemoved(message.getKey());
- }
- }
- }
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageChanged(messagesBundle, changeEvent);
- }
- }
- // MessagesBundle property changes:
- public void propertyChange(PropertyChangeEvent evt) {
- MessagesBundle bundle = (MessagesBundle) evt.getSource();
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleChanged(bundle, evt);
- }
- }
- }
-
- public boolean hasPropertiesFileGroupStrategy() {
- return groupStrategy instanceof PropertiesFileGroupStrategy;
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroupAdapter.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroupAdapter.java
deleted file mode 100644
index 026e010d..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroupAdapter.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.eclipse.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-
-/**
- * An adapter class for a {@link IMessagesBundleGroupListener}. Methods
- * implementation do nothing.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundleGroupAdapter
- implements IMessagesBundleGroupListener {
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleGroupListener#
- * keyAdded(java.lang.String)
- */
- public void keyAdded(String key) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleGroupListener#
- * keyRemoved(java.lang.String)
- */
- public void keyRemoved(String key) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleGroupListener#
- * messagesBundleAdded(org.eclipse.babel.core.message.MessagesBundle)
- */
- public void messagesBundleAdded(MessagesBundle messagesBundle) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleGroupListener#
- * messagesBundleChanged(org.eclipse.babel.core.message.MessagesBundle,
- * java.beans.PropertyChangeEvent)
- */
- public void messagesBundleChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleGroupListener
- * #messagesBundleRemoved(org.eclipse.babel.core.message.MessagesBundle)
- */
- public void messagesBundleRemoved(MessagesBundle messagesBundle) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleListener#messageAdded(
- * org.eclipse.babel.core.message.MessagesBundle,
- * org.eclipse.babel.core.message.Message)
- */
- public void messageAdded(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleListener#
- * messageChanged(org.eclipse.babel.core.message.MessagesBundle,
- * java.beans.PropertyChangeEvent)
- */
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.core.message.IMessagesBundleListener#
- * messageRemoved(org.eclipse.babel.core.message.MessagesBundle,
- * org.eclipse.babel.core.message.Message)
- */
- public void messageRemoved(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see java.beans.PropertyChangeListener#propertyChange(
- * java.beans.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent evt) {
- // do nothing
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/DuplicateValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/DuplicateValueCheck.java
deleted file mode 100644
index ddcf2ae0..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/DuplicateValueCheck.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.checks;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Checks if key as a duplicate value.
- * @author Pascal Essiembre ([email protected])
- */
-public class DuplicateValueCheck implements IMessageCheck {
-
- private String[] duplicateKeys;
-
- /**
- * Constructor.
- */
- public DuplicateValueCheck() {
- super();
- }
-
- /**
- * Resets the collected keys to null.
- */
- public void reset() {
- duplicateKeys = null;
- }
-
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
- Collection<String> keys = new ArrayList<String>();
- if (message != null) {
- IMessagesBundle messagesBundle =
- messagesBundleGroup.getMessagesBundle(message.getLocale());
- for (IMessage duplicateEntry : messagesBundle.getMessages()) {
- if (!message.getKey().equals(duplicateEntry.getKey())
- && BabelUtils.equals(message.getValue(),
- duplicateEntry.getValue())) {
- keys.add(duplicateEntry.getKey());
- }
- }
- if (!keys.isEmpty()) {
- keys.add(message.getKey());
- }
- }
-
- duplicateKeys = keys.toArray(new String[]{});
- return !keys.isEmpty();
- }
-
- public String[] getDuplicateKeys() {
- return duplicateKeys;
- }
-
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java
index b743a259..39aa54bc 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java
@@ -10,10 +10,10 @@
******************************************************************************/
package org.eclipse.babel.core.message.checks;
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.Message;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
/**
* All purpose {@link Message} testing. Use this interface to establish
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/MissingValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/MissingValueCheck.java
deleted file mode 100644
index f40517c3..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/MissingValueCheck.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.checks;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Visitor for finding if a key has at least one corresponding bundle entry
- * with a missing value.
- * @author Pascal Essiembre ([email protected])
- */
-public class MissingValueCheck implements IMessageCheck {
-
- /** The singleton */
- public static MissingValueCheck MISSING_KEY = new MissingValueCheck();
-
- /**
- * Constructor.
- */
- private MissingValueCheck() {
- super();
- }
-
- /**
- * @see org.eclipse.babel.core.message.checks.IMessageCheck#checkKey(
- * org.eclipse.babel.core.message.MessagesBundleGroup,
- * org.eclipse.babel.core.message.Message)
- */
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
- if (message == null || message.getValue() == null
- || message.getValue().length() == 0) {
- return true;
- }
- return false;
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/SimilarValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/SimilarValueCheck.java
deleted file mode 100644
index 88d1dd57..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/SimilarValueCheck.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.checks;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer;
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-
-/**
- * Checks if key as a duplicate value.
- * @author Pascal Essiembre ([email protected])
- */
-public class SimilarValueCheck implements IMessageCheck {
-
- private String[] similarKeys;
- private IProximityAnalyzer analyzer;
-
- /**
- * Constructor.
- */
- public SimilarValueCheck(IProximityAnalyzer analyzer) {
- super();
- this.analyzer = analyzer;
- }
-
- /**
- * @see org.eclipse.babel.core.message.checks.IMessageCheck#checkKey(
- * org.eclipse.babel.core.message.MessagesBundleGroup,
- * org.eclipse.babel.core.message.Message)
- */
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
- Collection<String> keys = new ArrayList<String>();
- if (message != null) {
- //TODO have case as preference
- String value1 = message.getValue().toLowerCase();
- IMessagesBundle messagesBundle =
- messagesBundleGroup.getMessagesBundle(message.getLocale());
- for (IMessage similarEntry : messagesBundle.getMessages()) {
- if (!message.getKey().equals(similarEntry.getKey())) {
- String value2 = similarEntry.getValue().toLowerCase();
- //TODO have preference to report identical as similar
- if (!BabelUtils.equals(value1, value2)
- && analyzer.analyse(value1, value2) >= 0.75) {
- //TODO use preferences
-// >= RBEPreferences.getReportSimilarValuesPrecision()) {
- keys.add(similarEntry.getKey());
- }
- }
- }
- if (!keys.isEmpty()) {
- keys.add(message.getKey());
- }
- }
- similarKeys = keys.toArray(new String[]{});
- return !keys.isEmpty();
- }
-
- /**
- * Gets similar keys.
- * @return similar keys
- */
- public String[] getSimilarMessageKeys() {
- return similarKeys;
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java
new file mode 100644
index 00000000..e6860aa3
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.checks.internal;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.checks.IMessageCheck;
+import org.eclipse.babel.core.util.BabelUtils;
+
+/**
+ * Checks if key as a duplicate value.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class DuplicateValueCheck implements IMessageCheck {
+
+ private String[] duplicateKeys;
+
+ /**
+ * Constructor.
+ */
+ public DuplicateValueCheck() {
+ super();
+ }
+
+ /**
+ * Resets the collected keys to null.
+ */
+ public void reset() {
+ duplicateKeys = null;
+ }
+
+ public boolean checkKey(
+ IMessagesBundleGroup messagesBundleGroup, IMessage message) {
+ Collection<String> keys = new ArrayList<String>();
+ if (message != null) {
+ IMessagesBundle messagesBundle =
+ messagesBundleGroup.getMessagesBundle(message.getLocale());
+ for (IMessage duplicateEntry : messagesBundle.getMessages()) {
+ if (!message.getKey().equals(duplicateEntry.getKey())
+ && BabelUtils.equals(message.getValue(),
+ duplicateEntry.getValue())) {
+ keys.add(duplicateEntry.getKey());
+ }
+ }
+ if (!keys.isEmpty()) {
+ keys.add(message.getKey());
+ }
+ }
+
+ duplicateKeys = keys.toArray(new String[]{});
+ return !keys.isEmpty();
+ }
+
+ public String[] getDuplicateKeys() {
+ return duplicateKeys;
+ }
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java
new file mode 100644
index 00000000..ef297bdc
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.checks.internal;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.checks.IMessageCheck;
+
+/**
+ * Visitor for finding if a key has at least one corresponding bundle entry
+ * with a missing value.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class MissingValueCheck implements IMessageCheck {
+
+ /** The singleton */
+ public static MissingValueCheck MISSING_KEY = new MissingValueCheck();
+
+ /**
+ * Constructor.
+ */
+ private MissingValueCheck() {
+ super();
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey(
+ * org.eclipse.babel.core.message.internal.MessagesBundleGroup,
+ * org.eclipse.babel.core.message.internal.Message)
+ */
+ public boolean checkKey(
+ IMessagesBundleGroup messagesBundleGroup, IMessage message) {
+ if (message == null || message.getValue() == null
+ || message.getValue().length() == 0) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java
new file mode 100644
index 00000000..437b6b95
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.checks.internal;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.checks.IMessageCheck;
+import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer;
+import org.eclipse.babel.core.util.BabelUtils;
+
+
+/**
+ * Checks if key as a duplicate value.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class SimilarValueCheck implements IMessageCheck {
+
+ private String[] similarKeys;
+ private IProximityAnalyzer analyzer;
+
+ /**
+ * Constructor.
+ */
+ public SimilarValueCheck(IProximityAnalyzer analyzer) {
+ super();
+ this.analyzer = analyzer;
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey(
+ * org.eclipse.babel.core.message.internal.MessagesBundleGroup,
+ * org.eclipse.babel.core.message.internal.Message)
+ */
+ public boolean checkKey(
+ IMessagesBundleGroup messagesBundleGroup, IMessage message) {
+ Collection<String> keys = new ArrayList<String>();
+ if (message != null) {
+ //TODO have case as preference
+ String value1 = message.getValue().toLowerCase();
+ IMessagesBundle messagesBundle =
+ messagesBundleGroup.getMessagesBundle(message.getLocale());
+ for (IMessage similarEntry : messagesBundle.getMessages()) {
+ if (!message.getKey().equals(similarEntry.getKey())) {
+ String value2 = similarEntry.getValue().toLowerCase();
+ //TODO have preference to report identical as similar
+ if (!BabelUtils.equals(value1, value2)
+ && analyzer.analyse(value1, value2) >= 0.75) {
+ //TODO use preferences
+// >= RBEPreferences.getReportSimilarValuesPrecision()) {
+ keys.add(similarEntry.getKey());
+ }
+ }
+ }
+ if (!keys.isEmpty()) {
+ keys.add(message.getKey());
+ }
+ }
+ similarKeys = keys.toArray(new String[]{});
+ return !keys.isEmpty();
+ }
+
+ /**
+ * Gets similar keys.
+ * @return similar keys
+ */
+ public String[] getSimilarMessageKeys() {
+ return similarKeys;
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java
new file mode 100644
index 00000000..ecfc44df
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java
@@ -0,0 +1,89 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+
+/**
+ * Same functionality than an {@link IResourceChangeListener} but listens to
+ * a single file at a time. Subscribed and unsubscribed directly on
+ * the MessageEditorPlugin.
+ *
+ * @author Hugues Malphettes
+ */
+public abstract class AbstractIFileChangeListener {
+
+ /**
+ * Takes a IResourceChangeListener and wraps it into an AbstractIFileChangeListener.
+ * <p>
+ * Delegates the listenedFileChanged calls to the underlying
+ * IResourceChangeListener#resourceChanged.
+ * </p>
+ * @param rcl
+ * @param listenedFile
+ * @return
+ */
+ public static AbstractIFileChangeListener wrapResourceChangeListener(
+ final IResourceChangeListener rcl, IFile listenedFile) {
+ return new AbstractIFileChangeListener(listenedFile) {
+ public void listenedFileChanged(IResourceChangeEvent event) {
+ rcl.resourceChanged(event);
+ }
+ };
+ }
+
+
+ //we use a string to be certain that no memory will leak from this class:
+ //there is nothing to do a priori to dispose of this class.
+ private final String listenedFileFullPath;
+
+ /**
+ * @param listenedFile The file this object listens to. It is final.
+ */
+ public AbstractIFileChangeListener(IFile listenedFile) {
+ listenedFileFullPath = listenedFile.getFullPath().toString();
+ }
+
+ /**
+ * @return The file listened to. It is final.
+ */
+ public final String getListenedFileFullPath() {
+ return listenedFileFullPath;
+ }
+
+ /**
+ * @param event The change event. It is guaranteed that this
+ * event's getResource() method returns the file that this object listens to.
+ */
+ public abstract void listenedFileChanged(IResourceChangeEvent event);
+
+ /**
+ * Interface implemented by the MessageEditorPlugin.
+ * <p>
+ * Describes the registry of file change listeners.
+ *
+ * </p>
+ */
+ public interface IFileChangeListenerRegistry {
+ /**
+ * @param rcl Adds a subscriber to a resource change event.
+ */
+ public void subscribe(AbstractIFileChangeListener fileChangeListener);
+
+ /**
+ * @param rcl Removes a subscriber to a resource change event.
+ */
+ public void unsubscribe(AbstractIFileChangeListener fileChangeListener);
+ }
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java
new file mode 100644
index 00000000..474786d4
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java
@@ -0,0 +1,228 @@
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - TapJI integration -> DirtyHack
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.io.Serializable;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.util.BabelUtils;
+
+
+/**
+ * A convenience base class for observable message-related classes.
+ * This class follows the conventions and recommendations as described
+ * in the <a href="http://java.sun.com/products/javabeans/docs/spec.html">SUN
+ * JavaBean specifications</a>.
+ *
+ * @author Pascal Essiembre ([email protected])
+ * @author Karsten Lentzsch ([email protected])
+ */
+public abstract class AbstractMessageModel implements Serializable {
+ /** Handles <code>PropertyChangeListeners</code>. */
+ private transient PropertyChangeSupport changeSupport;
+
+ /**
+ * Adds a PropertyChangeListener to the listener list. The listener is
+ * registered for all properties of this class.<p>
+ * Adding a <code>null</code> listener has no effect.
+ *
+ * @param listener the PropertyChangeListener to be added
+ */
+ /*default*/ final synchronized void addPropertyChangeListener(
+ final PropertyChangeListener listener) {
+ if (listener == null) {
+ return;
+ }
+ if (changeSupport == null) {
+ changeSupport = new PropertyChangeSupport(this);
+ }
+ changeSupport.addPropertyChangeListener(listener);
+ }
+
+ /**
+ * Removes a PropertyChangeListener from the listener list. This method
+ * should be used to remove PropertyChangeListeners that were registered
+ * for all bound properties of this class.<p>
+ * Removing a <code>null</code> listener has no effect.
+ *
+ * @param listener the PropertyChangeListener to be removed
+ */
+ /*default*/ final synchronized void removePropertyChangeListener(
+ final PropertyChangeListener listener) {
+ if (listener == null || changeSupport == null) {
+ return;
+ }
+ changeSupport.removePropertyChangeListener(listener);
+ }
+
+ /**
+ * Returns an array of all the property change listeners registered on
+ * this component.
+ *
+ * @return all of this component's <code>PropertyChangeListener</code>s
+ * or an empty array if no property change
+ * listeners are currently registered
+ */
+ /*default*/ final synchronized
+ PropertyChangeListener[] getPropertyChangeListeners() {
+ if (changeSupport == null) {
+ return new PropertyChangeListener[0];
+ }
+ return changeSupport.getPropertyChangeListeners();
+ }
+
+ /**
+ * Support for reporting bound property changes for Object properties.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param propertyName the property whose value has changed
+ * @param oldValue the property's previous value
+ * @param newValue the property's new value
+ */
+ protected final void firePropertyChange(
+ final String propertyName,
+ final Object oldValue,
+ final Object newValue) {
+ if (changeSupport == null || !DirtyHack.isFireEnabled()) {
+ return;
+ }
+ changeSupport.firePropertyChange(propertyName, oldValue, newValue);
+ }
+
+ /**
+ * Support for reporting bound property changes for boolean properties.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param propertyName the property whose value has changed
+ * @param oldValue the property's previous value
+ * @param newValue the property's new value
+ */
+ protected final void firePropertyChange(
+ final String propertyName,
+ final boolean oldValue,
+ final boolean newValue) {
+ if (changeSupport == null || !DirtyHack.isFireEnabled()) {
+ return;
+ }
+ changeSupport.firePropertyChange(propertyName, oldValue, newValue);
+ }
+
+ /**
+ * Support for reporting bound property changes for events.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param event the event that triggered the change
+ */
+ protected final void firePropertyChange(
+ final PropertyChangeEvent event) {
+ if (changeSupport == null || !DirtyHack.isFireEnabled()) {
+ return;
+ }
+ changeSupport.firePropertyChange(event);
+ }
+
+ /**
+ * Support for reporting bound property changes for integer properties.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param propertyName the property whose value has changed
+ * @param oldValue the property's previous value
+ * @param newValue the property's new value
+ */
+ protected final void firePropertyChange(
+ final String propertyName,
+ final double oldValue,
+ final double newValue) {
+ firePropertyChange(
+ propertyName, new Double(oldValue), new Double(newValue));
+ }
+
+ /**
+ * Support for reporting bound property changes for integer properties.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param propertyName the property whose value has changed
+ * @param oldValue the property's previous value
+ * @param newValue the property's new value
+ */
+ protected final void firePropertyChange(
+ final String propertyName,
+ final float oldValue,
+ final float newValue) {
+ firePropertyChange(
+ propertyName, new Float(oldValue), new Float(newValue));
+ }
+
+ /**
+ * Support for reporting bound property changes for integer properties.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param propertyName the property whose value has changed
+ * @param oldValue the property's previous value
+ * @param newValue the property's new value
+ */
+ protected final void firePropertyChange(
+ final String propertyName,
+ final int oldValue,
+ final int newValue) {
+ if (changeSupport == null || !DirtyHack.isFireEnabled()) {
+ return;
+ }
+ changeSupport.firePropertyChange(propertyName, oldValue, newValue);
+ }
+
+ /**
+ * Support for reporting bound property changes for integer properties.
+ * This method can be called when a bound property has changed and it will
+ * send the appropriate PropertyChangeEvent to any registered
+ * PropertyChangeListeners.
+ *
+ * @param propertyName the property whose value has changed
+ * @param oldValue the property's previous value
+ * @param newValue the property's new value
+ */
+ protected final void firePropertyChange(
+ final String propertyName,
+ final long oldValue,
+ final long newValue) {
+ firePropertyChange(
+ propertyName, new Long(oldValue), new Long(newValue));
+ }
+
+ /**
+ * Checks and answers if the two objects are both <code>null</code>
+ * or equal.
+ *
+ * @param o1 the first object to compare
+ * @param o2 the second object to compare
+ * @return boolean true if and only if both objects are <code>null</code>
+ * or equal
+ */
+ protected final boolean equals(final Object o1, final Object o2) {
+ return BabelUtils.equals(o1, o2);
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java
new file mode 100644
index 00000000..1bf9948f
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+
+/**
+ * A listener for changes on a {@link MessagesBundleGroup}.
+ * @author Pascal Essiembre ([email protected])
+ * @see MessagesBundleGroup
+ */
+public interface IMessagesBundleGroupListener extends IMessagesBundleListener {
+
+ /**
+ * A message key has been added.
+ * @param key the added key
+ */
+ void keyAdded(String key);
+ /**
+ * A message key has been removed.
+ * @param key the removed key
+ */
+ void keyRemoved(String key);
+ /**
+ * A messages bundle has been added.
+ * @param messagesBundle the messages bundle
+ */
+ void messagesBundleAdded(MessagesBundle messagesBundle);
+ /**
+ * A messages bundle has been removed.
+ * @param messagesBundle the messages bundle
+ */
+ void messagesBundleRemoved(MessagesBundle messagesBundle);
+ /**
+ * A messages bundle was modified.
+ * @param messagesBundle the messages bundle
+ */
+ void messagesBundleChanged(
+ MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java
new file mode 100644
index 00000000..76a3fb36
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+/**
+ * A listener for changes on a {@link MessagesBundle}.
+ * @author Pascal Essiembre ([email protected])
+ * @see MessagesBundle
+ */
+public interface IMessagesBundleListener extends PropertyChangeListener {
+ /**
+ * A message was added.
+ * @param messagesBundle the messages bundle on which the message was added.
+ * @param message the message
+ */
+ void messageAdded(MessagesBundle messagesBundle, Message message);
+ /**
+ * A message was removed.
+ * @param messagesBundle the messages bundle on which the message was
+ * removed.
+ * @param message the message
+ */
+ void messageRemoved(MessagesBundle messagesBundle, Message message);
+ /**
+ * A message was changed.
+ * @param messagesBundle the messages bundle on which the message was
+ * changed.
+ * @param message the message
+ */
+ void messageChanged(
+ MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java
new file mode 100644
index 00000000..cba200a4
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java
@@ -0,0 +1,198 @@
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - TapJI integration
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeListener;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.IMessage;
+
+/**
+ * A single entry in a <code>MessagesBundle</code>.
+ *
+ * @author Pascal Essiembre ([email protected])
+ * @see MessagesBundle
+ * @see MessagesBundleGroup
+ */
+public final class Message extends AbstractMessageModel implements IMessage {
+
+ /** For serialisation. */
+ private static final long serialVersionUID = 1160670351341655427L;
+
+ public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
+ public static final String PROPERTY_ACTIVE = "active"; //$NON-NLS-1$
+ public static final String PROPERTY_TEXT = "text"; //$NON-NLS-1$
+
+ /** Entry unique identifier. */
+ private final String key;
+ /** Entry locale. */
+ private final Locale locale;
+ /** Entry comment. */
+ private String comment;
+ /** Whether this entry is commented out or not. */
+ private boolean active = true;
+ /** Entry text. */
+ private String text;
+
+ /**
+ * Constructor. Key and locale arguments are <code>null</code> safe.
+ * @param key unique identifier within a messages bundle
+ * @param locale the message locale
+ */
+ public Message(final String key, final Locale locale) {
+ super();
+ this.key = (key == null ? "" : key); //$NON-NLS-1$
+ this.locale = locale;
+ }
+
+
+
+ /**
+ * Sets the message comment.
+ * @param comment The comment to set.
+ */
+ public void setComment(String comment) {
+ Object oldValue = this.comment;
+ this.comment = comment;
+ firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
+ }
+
+ public void setComment(String comment, boolean silent) {
+ Object oldValue = this.comment;
+ this.comment = comment;
+ if (!silent) {
+ firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
+ }
+ }
+
+ /**
+ * Sets whether the message is active or not. An inactive message is
+ * one that we continue to keep track of, but will not be picked
+ * up by internationalisation mechanism (e.g. <code>ResourceBundle</code>).
+ * Typically, those are commented (i.e. //) key/text pairs in a
+ * *.properties file.
+ * @param active The active to set.
+ */
+ public void setActive(boolean active) {
+ boolean oldValue = this.active;
+ this.active = active;
+ firePropertyChange(PROPERTY_ACTIVE, oldValue, active);
+ }
+
+ /**
+ * Sets the actual message text.
+ * @param text The text to set.
+ */
+ public void setText(String text) {
+ Object oldValue = this.text;
+ this.text = text;
+ firePropertyChange(PROPERTY_TEXT, oldValue, text);
+ }
+
+ public void setText(String text, boolean silent) {
+ Object oldValue = this.text;
+ this.text = text;
+ if (!silent) {
+ firePropertyChange(PROPERTY_TEXT, oldValue, text);
+ }
+ }
+
+ /**
+ * Gets the comment associated with this message (<code>null</code> if
+ * no comments).
+ * @return Returns the comment.
+ */
+ public String getComment() {
+ return comment;
+ }
+ /**
+ * Gets the message key attribute.
+ * @return Returns the key.
+ */
+ public String getKey() {
+ return key;
+ }
+
+ /**
+ * Gets the message text.
+ * @return Returns the text.
+ */
+ public String getValue() {
+ return text;
+ }
+
+ /**
+ * Gets the message locale.
+ * @return Returns the locale
+ */
+ public Locale getLocale() {
+ return locale;
+ }
+
+ /**
+ * Gets whether this message is active or not.
+ * @return <code>true</code> if this message is active.
+ */
+ public boolean isActive() {
+ return active;
+ }
+
+ /**
+ * Copies properties of the given message to this message.
+ * The properties copied over are all properties but the
+ * message key and locale.
+ * @param message
+ */
+ protected void copyFrom(IMessage message) {
+ setComment(message.getComment());
+ setActive(message.isActive());
+ setText(message.getValue());
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Message)) {
+ return false;
+ }
+ Message entry = (Message) obj;
+ return equals(key, entry.key)
+ && equals(locale, entry.locale)
+ && active == entry.active
+ && equals(text, entry.text)
+ && equals(comment, entry.comment);
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "Message=[[key=" + key //$NON-NLS-1$
+ + "][text=" + text //$NON-NLS-1$
+ + "][comment=" + comment //$NON-NLS-1$
+ + "][active=" + active //$NON-NLS-1$
+ + "]]"; //$NON-NLS-1$
+ }
+
+ public final synchronized void addMessageListener(
+ final PropertyChangeListener listener) {
+ addPropertyChangeListener(listener);
+ }
+ public final synchronized void removeMessageListener(
+ final PropertyChangeListener listener) {
+ removePropertyChangeListener(listener);
+ }
+ public final synchronized PropertyChangeListener[] getMessageListeners() {
+ return getPropertyChangeListeners();
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java
new file mode 100644
index 00000000..5ef6454a
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+/**
+ * Exception thrown when a message-related operation raised a problem.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class MessageException extends RuntimeException {
+
+ /** For serialisation. */
+ private static final long serialVersionUID = 5702621096263524623L;
+
+ /**
+ * Creates a new <code>MessageException</code>.
+ */
+ public MessageException() {
+ super();
+ }
+
+ /**
+ * Creates a new <code>MessageException</code>.
+ * @param message exception message
+ */
+ public MessageException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new <code>MessageException</code>.
+ * @param message exception message
+ * @param cause root cause
+ */
+ public MessageException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new <code>MessageException</code>.
+ * @param cause root cause
+ */
+ public MessageException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java
new file mode 100644
index 00000000..9473955f
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java
@@ -0,0 +1,376 @@
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - TapJI integration, correct dispose
+ * Matthias Lettmayer - added removeMessageAddParentKey() (fixed issue 41)
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesResourceChangeListener;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+import org.eclipse.babel.core.util.BabelUtils;
+
+/**
+ * For a given scope, all messages for a national language.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class MessagesBundle extends AbstractMessageModel
+ implements IMessagesResourceChangeListener, IMessagesBundle {
+
+ private static final long serialVersionUID = -331515196227475652L;
+
+ public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
+ public static final String PROPERTY_MESSAGES_COUNT =
+ "messagesCount"; //$NON-NLS-1$
+
+ private static final IMessagesBundleListener[] EMPTY_MSG_BUNDLE_LISTENERS =
+ new IMessagesBundleListener[] {};
+ private final Collection<String> orderedKeys = new ArrayList<String>();
+ private final Map<String, IMessage> keyedMessages = new HashMap<String, IMessage>();
+
+ private final IMessagesResource resource;
+
+ private final PropertyChangeListener messageListener =
+ new PropertyChangeListener(){
+ public void propertyChange(PropertyChangeEvent event) {
+ fireMessageChanged(event);
+ }
+ };
+ private String comment;
+
+ /**
+ * Creates a new <code>MessagesBundle</code>.
+ * @param resource the messages bundle resource
+ */
+ public MessagesBundle(IMessagesResource resource) {
+ super();
+ this.resource = resource;
+ readFromResource();
+ // Handle resource changes
+ resource.addMessagesResourceChangeListener(
+ new IMessagesResourceChangeListener(){
+ public void resourceChanged(IMessagesResource changedResource) {
+ readFromResource();
+ }
+ });
+ // Handle bundle changes
+ addMessagesBundleListener(new MessagesBundleAdapter() {
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ writetoResource();
+ }
+ public void propertyChange(PropertyChangeEvent evt) {
+ writetoResource();
+ }
+ });
+ }
+
+ /**
+ * Called before this object will be discarded.
+ */
+ public void dispose() {
+ this.resource.dispose();
+ }
+
+ /**
+ * Gets the underlying messages resource implementation.
+ * @return
+ */
+ public IMessagesResource getResource() {
+ return resource;
+ }
+
+ public int getMessagesCount() {
+ return keyedMessages.size();
+ }
+
+ /**
+ * Gets the locale for the messages bundle (<code>null</code> assumes
+ * the default system locale).
+ * @return Returns the locale.
+ */
+ public Locale getLocale() {
+ return resource.getLocale();
+ }
+
+ /**
+ * Gets the overall comment, or description, for this messages bundle..
+ * @return Returns the comment.
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the comment for this messages bundle.
+ * @param comment The comment to set.
+ */
+ public void setComment(String comment) {
+ Object oldValue = this.comment;
+ this.comment = comment;
+ firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.resource
+ * .IMessagesResourceChangeListener#resourceChanged(
+ * org.eclipse.babel.core.message.internal.resource.IMessagesResource)
+ */
+ public void resourceChanged(IMessagesResource changedResource) {
+ this.resource.deserialize(this);
+ }
+
+ /**
+ * Adds a message to this messages bundle. If the message already exists
+ * its properties are updated and no new message is added.
+ * @param message the message to add
+ */
+ public void addMessage(IMessage message) {
+ Message m = (Message) message;
+ int oldCount = getMessagesCount();
+ if (!orderedKeys.contains(m.getKey())) {
+ orderedKeys.add(m.getKey());
+ }
+ if (!keyedMessages.containsKey(m.getKey())) {
+ keyedMessages.put(m.getKey(), m);
+ m.addMessageListener(messageListener);
+ firePropertyChange(
+ PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
+ fireMessageAdded(m);
+ } else {
+ // Entry already exists, update it.
+ Message matchingEntry = (Message) keyedMessages.get(m.getKey());
+ matchingEntry.copyFrom(m);
+ }
+ }
+ /**
+ * Removes a message from this messages bundle.
+ * @param messageKey the key of the message to remove
+ */
+ public void removeMessage(String messageKey) {
+ int oldCount = getMessagesCount();
+ orderedKeys.remove(messageKey);
+ Message message = (Message) keyedMessages.get(messageKey);
+ if (message != null) {
+ message.removePropertyChangeListener(messageListener);
+ keyedMessages.remove(messageKey);
+ firePropertyChange(
+ PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
+ fireMessageRemoved(message);
+ }
+ }
+
+ /**
+ * Removes a message from this messages bundle and adds it's parent key to bundle.
+ * E.g.: key = a.b.c gets deleted, a.b gets added with a default message
+ * @param messageKey the key of the message to remove
+ */
+ public void removeMessageAddParentKey(String messageKey) {
+ removeMessage(messageKey);
+
+ // add parent key
+ int index = messageKey.lastIndexOf(".");
+ messageKey = (index == -1 ? "" : messageKey.substring(0, index));
+
+ if (! messageKey.isEmpty())
+ addMessage(new Message(messageKey, getLocale()));
+ }
+
+ /**
+ * Removes messages from this messages bundle.
+ * @param messageKeys the keys of the messages to remove
+ */
+ public void removeMessages(String[] messageKeys) {
+ for (int i = 0; i < messageKeys.length; i++) {
+ removeMessage(messageKeys[i]);
+ }
+ }
+
+ /**
+ * Renames a message key.
+ * @param sourceKey the message key to rename
+ * @param targetKey the new key for the message
+ * @throws MessageException if the target key already exists
+ */
+ public void renameMessageKey(String sourceKey, String targetKey) {
+ if (getMessage(targetKey) != null) {
+ throw new MessageException(
+ "Cannot rename: target key already exists."); //$NON-NLS-1$
+ }
+ IMessage sourceEntry = getMessage(sourceKey);
+ if (sourceEntry != null) {
+ Message targetEntry = new Message(targetKey, getLocale());
+ targetEntry.copyFrom(sourceEntry);
+ removeMessage(sourceKey);
+ addMessage(targetEntry);
+ }
+ }
+ /**
+ * Duplicates a message.
+ * @param sourceKey the message key to duplicate
+ * @param targetKey the new message key
+ * @throws MessageException if the target key already exists
+ */
+ public void duplicateMessage(String sourceKey, String targetKey) {
+ if (getMessage(sourceKey) != null) {
+ throw new MessageException(
+ "Cannot duplicate: target key already exists."); //$NON-NLS-1$
+ }
+ IMessage sourceEntry = getMessage(sourceKey);
+ if (sourceEntry != null) {
+ Message targetEntry = new Message(targetKey, getLocale());
+ targetEntry.copyFrom(sourceEntry);
+ addMessage(targetEntry);
+ }
+ }
+
+ /**
+ * Gets a message.
+ * @param key a message key
+ * @return a message
+ */
+ public IMessage getMessage(String key) {
+ return keyedMessages.get(key);
+ }
+
+ /**
+ * Adds an empty message.
+ * @param key the new message key
+ */
+ public void addMessage(String key) {
+ addMessage(new Message(key, getLocale()));
+ }
+
+ /**
+ * Gets all message keys making up this messages bundle.
+ * @return message keys
+ */
+ public String[] getKeys() {
+ return orderedKeys.toArray(BabelUtils.EMPTY_STRINGS);
+ }
+
+ /**
+ * Obtains the set of <code>Message</code> objects in this bundle.
+ * @return a collection of <code>Message</code> objects in this bundle
+ */
+ public Collection<IMessage> getMessages() {
+ return keyedMessages.values();
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ String str = "MessagesBundle=[[locale=" + getLocale() //$NON-NLS-1$
+ + "][comment=" + comment //$NON-NLS-1$
+ + "][entries="; //$NON-NLS-1$
+ for (IMessage message : getMessages()) {
+ str += message.toString();
+ }
+ str += "]]"; //$NON-NLS-1$
+ return str;
+ }
+
+ /**
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+ final int PRIME = 31;
+ int result = 1;
+ result = PRIME * result + ((comment == null) ? 0 : comment.hashCode());
+ result = PRIME * result + ((messageListener == null)
+ ? 0 : messageListener.hashCode());
+ result = PRIME * result + ((keyedMessages == null)
+ ? 0 : keyedMessages.hashCode());
+ result = PRIME * result + ((orderedKeys == null)
+ ? 0 : orderedKeys.hashCode());
+ result = PRIME * result + ((resource == null)
+ ? 0 : resource.hashCode());
+ return result;
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MessagesBundle)) {
+ return false;
+ }
+ MessagesBundle messagesBundle = (MessagesBundle) obj;
+ return equals(comment, messagesBundle.comment)
+ && equals(keyedMessages, messagesBundle.keyedMessages);
+ }
+
+ public final synchronized void addMessagesBundleListener(
+ final IMessagesBundleListener listener) {
+ addPropertyChangeListener(listener);
+ }
+ public final synchronized void removeMessagesBundleListener(
+ final IMessagesBundleListener listener) {
+ removePropertyChangeListener(listener);
+ }
+ public final synchronized IMessagesBundleListener[]
+ getMessagesBundleListeners() {
+ //TODO find more efficient way to avoid class cast.
+ return Arrays.asList(
+ getPropertyChangeListeners()).toArray(
+ EMPTY_MSG_BUNDLE_LISTENERS);
+ }
+
+
+ private void readFromResource() {
+ this.resource.deserialize(this);
+ }
+ private void writetoResource() {
+ this.resource.serialize(this);
+ }
+
+ private void fireMessageAdded(Message message) {
+ IMessagesBundleListener[] listeners = getMessagesBundleListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleListener listener = listeners[i];
+ listener.messageAdded(this, message);
+ }
+ }
+ private void fireMessageRemoved(Message message) {
+ IMessagesBundleListener[] listeners = getMessagesBundleListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleListener listener = listeners[i];
+ listener.messageRemoved(this, message);
+ }
+ }
+ private void fireMessageChanged(PropertyChangeEvent event) {
+ IMessagesBundleListener[] listeners = getMessagesBundleListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleListener listener = listeners[i];
+ listener.messageChanged(this, event);
+ }
+ }
+
+ /**
+ * Returns the value to the given key, if the key exists.
+ * Otherwise may throw a NPE.
+ * @param key, the key of a message.
+ * @return The value to the given key.
+ */
+ public String getValue(String key) {
+ return getMessage(key).getValue();
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java
new file mode 100644
index 00000000..971e5e67
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+
+/**
+ * An adapter class for a {@link IMessagesBundleListener}. Methods
+ * implementation do nothing.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class MessagesBundleAdapter implements IMessagesBundleListener {
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#messageAdded(
+ * org.eclipse.babel.core.message.internal.MessagesBundle,
+ * org.eclipse.babel.core.message.internal.Message)
+ */
+ public void messageAdded(MessagesBundle messagesBundle, Message message) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener
+ * #messageChanged(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * java.beans.PropertyChangeEvent)
+ */
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener
+ * #messageRemoved(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * org.eclipse.babel.core.message.internal.Message)
+ */
+ public void messageRemoved(MessagesBundle messagesBundle, Message message) {
+ // do nothing
+ }
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(
+ * java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent evt) {
+ // do nothing
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
new file mode 100644
index 00000000..bf318882
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
@@ -0,0 +1,606 @@
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - TapJI integration
+ * Matthias Lettmayer - added removeMessagesAddParentKey() (fixed issue 41)
+ ******************************************************************************/
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+import org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy;
+import org.eclipse.babel.core.message.strategy.PropertiesFileGroupStrategy;
+import org.eclipse.babel.core.util.BabelUtils;
+
+/**
+ * Grouping of all messages bundle of the same kind.
+ *
+ * @author Pascal Essiembre ([email protected])
+ */
+public class MessagesBundleGroup extends AbstractMessageModel implements
+ IMessagesBundleGroup {
+
+ private String projectName;
+
+ private static final IMessagesBundleGroupListener[] EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {};
+ private static final Message[] EMPTY_MESSAGES = new Message[] {};
+
+ public static final String PROPERTY_MESSAGES_BUNDLE_COUNT = "messagesBundleCount"; //$NON-NLS-1$
+ public static final String PROPERTY_KEY_COUNT = "keyCount"; //$NON-NLS-1$
+
+ /** For serialization. */
+ private static final long serialVersionUID = -1977849534191384324L;
+ /** Bundles forming the group (key=Locale; value=MessagesBundle). */
+ private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>();
+ private final Set<String> keys = new TreeSet<String>();
+ private final IMessagesBundleListener messagesBundleListener = new MessagesBundleListener();
+
+ private final IMessagesBundleGroupStrategy groupStrategy;
+ private static final Locale[] EMPTY_LOCALES = new Locale[] {};
+ private final String name;
+ private final String resourceBundleId;
+
+ /**
+ * Creates a new messages bundle group.
+ *
+ * @param groupStrategy
+ * a IMessagesBundleGroupStrategy instance
+ */
+ public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) {
+ super();
+ this.groupStrategy = groupStrategy;
+ this.name = groupStrategy.createMessagesBundleGroupName();
+ this.resourceBundleId = groupStrategy.createMessagesBundleId();
+
+ this.projectName = groupStrategy.getProjectName();
+
+ MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
+ if (bundles != null) {
+ for (int i = 0; i < bundles.length; i++) {
+ addMessagesBundle(bundles[i]);
+ }
+ }
+
+ RBManager.getInstance(this.projectName)
+ .notifyMessagesBundleGroupCreated(this);
+ }
+
+ /**
+ * Called before this object will be discarded. Disposes the underlying
+ * MessageBundles
+ */
+ @Override
+ public void dispose() {
+ for (IMessagesBundle mb : getMessagesBundles()) {
+ try {
+ mb.dispose();
+ } catch (Throwable t) {
+ // FIXME: remove debug:
+ System.err.println("Error disposing message-bundle "
+ + ((MessagesBundle) mb).getResource()
+ .getResourceLocationLabel());
+ // disregard crashes: this is a best effort to dispose things.
+ }
+ }
+
+ RBManager.getInstance(this.projectName)
+ .notifyMessagesBundleGroupDeleted(this);
+ }
+
+ /**
+ * Gets the messages bundle matching given locale.
+ *
+ * @param locale
+ * locale of bundle to retreive
+ * @return a bundle
+ */
+ @Override
+ public IMessagesBundle getMessagesBundle(Locale locale) {
+ return localeBundles.get(locale);
+ }
+
+ /**
+ * Gets the messages bundle matching given source object. A source object
+ * being a context-specific concrete underlying implementation of a
+ * <code>MessagesBundle</code> as per defined in
+ * <code>IMessageResource</code>.
+ *
+ * @param source
+ * the source object to match
+ * @return a messages bundle
+ * @see IMessagesResource
+ */
+ public MessagesBundle getMessagesBundle(Object source) {
+ for (IMessagesBundle messagesBundle : getMessagesBundles()) {
+ if (equals(source, ((MessagesBundle) messagesBundle).getResource()
+ .getSource())) {
+ return (MessagesBundle) messagesBundle;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Adds an empty <code>MessagesBundle</code> to this group for the given
+ * locale.
+ *
+ * @param locale
+ * locale for the new bundle added
+ */
+ public void addMessagesBundle(Locale locale) {
+ addMessagesBundle(groupStrategy.createMessagesBundle(locale));
+ }
+
+ /**
+ * Gets all locales making up this messages bundle group.
+ */
+ public Locale[] getLocales() {
+ return localeBundles.keySet().toArray(EMPTY_LOCALES);
+ }
+
+ /**
+ * Gets all messages associated with the given message key.
+ *
+ * @param key
+ * a message key
+ * @return messages
+ */
+ @Override
+ public IMessage[] getMessages(String key) {
+ List<IMessage> messages = new ArrayList<IMessage>();
+ for (IMessagesBundle messagesBundle : getMessagesBundles()) {
+ IMessage message = messagesBundle.getMessage(key);
+ if (message != null) {
+ messages.add(message);
+ }
+ }
+ return messages.toArray(EMPTY_MESSAGES);
+ }
+
+ /**
+ * Gets the message matching given key and locale.
+ *
+ * @param locale
+ * locale for which to retrieve the message
+ * @param key
+ * key matching entry to retrieve the message
+ * @return a message
+ */
+ @Override
+ public IMessage getMessage(String key, Locale locale) {
+ IMessagesBundle messagesBundle = getMessagesBundle(locale);
+ if (messagesBundle != null) {
+ return messagesBundle.getMessage(key);
+ }
+ return null;
+ }
+
+ /**
+ * Adds a messages bundle to this group.
+ *
+ * @param messagesBundle
+ * bundle to add
+ * @throws MessageException
+ * if a messages bundle for the same locale already exists.
+ */
+ public void addMessagesBundle(IMessagesBundle messagesBundle) {
+ addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
+ }
+
+ /**
+ * Adds a messages bundle to this group.
+ *
+ * @param locale
+ * The locale of the bundle
+ * @param messagesBundle
+ * bundle to add
+ * @throws MessageException
+ * if a messages bundle for the same locale already exists.
+ */
+ @Override
+ public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) {
+ MessagesBundle mb = (MessagesBundle) messagesBundle;
+ if (localeBundles.get(mb.getLocale()) != null) {
+ throw new MessageException(
+ "A bundle with the same locale already exists."); //$NON-NLS-1$
+ }
+
+ int oldBundleCount = localeBundles.size();
+ localeBundles.put(mb.getLocale(), mb);
+
+ firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount,
+ localeBundles.size());
+ fireMessagesBundleAdded(mb);
+
+ String[] bundleKeys = mb.getKeys();
+ for (int i = 0; i < bundleKeys.length; i++) {
+ String key = bundleKeys[i];
+ if (!keys.contains(key)) {
+ int oldKeyCount = keys.size();
+ keys.add(key);
+ firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
+ fireKeyAdded(key);
+ }
+ }
+ mb.addMessagesBundleListener(messagesBundleListener);
+
+ }
+
+ /**
+ * Removes the {@link IMessagesBundle} from the group.
+ * @param messagesBundle The bundle to remove.
+ */
+ @Override
+ public void removeMessagesBundle(IMessagesBundle messagesBundle) {
+ Locale locale = messagesBundle.getLocale();
+
+ if (localeBundles.containsKey(locale)) {
+ localeBundles.remove(locale);
+ }
+
+ // which keys should I not remove?
+ Set<String> keysNotToRemove = new TreeSet<String>();
+
+ for (String key : messagesBundle.getKeys()) {
+ for (IMessagesBundle bundle : localeBundles.values()) {
+ if (bundle.getMessage(key) != null) {
+ keysNotToRemove.add(key);
+ }
+ }
+ }
+
+ // remove keys
+ for (String keyToRemove : messagesBundle.getKeys()) {
+ if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
+ keys.remove(keyToRemove);
+ }
+ }
+ }
+
+ /**
+ * Gets this messages bundle group name. That is the name, which is used
+ * for the tab of the MultiPageEditorPart
+ * @return bundle group name
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Adds an empty message to every messages bundle of this group with the
+ * given.
+ *
+ * @param key
+ * message key
+ */
+ @Override
+ public void addMessages(String key) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ ((MessagesBundle) msgBundle).addMessage(key);
+ }
+ }
+
+ /**
+ * Renames a key in all messages bundles forming this group.
+ *
+ * @param sourceKey
+ * the message key to rename
+ * @param targetKey
+ * the new message name
+ */
+ public void renameMessageKeys(String sourceKey, String targetKey) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.renameMessageKey(sourceKey, targetKey);
+ }
+ }
+
+ /**
+ * Removes messages matching the given key from all messages bundle.
+ *
+ * @param key
+ * key of messages to remove
+ */
+ @Override
+ public void removeMessages(String key) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.removeMessage(key);
+ }
+ }
+
+ /**
+ * Removes messages matching the given key from all messages bundle and add
+ * it's parent key to bundles.
+ *
+ * @param key
+ * key of messages to remove
+ */
+ @Override
+ public void removeMessagesAddParentKey(String key) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.removeMessageAddParentKey(key);
+ }
+ }
+
+ /**
+ * Sets whether messages matching the <code>key</code> are active or not.
+ *
+ * @param key
+ * key of messages
+ */
+ public void setMessagesActive(String key, boolean active) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ IMessage entry = msgBundle.getMessage(key);
+ if (entry != null) {
+ entry.setActive(active);
+ }
+ }
+ }
+
+ /**
+ * Duplicates each messages matching the <code>sourceKey</code> to the
+ * <code>newKey</code>.
+ *
+ * @param sourceKey
+ * original key
+ * @param targetKey
+ * new key
+ * @throws MessageException
+ * if a target key already exists
+ */
+ public void duplicateMessages(String sourceKey, String targetKey) {
+ if (sourceKey.equals(targetKey)) {
+ return;
+ }
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.duplicateMessage(sourceKey, targetKey);
+ }
+ }
+
+ /**
+ * Returns a collection of all bundles in this group.
+ *
+ * @return the bundles in this group
+ */
+ @Override
+ public Collection<IMessagesBundle> getMessagesBundles() {
+ return localeBundles.values();
+ }
+
+ /**
+ * Gets all keys from all messages bundles.
+ *
+ * @return all keys from all messages bundles
+ */
+ @Override
+ public String[] getMessageKeys() {
+ return keys.toArray(BabelUtils.EMPTY_STRINGS);
+ }
+
+ /**
+ * Whether the given key is found in this messages bundle group.
+ *
+ * @param key
+ * the key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ @Override
+ public boolean isMessageKey(String key) {
+ return keys.contains(key);
+ }
+
+ /**
+ * Gets the number of messages bundles in this group.
+ *
+ * @return the number of messages bundles in this group
+ */
+ @Override
+ public int getMessagesBundleCount() {
+ return localeBundles.size();
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MessagesBundleGroup)) {
+ return false;
+ }
+ MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
+ return equals(localeBundles, messagesBundleGroup.localeBundles);
+ }
+
+ public final synchronized void addMessagesBundleGroupListener(
+ final IMessagesBundleGroupListener listener) {
+ addPropertyChangeListener(listener);
+ }
+
+ public final synchronized void removeMessagesBundleGroupListener(
+ final IMessagesBundleGroupListener listener) {
+ removePropertyChangeListener(listener);
+ }
+
+ public final synchronized IMessagesBundleGroupListener[] getMessagesBundleGroupListeners() {
+ // TODO find more efficient way to avoid class cast.
+ return Arrays.asList(getPropertyChangeListeners()).toArray(
+ EMPTY_GROUP_LISTENERS);
+ }
+
+ private void fireKeyAdded(String key) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.keyAdded(key);
+ }
+ }
+
+ private void fireKeyRemoved(String key) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.keyRemoved(key);
+ }
+ }
+
+ private void fireMessagesBundleAdded(MessagesBundle messagesBundle) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleAdded(messagesBundle);
+ }
+ }
+
+ private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleRemoved(messagesBundle);
+ }
+ }
+
+ /**
+ * Returns true if the supplied key is already existing in this group.
+ *
+ * @param key
+ * The key that shall be tested.
+ *
+ * @return true <=> The key is already existing.
+ */
+ @Override
+ public boolean containsKey(String key) {
+ for (Locale locale : localeBundles.keySet()) {
+ IMessagesBundle messagesBundle = localeBundles.get(locale);
+ for (String k : messagesBundle.getKeys()) {
+ if (k.equals(key)) {
+ return true;
+ } else {
+ continue;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Is the given key found in this bundle group.
+ *
+ * @param key
+ * the key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ @Override
+ public boolean isKey(String key) {
+ return keys.contains(key);
+ }
+
+ /**
+ * Gets the unique id of the bundle group. That is usually: <directory>"."<default-filename>.
+ * The default filename is without the suffix (e.g. _en, or _en_GB).
+ * @return The unique identifier for the resource bundle group
+ */
+ @Override
+ public String getResourceBundleId() {
+ return resourceBundleId;
+ }
+
+ /**
+ * Gets the name of the project, the resource bundle group is in.
+ * @return The project name
+ */
+ @Override
+ public String getProjectName() {
+ return this.projectName;
+ }
+
+ /**
+ * Class listening for changes in underlying messages bundle and relays them
+ * to the listeners for MessagesBundleGroup.
+ */
+ private class MessagesBundleListener implements IMessagesBundleListener {
+ @Override
+ public void messageAdded(MessagesBundle messagesBundle, Message message) {
+ int oldCount = keys.size();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageAdded(messagesBundle, message);
+ if (getMessages(message.getKey()).length == 1) {
+ keys.add(message.getKey());
+ firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
+ keys.size());
+ fireKeyAdded(message.getKey());
+ }
+ }
+ }
+
+ @Override
+ public void messageRemoved(MessagesBundle messagesBundle,
+ Message message) {
+ int oldCount = keys.size();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageRemoved(messagesBundle, message);
+ int keyMessagesCount = getMessages(message.getKey()).length;
+ if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
+ keys.remove(message.getKey());
+ firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
+ keys.size());
+ fireKeyRemoved(message.getKey());
+ }
+ }
+ }
+
+ @Override
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageChanged(messagesBundle, changeEvent);
+ }
+ }
+
+ // MessagesBundle property changes:
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ MessagesBundle bundle = (MessagesBundle) evt.getSource();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleChanged(bundle, evt);
+ }
+ }
+ }
+
+ /**
+ * @return <code>true</code> if the bundle group has {@link PropertiesFileGroupStrategy} as strategy,
+ * else <code>false</code>. This is the case, when only TapiJI edits the resource bundles and no
+ * have been opened.
+ */
+ @Override
+ public boolean hasPropertiesFileGroupStrategy() {
+ return groupStrategy instanceof PropertiesFileGroupStrategy;
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java
new file mode 100644
index 00000000..fa654b19
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java
@@ -0,0 +1,81 @@
+package org.eclipse.babel.core.message.internal;
+
+import java.beans.PropertyChangeEvent;
+
+/**
+ * An adapter class for a {@link IMessagesBundleGroupListener}. Methods
+ * implementation do nothing.
+ * @author Pascal Essiembre ([email protected])
+ */
+public class MessagesBundleGroupAdapter
+ implements IMessagesBundleGroupListener {
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
+ * keyAdded(java.lang.String)
+ */
+ public void keyAdded(String key) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
+ * keyRemoved(java.lang.String)
+ */
+ public void keyRemoved(String key) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
+ * messagesBundleAdded(org.eclipse.babel.core.message.internal.MessagesBundle)
+ */
+ public void messagesBundleAdded(MessagesBundle messagesBundle) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener#
+ * messagesBundleChanged(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * java.beans.PropertyChangeEvent)
+ */
+ public void messagesBundleChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener
+ * #messagesBundleRemoved(org.eclipse.babel.core.message.internal.MessagesBundle)
+ */
+ public void messagesBundleRemoved(MessagesBundle messagesBundle) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#messageAdded(
+ * org.eclipse.babel.core.message.internal.MessagesBundle,
+ * org.eclipse.babel.core.message.internal.Message)
+ */
+ public void messageAdded(MessagesBundle messagesBundle, Message message) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#
+ * messageChanged(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * java.beans.PropertyChangeEvent)
+ */
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.IMessagesBundleListener#
+ * messageRemoved(org.eclipse.babel.core.message.internal.MessagesBundle,
+ * org.eclipse.babel.core.message.internal.Message)
+ */
+ public void messageRemoved(MessagesBundle messagesBundle, Message message) {
+ // do nothing
+ }
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(
+ * java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent evt) {
+ // do nothing
+ }
+}
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 030fc712..b4d7aaf9 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,13 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
package org.eclipse.babel.core.message.manager;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundle;
+/**
+ * Used to sync TapiJI with Babel and vice versa.
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
public interface IMessagesEditorListener {
+ /**
+ * Should only be called when the editor performs save!
+ */
void onSave();
+ /**
+ * Can be called when the Editor changes.
+ */
void onModify();
+ /**
+ * Called when a {@link IMessagesBundle} changed.
+ * @param bundle
+ */
void onResourceChanged(IMessagesBundle bundle);
+ // TODO: Get rid of this method, maybe merge with onModify()
}
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
new file mode 100644
index 00000000..4f309816
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.manager;
+
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.core.resources.IResource;
+
+
+/**
+ * Used to update TapiJI (ResourceBundleManager) when bundles have been removed.
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
+public interface IResourceDeltaListener {
+
+ /**
+ * Called when a resource (= bundle) has been removed
+ * @param resourceBundleId The {@link IMessagesBundleGroup} which contains the bundle
+ * @param resource The resource itself
+ */
+ public void onDelete(String resourceBundleId, IResource resource);
+
+ /**
+ * Called when a {@link IMessagesBundleGroup} has been removed
+ * @param bundleGroup The removed bundle group
+ */
+ public void onDelete(IMessagesBundleGroup bundleGroup);
+
+}
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 ac73c955..1d8f7d79 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,7 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
package org.eclipse.babel.core.message.manager;
-import java.io.ByteArrayInputStream;
-import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -9,177 +17,287 @@
import java.util.Locale;
import java.util.Map;
import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
-import org.eclipse.babel.core.configuration.ConfigurationManager;
import org.eclipse.babel.core.configuration.DirtyHack;
import org.eclipse.babel.core.factory.MessagesBundleGroupFactory;
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.resource.PropertiesFileResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.babel.core.message.strategy.PropertiesFileGroupStrategy;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.Message;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.util.FileUtils;
+import org.eclipse.babel.core.util.NameUtils;
import org.eclipse.babel.core.util.PDEUtils;
-import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
/**
+ * Manages all {@link MessagesBundleGroup}s. That is: <li>Hold map with projects
+ * and their RBManager (1 RBManager per project)</li> <li>Hold up-to-date map
+ * with resource bundles (= {@link MessagesBundleGroup})</li> <li>Hold
+ * {@link IMessagesEditorListener}, which can be used to keep systems in sync</li>
+ * <br>
+ * <br>
*
* @author Alexej Strelzow
*/
public class RBManager {
private static Map<IProject, RBManager> managerMap = new HashMap<IProject, RBManager>();
-
+
+ /** <package>.<resourceBundleName> , IMessagesBundleGroup */
private Map<String, IMessagesBundleGroup> resourceBundles;
private static RBManager INSTANCE;
-
+
private List<IMessagesEditorListener> editorListeners;
+ private List<IResourceDeltaListener> resourceListeners;
+
private IProject project;
-
+
+ private static final String TAPIJI_NATURE = "org.eclipse.babel.tapiji.tools.core.nature";
+
+ private static Logger logger = Logger.getLogger(RBManager.class
+ .getSimpleName());
+
private RBManager() {
resourceBundles = new HashMap<String, IMessagesBundleGroup>();
editorListeners = new ArrayList<IMessagesEditorListener>(3);
+ resourceListeners = new ArrayList<IResourceDeltaListener>(2);
}
-
- public IMessagesBundleGroup getMessagesBundleGroup(String name) {
- if (!resourceBundles.containsKey(name)) {
- System.out.println("ohje"); // TODO log
+
+ /**
+ * @param resourceBundleId
+ * <package>.<resourceBundleName>
+ * @return {@link IMessagesBundleGroup} if found, else <code>null</code>
+ */
+ public IMessagesBundleGroup getMessagesBundleGroup(String resourceBundleId) {
+ if (!resourceBundles.containsKey(resourceBundleId)) {
+ logger.log(Level.SEVERE,
+ "getMessagesBundleGroup with non-existing Id: "
+ + resourceBundleId);
return null;
} else {
- return resourceBundles.get(name);
+ return resourceBundles.get(resourceBundleId);
}
}
-
+
+ /**
+ * @return All the names of the <code>resourceBundles</code> in the format:
+ * <projectName>/<resourceBundleId>
+ */
public List<String> getMessagesBundleGroupNames() {
- Set<String> keySet = resourceBundles.keySet();
List<String> bundleGroupNames = new ArrayList<String>();
-
- for (String key : keySet) {
+
+ for (String key : resourceBundles.keySet()) {
bundleGroupNames.add(project.getName() + "/" + key);
}
return bundleGroupNames;
}
-
+
+ /**
+ * @return All the {@link #getMessagesBundleGroupNames()} of all the
+ * projects.
+ */
public static List<String> getAllMessagesBundleGroupNames() {
- Set<IProject> projects = getAllSupportedProjects();
List<String> bundleGroupNames = new ArrayList<String>();
-
- for (IProject project : projects) {
+
+ for (IProject project : getAllSupportedProjects()) {
RBManager manager = getInstance(project);
bundleGroupNames.addAll(manager.getMessagesBundleGroupNames());
- }
+ }
return bundleGroupNames;
}
-
+
/**
- * Hier darf nur BABEL rein
+ * Notification, that a {@link IMessagesBundleGroup} has been created and
+ * needs to be managed by the {@link RBManager}.
+ *
* @param bundleGroup
+ * The new {@link IMessagesBundleGroup}
*/
- public void notifyMessagesBundleCreated(IMessagesBundleGroup bundleGroup) {
+ public void notifyMessagesBundleGroupCreated(
+ IMessagesBundleGroup bundleGroup) {
if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
- IMessagesBundleGroup oldbundleGroup = resourceBundles.get(bundleGroup.getResourceBundleId());
+ IMessagesBundleGroup oldbundleGroup = resourceBundles
+ .get(bundleGroup.getResourceBundleId());
+
+ // not the same object
if (!equalHash(oldbundleGroup, bundleGroup)) {
- boolean oldHasPropertiesStrategy = oldbundleGroup.hasPropertiesFileGroupStrategy();
- boolean newHasPropertiesStrategy = bundleGroup.hasPropertiesFileGroupStrategy();
-
- // in this case, the old one is only writing to the property file, not the editor
- // we have to sync them and store the bundle with the editor as resource
+ // we need to distinguish between 2 kinds of resources:
+ // 1) Property-File
+ // 2) Eclipse-Editor
+ // When first 1) is used, and some operations where made, we
+ // need to
+ // sync 2) when it appears!
+ boolean oldHasPropertiesStrategy = oldbundleGroup
+ .hasPropertiesFileGroupStrategy();
+ boolean newHasPropertiesStrategy = bundleGroup
+ .hasPropertiesFileGroupStrategy();
+
+ // in this case, the old one is only writing to the property
+ // file, not the editor
+ // we have to sync them and store the bundle with the editor as
+ // resource
if (oldHasPropertiesStrategy && !newHasPropertiesStrategy) {
-
+
syncBundles(bundleGroup, oldbundleGroup);
- resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
-
+ resourceBundles.put(bundleGroup.getResourceBundleId(),
+ bundleGroup);
+
+ logger.log(
+ Level.INFO,
+ "sync: " + bundleGroup.getResourceBundleId()
+ + " with "
+ + oldbundleGroup.getResourceBundleId());
+
oldbundleGroup.dispose();
-
- } else if ( (oldHasPropertiesStrategy && newHasPropertiesStrategy)
- || (!oldHasPropertiesStrategy && !newHasPropertiesStrategy) ) {
-
-// syncBundles(oldbundleGroup, bundleGroup); do not need that, because we take the new one
- // and we do that, because otherwise we cache old Text-Editor instances, which we
+
+ } else if ((oldHasPropertiesStrategy && newHasPropertiesStrategy)
+ || (!oldHasPropertiesStrategy && !newHasPropertiesStrategy)) {
+
+ // syncBundles(oldbundleGroup, bundleGroup); do not need
+ // that, because we take the new one
+ // and we do that, because otherwise we cache old
+ // Text-Editor instances, which we
// do not need -> read only phenomenon
- resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
-
+ resourceBundles.put(bundleGroup.getResourceBundleId(),
+ bundleGroup);
+
+ logger.log(
+ Level.INFO,
+ "replace: " + bundleGroup.getResourceBundleId()
+ + " with "
+ + oldbundleGroup.getResourceBundleId());
+
oldbundleGroup.dispose();
} else {
- // in this case our old resource has an EditorSite, but not the new one
+ // in this case our old resource has an EditorSite, but not
+ // the new one
+ logger.log(Level.INFO,
+ "dispose: " + bundleGroup.getResourceBundleId());
+
bundleGroup.dispose();
}
}
} else {
resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
+
+ logger.log(Level.INFO, "add: " + bundleGroup.getResourceBundleId());
}
}
-
+
/**
- * Hier darf nur BABEL rein
+ * Notification, that a {@link IMessagesBundleGroup} has been deleted!
+ *
* @param bundleGroup
+ * The {@link IMessagesBundleGroup} to remove
*/
- public void notifyMessagesBundleDeleted(IMessagesBundleGroup bundleGroup) {
+ public void notifyMessagesBundleGroupDeleted(
+ IMessagesBundleGroup bundleGroup) {
if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
- if (equalHash(resourceBundles.get(bundleGroup.getResourceBundleId()), bundleGroup)) {
+ if (equalHash(
+ resourceBundles.get(bundleGroup.getResourceBundleId()),
+ bundleGroup)) {
resourceBundles.remove(bundleGroup.getResourceBundleId());
- System.out.println(bundleGroup.getResourceBundleId() + " deleted!");
+
+ for (IResourceDeltaListener deltaListener : resourceListeners) {
+ deltaListener.onDelete(bundleGroup);
+ }
}
- }
+ }
}
-
+
+ /**
+ * Notification, that a resource bundle (= {@link MessagesBundle}) have been
+ * removed.
+ *
+ * @param resourceBundle
+ * The removed {@link MessagesBundle}
+ */
public void notifyResourceRemoved(IResource resourceBundle) {
- //String parentName = resourceBundle.getParent().getName();
- //String resourceBundleId = parentName + "." + getResourceBundleName(resourceBundle);
- String resourceBundleId = PropertiesFileGroupStrategy.getResourceBundleId(resourceBundle);
- IMessagesBundleGroup bundleGroup = resourceBundles.get(resourceBundleId);
+ String resourceBundleId = NameUtils.getResourceBundleId(resourceBundle);
+
+ IMessagesBundleGroup bundleGroup = resourceBundles
+ .get(resourceBundleId);
+
if (bundleGroup != null) {
- Locale locale = getLocaleByName(getResourceBundleName(resourceBundle), resourceBundle.getName());
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(locale);
+ Locale locale = NameUtils.getLocaleByName(
+ NameUtils.getResourceBundleName(resourceBundle),
+ resourceBundle.getName());
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(locale);
if (messagesBundle != null) {
bundleGroup.removeMessagesBundle(messagesBundle);
}
+
+ for (IResourceDeltaListener deltaListener : resourceListeners) {
+ deltaListener.onDelete(resourceBundleId, resourceBundle);
+ }
+
if (bundleGroup.getMessagesBundleCount() == 0) {
- notifyMessagesBundleDeleted(bundleGroup);
+ notifyMessagesBundleGroupDeleted(bundleGroup);
}
}
-
+
// TODO: maybe save and reinit the editor?
}
-
+
/**
- * Weil der BABEL-Builder nicht richtig funkt (added 1 x und removed 2 x das GLEICHE!)
+ * Because BABEL-Builder does not work correctly (adds 1 x and removes 2 x
+ * the SAME {@link MessagesBundleGroup}!)
+ *
* @param oldBundleGroup
+ * {@link IMessagesBundleGroup}
* @param newBundleGroup
- * @return
+ * {@link IMessagesBundleGroup}
+ * @return <code>true</code> if same {@link IMessagesBundleGroup}, else
+ * <code>false</code>
*/
- private boolean equalHash(IMessagesBundleGroup oldBundleGroup, IMessagesBundleGroup newBundleGroup) {
- int oldHashCode = oldBundleGroup.hashCode();
- int newHashCode = newBundleGroup.hashCode();
- return oldHashCode == newHashCode;
+ private boolean equalHash(IMessagesBundleGroup oldBundleGroup,
+ IMessagesBundleGroup newBundleGroup) {
+ return oldBundleGroup.hashCode() == newBundleGroup.hashCode();
}
-
- private void syncBundles(IMessagesBundleGroup oldBundleGroup, IMessagesBundleGroup newBundleGroup) {
+
+ /**
+ * Has only one use case. If we worked with property-file as resource and
+ * afterwards the messages editor pops open, we need to sync them, so that
+ * the information of the property-file won't get lost.
+ *
+ * @param oldBundleGroup
+ * The prior {@link IMessagesBundleGroup}
+ * @param newBundleGroup
+ * The replacement
+ */
+ private void syncBundles(IMessagesBundleGroup oldBundleGroup,
+ IMessagesBundleGroup newBundleGroup) {
List<IMessagesBundle> bundlesToRemove = new ArrayList<IMessagesBundle>();
List<IMessage> keysToRemove = new ArrayList<IMessage>();
-
- DirtyHack.setFireEnabled(false); // hebelt AbstractMessageModel aus
- // sonst m�ssten wir in setText von EclipsePropertiesEditorResource ein asyncExec zulassen
-
+
+ DirtyHack.setFireEnabled(false); // hebelt AbstractMessageModel aus
+ // sonst m�ssten wir in setText von EclipsePropertiesEditorResource
+ // ein
+ // asyncExec zulassen
+
for (IMessagesBundle newBundle : newBundleGroup.getMessagesBundles()) {
- IMessagesBundle oldBundle = oldBundleGroup.getMessagesBundle(newBundle.getLocale());
+ IMessagesBundle oldBundle = oldBundleGroup
+ .getMessagesBundle(newBundle.getLocale());
if (oldBundle == null) { // it's a new one
- oldBundleGroup.addMessagesBundle(newBundle.getLocale(), newBundle);
+ oldBundleGroup.addMessagesBundle(newBundle.getLocale(),
+ newBundle);
} else { // check keys
for (IMessage newMsg : newBundle.getMessages()) {
- if (oldBundle.getMessage(newMsg.getKey()) == null) { // new entry, create new message
- oldBundle.addMessage(new Message(newMsg.getKey(), newMsg.getLocale()));
+ if (oldBundle.getMessage(newMsg.getKey()) == null) {
+ // new entry, create new message
+ oldBundle.addMessage(new Message(newMsg.getKey(),
+ newMsg.getLocale()));
} else { // update old entries
IMessage oldMsg = oldBundle.getMessage(newMsg.getKey());
if (oldMsg == null) { // it's a new one
@@ -192,10 +310,11 @@ private void syncBundles(IMessagesBundleGroup oldBundleGroup, IMessagesBundleGro
}
}
}
-
+
// check keys
for (IMessagesBundle oldBundle : oldBundleGroup.getMessagesBundles()) {
- IMessagesBundle newBundle = newBundleGroup.getMessagesBundle(oldBundle.getLocale());
+ IMessagesBundle newBundle = newBundleGroup
+ .getMessagesBundle(oldBundle.getLocale());
if (newBundle == null) { // we have an old one
bundlesToRemove.add(oldBundle);
} else {
@@ -206,60 +325,85 @@ private void syncBundles(IMessagesBundleGroup oldBundleGroup, IMessagesBundleGro
}
}
}
-
+
for (IMessagesBundle bundle : bundlesToRemove) {
oldBundleGroup.removeMessagesBundle(bundle);
}
-
+
for (IMessage msg : keysToRemove) {
- IMessagesBundle mb = oldBundleGroup.getMessagesBundle(msg.getLocale());
+ IMessagesBundle mb = oldBundleGroup.getMessagesBundle(msg
+ .getLocale());
if (mb != null) {
mb.removeMessage(msg.getKey());
}
}
-
+
DirtyHack.setFireEnabled(true);
-
+
}
-
+
/**
- * Hier darf nur TAPIJI rein
- * @param bundleGroup
+ * If TapiJI needs to delete sth.
+ *
+ * @param resourceBundleId
+ * The resourceBundleId
*/
- public void deleteMessagesBundle(String name) {
- if (resourceBundles.containsKey(name)) {
- resourceBundles.remove(name);
+ public void deleteMessagesBundleGroup(String resourceBundleId) {
+ // TODO: Try to unify it some time
+ if (resourceBundles.containsKey(resourceBundleId)) {
+ resourceBundles.remove(resourceBundleId);
} else {
- System.out.println("ohje");
+ logger.log(Level.SEVERE,
+ "deleteMessagesBundleGroup with non-existing Id: "
+ + resourceBundleId);
}
}
-
- public boolean containsMessagesBundleGroup(String name) {
- return resourceBundles.containsKey(name);
+
+ /**
+ * @param resourceBundleId
+ * The resourceBundleId
+ * @return <code>true</code> if the manager knows the
+ * {@link MessagesBundleGroup} with the id resourceBundleId
+ */
+ public boolean containsMessagesBundleGroup(String resourceBundleId) {
+ return resourceBundles.containsKey(resourceBundleId);
}
-
+
+ /**
+ * @param project
+ * The project, which is managed by the {@link RBManager}
+ * @return The corresponding {@link RBManager} to the project
+ */
public static RBManager getInstance(IProject project) {
// set host-project
- if (PDEUtils.isFragment(project))
- project = PDEUtils.getFragmentHost(project);
-
+ if (PDEUtils.isFragment(project)) {
+ project = PDEUtils.getFragmentHost(project);
+ }
+
INSTANCE = managerMap.get(project);
-
+
if (INSTANCE == null) {
INSTANCE = new RBManager();
INSTANCE.project = project;
managerMap.put(project, INSTANCE);
INSTANCE.detectResourceBundles();
}
-
+
return INSTANCE;
}
-
+
+ /**
+ * @param projectName
+ * The name of the project, which is managed by the
+ * {@link RBManager}
+ * @return The corresponding {@link RBManager} to the project
+ */
public static RBManager getInstance(String projectName) {
- for (IProject project : getAllSupportedProjects()) {
+ for (IProject project : getAllWorkspaceProjects(true)) {
if (project.getName().equals(projectName)) {
- //check if the projectName is a fragment and return the manager for the host
- if(PDEUtils.isFragment(project)) {
+ // check if the projectName is a fragment and return the manager
+ // for the host
+ if (PDEUtils.isFragment(project)) {
return getInstance(PDEUtils.getFragmentHost(project));
} else {
return getInstance(project);
@@ -268,169 +412,145 @@ public static RBManager getInstance(String projectName) {
}
return null;
}
-
- public static Set<IProject> getAllSupportedProjects () {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+
+ /**
+ * @param ignoreNature
+ * <code>true</code> if the internationalization nature should be
+ * ignored, else <code>false</code>
+ * @return A set of projects, which have the nature (ignoreNature == false)
+ * or not.
+ */
+ public static Set<IProject> getAllWorkspaceProjects(boolean ignoreNature) {
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
Set<IProject> projs = new HashSet<IProject>();
-
+
for (IProject p : projects) {
try {
- if (p.hasNature("org.eclipselabs.tapiji.tools.core.nature")) {
+ if (ignoreNature || p.hasNature(TAPIJI_NATURE)) {
projs.add(p);
}
} catch (CoreException e) {
- e.printStackTrace();
+ logger.log(Level.SEVERE,
+ "getAllWorkspaceProjects(...): hasNature failed!", e);
}
}
return projs;
}
-
+
+ /**
+ * @return All supported projects, those who have the correct nature.
+ */
+ public static Set<IProject> getAllSupportedProjects() {
+ return getAllWorkspaceProjects(false);
+ }
+
+ /**
+ * @param listener
+ * {@link IMessagesEditorListener} to add
+ */
public void addMessagesEditorListener(IMessagesEditorListener listener) {
this.editorListeners.add(listener);
}
-
+
+ /**
+ * @param listener
+ * {@link IMessagesEditorListener} to remove
+ */
public void removeMessagesEditorListener(IMessagesEditorListener listener) {
this.editorListeners.remove(listener);
}
+ /**
+ * @param listener
+ * {@link IResourceDeltaListener} to add
+ */
+ public void addResourceDeltaListener(IResourceDeltaListener listener) {
+ this.resourceListeners.add(listener);
+ }
+
+ /**
+ * @param listener
+ * {@link IResourceDeltaListener} to remove
+ */
+ public void removeResourceDeltaListener(IResourceDeltaListener listener) {
+ this.resourceListeners.remove(listener);
+ }
+
+ /**
+ * Fire: MessagesEditor has been saved
+ */
public void fireEditorSaved() {
for (IMessagesEditorListener listener : this.editorListeners) {
listener.onSave();
}
+ logger.log(Level.INFO, "fireEditorSaved");
}
-
+
+ /**
+ * Fire: MessagesEditor has been modified
+ */
public void fireEditorChanged() {
for (IMessagesEditorListener listener : this.editorListeners) {
listener.onModify();
}
+ logger.log(Level.INFO, "fireEditorChanged");
}
-
+
+ /**
+ * Fire: {@link IMessagesBundle} has been edited
+ */
public void fireResourceChanged(IMessagesBundle bundle) {
for (IMessagesEditorListener listener : this.editorListeners) {
listener.onResourceChanged(bundle);
+ logger.log(Level.INFO, "fireResourceChanged"
+ + bundle.getResource().getResourceLocationLabel());
}
}
-
- protected void detectResourceBundles () {
- try {
+
+ /**
+ * Detects all resource bundles, which we want to work with.
+ */
+ protected void detectResourceBundles() {
+ try {
project.accept(new ResourceBundleDetectionVisitor(this));
-
+
IProject[] fragments = PDEUtils.lookupFragment(project);
- if (fragments != null){
- for (IProject p : fragments){
+ if (fragments != null) {
+ for (IProject p : fragments) {
p.accept(new ResourceBundleDetectionVisitor(this));
}
}
} catch (CoreException e) {
+ logger.log(Level.SEVERE, "detectResourceBundles: accept failed!", e);
}
}
-
+
// passive loading -> see detectResourceBundles
+ /**
+ * Invoked by {@link #detectResourceBundles()}.
+ */
public void addBundleResource(IResource resource) {
// create it with MessagesBundleFactory or read from resource!
// we can optimize that, now we create a bundle group for each bundle
// we should create a bundle group only once!
-
- String resourceBundleId = getResourceBundleId(resource);
+
+ String resourceBundleId = NameUtils.getResourceBundleId(resource);
if (!resourceBundles.containsKey(resourceBundleId)) {
// if we do not have this condition, then you will be doomed with
// resource out of syncs, because here we instantiate
// PropertiesFileResources, which have an evil setText-Method
MessagesBundleGroupFactory.createBundleGroup(resource);
+
+ logger.log(Level.INFO, "addBundleResource (passive loading): "
+ + resource.getName());
}
}
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
- public 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 void writeToFile(IMessagesBundleGroup bundleGroup) {
for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) {
- writeToFile(bundle);
- }
- }
-
- public void writeToFile(IMessagesBundle bundle) {
- DirtyHack.setEditorModificationEnabled(false);
-
- PropertiesSerializer ps = new PropertiesSerializer(ConfigurationManager.getInstance().getSerializerConfig());
- String editorContent = ps.serialize(bundle);
- IFile file = getFile(bundle);
- try {
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- file.setContents(new ByteArrayInputStream(editorContent.getBytes()),
- false, true, null);
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- DirtyHack.setEditorModificationEnabled(true);
- }
-
- fireResourceChanged(bundle);
-
- }
-
- private IFile getFile(IMessagesBundle bundle) {
- if (bundle.getResource() instanceof PropertiesFileResource) { // different ResourceLocationLabel
- String path = bundle.getResource().getResourceLocationLabel(); // P:\Allianz\Workspace\AST\TEST\src\messages\Messages_de.properties
- int index = path.indexOf("src");
- String pathBeforeSrc = path.substring(0, index - 1);
- int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
- String projectName = path.substring(lastIndexOf + 1, index - 1);
- String relativeFilePath = path.substring(index, path.length());
-
- return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(relativeFilePath);
- } else {
- String location = bundle.getResource().getResourceLocationLabel(); ///TEST/src/messages/Messages_en_IN.properties
- location = location.substring(project.getName().length() + 1, location.length());
- return ResourcesPlugin.getWorkspace().getRoot().getProject(project.getName()).getFile(location);
- }
- }
-
- protected Locale getLocaleByName (String bundleName, String localeID) {
- // Check locale
- Locale locale = null;
- localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
- if (localeID.length() == bundleName.length()) {
- // default locale
- return null;
- } else {
- localeID = localeID.substring(bundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
-
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
- break;
- default:
- locale = null;
- break;
- }
+ FileUtils.writeToFile(bundle);
+ fireResourceChanged(bundle);
}
-
- return locale;
}
}
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 25e0e209..6f7d5ccc 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,3 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - detection if isResourceBundleFile
+ ******************************************************************************/
+
package org.eclipse.babel.core.message.manager;
import java.util.LinkedList;
@@ -13,12 +25,11 @@
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
-
public class ResourceBundleDetectionVisitor implements IResourceVisitor,
IResourceDeltaVisitor {
private RBManager manager = null;
-
+
public ResourceBundleDetectionVisitor(RBManager manager) {
this.manager = manager;
}
@@ -26,12 +37,7 @@ public ResourceBundleDetectionVisitor(RBManager manager) {
public boolean visit(IResource resource) throws CoreException {
try {
if (isResourceBundleFile(resource)) {
-
-// Logger.logInfo("Loading Resource-Bundle file '" + resource.getName() + "'");
-
-// if (!ResourceBundleManager.isResourceExcluded(resource)) {
- manager.addBundleResource(resource);
-// }
+ manager.addBundleResource(resource);
return false;
} else
return true;
@@ -44,87 +50,98 @@ public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
if (isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
return false;
}
-
+
return true;
}
-
- private final String RB_MARKER_ID = "org.eclipselabs.tapiji.tools.core.ResourceBundleAuditMarker";
-
+
+ private final String RB_MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ResourceBundleAuditMarker";
+
private boolean isResourceBundleFile(IResource file) {
boolean isValied = false;
-
- if (file != null && file instanceof IFile && !file.isDerived() &&
- file.getFileExtension()!=null && file.getFileExtension().equalsIgnoreCase("properties")){
+
+ if (file != null && file instanceof IFile && !file.isDerived()
+ && file.getFileExtension() != null
+ && file.getFileExtension().equalsIgnoreCase("properties")) {
isValied = true;
-
+
List<CheckItem> list = getBlacklistItems();
- for (CheckItem item : list){
- if (item.getChecked() && file.getFullPath().toString().matches(item.getName())){
+ 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 properties-file is not RB-file and has
+ // ResouceBundleMarker, deletes all ResouceBundleMarker of
+ // the file
if (hasResourceBundleMarker(file))
try {
- file.deleteMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE);
+ file.deleteMarkers(RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE);
} catch (CoreException e) {
}
}
}
}
-
+
return isValied;
}
-
+
private List<CheckItem> getBlacklistItems() {
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
return convertStringToList(configuration.getNonRbPattern());
}
-
+
private static final String DELIMITER = ";";
private static final String ATTRIBUTE_DELIMITER = ":";
-
+
private 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);
+ StringTokenizer attribute = new StringTokenizer(
+ tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
String name = attribute.nextToken();
boolean checked;
- if (attribute.nextToken().equals("true")) checked = true;
- else checked = false;
-
+ if (attribute.nextToken().equals("true"))
+ checked = true;
+ else
+ checked = false;
+
elements.add(new CheckItem(name, checked));
}
return elements;
}
-
+
/**
* Checks whether a RB-file has a problem-marker
*/
- public boolean hasResourceBundleMarker(IResource r){
+ public boolean hasResourceBundleMarker(IResource r) {
try {
- if(r.findMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
- return true;
- else return false;
+ if (r.findMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
+ return true;
+ else
+ return false;
} catch (CoreException e) {
return false;
}
}
-
- private class CheckItem{
+
+ private class CheckItem {
boolean checked;
String name;
-
+
public CheckItem(String item, boolean checked) {
this.name = item;
this.checked = checked;
}
-
+
public String getName() {
return name;
}
@@ -133,5 +150,5 @@ public boolean getChecked() {
return checked;
}
}
-
+
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/AbstractMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/AbstractMessagesResource.java
deleted file mode 100644
index 4e287fc9..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/AbstractMessagesResource.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.resource;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResourceChangeListener;
-
-/**
- * Base implementation of a {@link IMessagesResource} bound to a locale
- * and providing ways to add and remove {@link IMessagesResourceChangeListener}
- * instances.
- * @author Pascal Essiembre
- */
-public abstract class AbstractMessagesResource implements IMessagesResource {
-
- private Locale locale;
- private List<IMessagesResourceChangeListener> listeners = new ArrayList<IMessagesResourceChangeListener>();
-
- /**
- * Constructor.
- * @param locale bound locale
- */
- public AbstractMessagesResource(Locale locale) {
- super();
- this.locale = locale;
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.resource.IMessagesResource#getLocale()
- */
- public Locale getLocale() {
- return locale;
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource#
- * addMessagesResourceChangeListener(
- * org.eclipse.babel.core.message.resource
- * .IMessagesResourceChangeListener)
- */
- public void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener) {
- listeners.add(0, listener);
- }
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource#
- * removeMessagesResourceChangeListener(
- * org.eclipse.babel.core.message
- * .resource.IMessagesResourceChangeListener)
- */
- public void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener) {
- listeners.remove(listener);
- }
-
- /**
- * Fires notification that a {@link IMessagesResource} changed.
- * @param resource {@link IMessagesResource}
- */
- protected void fireResourceChange(IMessagesResource resource) {
- for (IMessagesResourceChangeListener listener : listeners) {
- listener.resourceChanged(resource);
- }
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/AbstractPropertiesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/AbstractPropertiesResource.java
deleted file mode 100644
index ed186401..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/AbstractPropertiesResource.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.resource;
-
-import java.util.Locale;
-import java.util.Properties;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-/**
- * Based implementation of a text-based messages resource following
- * the conventions defined by the Java {@link Properties} class for
- * serialization and deserialization.
- * @author Pascal Essiembre
- */
-public abstract class AbstractPropertiesResource
- extends AbstractMessagesResource {
-
- private PropertiesDeserializer deserializer;
- private PropertiesSerializer serializer;
-
- /**
- * Constructor.
- * @param locale properties locale
- * @param serializer properties serializer
- * @param deserializer properties deserializer
- */
- public AbstractPropertiesResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer) {
- super(locale);
- this.deserializer = deserializer;
- this.serializer = serializer;
- //TODO initialises with configurations only...
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource#serialize(
- * org.eclipse.babel.core.message.MessagesBundle)
- */
- public void serialize(IMessagesBundle messagesBundle) {
- setText(serializer.serialize(messagesBundle));
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource
- * #deserialize(org.eclipse.babel.core.message.MessagesBundle)
- */
- public void deserialize(IMessagesBundle messagesBundle) {
- deserializer.deserialize(messagesBundle, getText());
- }
-
- /**
- * Gets the {@link Properties}-like formated text.
- * @return formated text
- */
- protected abstract String getText();
- /**
- * Sets the {@link Properties}-like formated text.
- * @param text formated text
- */
- protected abstract void setText(String text);
-
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java
new file mode 100644
index 00000000..ca16df44
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.resource;
+
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesResourceChangeListener;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+
+/**
+ * Class abstracting the underlying native storage mechanism for persisting
+ * internationalised text messages.
+ *
+ * @author Pascal Essiembre
+ */
+public interface IMessagesResource {
+
+ /**
+ * Gets the resource locale.
+ *
+ * @return locale
+ */
+ Locale getLocale();
+
+ /**
+ * Gets the underlying object abstracted by this resource (e.g. a File).
+ *
+ * @return source object
+ */
+ Object getSource();
+
+ /**
+ * Serializes a {@link MessagesBundle} instance to its native format.
+ *
+ * @param messagesBundle
+ * the MessagesBundle to serialize
+ */
+ void serialize(IMessagesBundle messagesBundle);
+
+ /**
+ * Deserializes a {@link MessagesBundle} instance from its native format.
+ *
+ * @param messagesBundle
+ * the MessagesBundle to deserialize
+ */
+ void deserialize(IMessagesBundle messagesBundle);
+
+ /**
+ * Adds a messages resource listener. Implementors are required to notify
+ * listeners of changes within the native implementation.
+ *
+ * @param listener
+ * the listener
+ */
+ void addMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
+
+ /**
+ * Removes a messages resource listener.
+ *
+ * @param listener
+ * the listener
+ */
+ void removeMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
+
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ String getResourceLocationLabel();
+
+ /**
+ * Called when the group it belongs to is disposed.
+ */
+ void dispose();
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesFileResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesFileResource.java
deleted file mode 100644
index 7ad534b9..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesFileResource.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.resource;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.babel.core.util.FileChangeListener;
-import org.eclipse.babel.core.util.FileMonitor;
-
-
-/**
- * Properties file, where the underlying storage is a regular {@link File}.
- * For files referenced through Eclipse workspace, implementors should
- * use {@link PropertiesIFileResource}.
- *
- * @author Pascal Essiembre
- * @see PropertiesIFileResource
- */
-public class PropertiesFileResource extends AbstractPropertiesResource {
-
- private File file;
-
- private FileChangeListenerImpl fileChangeListener;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param file the underlying file
- * @throws FileNotFoundException
- */
- public PropertiesFileResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- File file) throws FileNotFoundException {
- super(locale, serializer, deserializer);
- this.file = file;
- this.fileChangeListener = new FileChangeListenerImpl();
-
- FileMonitor.getInstance().addFileChangeListener(this.fileChangeListener, file, 2000); //TODO make file scan delay configurable
- }
-
-
- /**
- * @see org.eclipse.babel.core.message.resource.AbstractPropertiesResource
- * #getText()
- */
- public String getText() {
- FileReader inputStream = null;
- StringWriter outputStream = null;
- try {
- if (!file.exists()) {
- return "";
- }
- inputStream = new FileReader(file);
- outputStream = new StringWriter();
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException(
- "Cannot get properties file text. Handle better.", e);
- } finally {
- closeReader(inputStream);
- closeWriter(outputStream);
- }
- return outputStream.toString();
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.AbstractPropertiesResource
- * #setText(java.lang.String)
- */
- public void setText(String content) {
- StringReader inputStream = null;
- FileWriter outputStream = null;
- try {
- inputStream = new StringReader(content);
- outputStream = new FileWriter(file);
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException(
- "Cannot get properties file text. Handle better.", e);
- } finally {
- closeReader(inputStream);
- closeWriter(outputStream);
-
-// IFile file =
-// ResourcesPlugin.getWorkspace().getRoot().getFileForLocation( new
-// Path(getResourceLocationLabel()));
-// try {
-// file.refreshLocal(IResource.DEPTH_ZERO, null);
-// } catch (CoreException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource
- * .IMessagesResource#getSource()
- */
- public Object getSource() {
- return file;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- return file.getAbsolutePath();
- }
-
- //TODO move to util class for convinience???
- private void closeWriter(Writer writer) {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException("Cannot close writer stream.", e);
- }
- }
- }
-
- //TODO move to util class for convinience???
- public void closeReader(Reader reader) {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException("Cannot close reader.", e);
- }
- }
- }
-
- /**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this file.
- */
- public void dispose() {
- FileMonitor.getInstance().removeFileChangeListener(this.fileChangeListener, file);
- }
-
- private class FileChangeListenerImpl implements FileChangeListener {
-
- @Override
- public void fileChanged(final File changedFile) {
- fireResourceChange(PropertiesFileResource.this);
- }
-
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesIFileResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesIFileResource.java
deleted file mode 100644
index 04a6aec9..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesIFileResource.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.resource;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.AbstractIFileChangeListener;
-import org.eclipse.babel.core.message.AbstractIFileChangeListener.IFileChangeListenerRegistry;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.runtime.CoreException;
-
-
-/**
- * Properties file, where the underlying storage is a {@link IFile}.
- * When dealing with {@link File} as opposed to {@link IFile},
- * implementors should use {@link PropertiesFileResource}.
- *
- * @author Pascal Essiembre
- * @see PropertiesFileResource
- */
-public class PropertiesIFileResource extends AbstractPropertiesResource {
-
- private final IFile file;
-
- private final AbstractIFileChangeListener fileListener;
- private final IFileChangeListenerRegistry listenerRegistry;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param file the underlying {@link IFile}
- * @param listenerRegistry It is the MessageEditorPlugin.
- * Or null if we don't care for file changes.
- * We could replace it by an activator in this plugin.
- */
- public PropertiesIFileResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- IFile file, IFileChangeListenerRegistry listenerRegistry) {
- super(locale, serializer, deserializer);
- this.file = file;
- this.listenerRegistry = listenerRegistry;
-
- //[hugues] FIXME: this object is built at the beginning
- //of a build (no message editor)
- //it is disposed of at the end of the build.
- //during a build files are not changed.
- //so it is I believe never called.
- if (this.listenerRegistry != null) {
- IResourceChangeListener rcl =
- new IResourceChangeListener() {
- public void resourceChanged(IResourceChangeEvent event) {
- //no need to check: it is always the case as this
- //is subscribed for a particular file.
-// if (event.getResource() != null
-// && PropertiesIFileResource.this.file.equals(event.getResource())) {
- fireResourceChange(PropertiesIFileResource.this);
-// }
- }
- };
- fileListener = AbstractIFileChangeListener
- .wrapResourceChangeListener(rcl, file);
- this.listenerRegistry.subscribe(fileListener);
- } else {
- fileListener = null;
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.AbstractPropertiesResource
- * #getText()
- */
- public String getText() {
- try {
- file.refreshLocal(IResource.DEPTH_INFINITE, null);
- InputStream is = file.getContents();
- int byteCount = is.available();
- byte[] b = new byte[byteCount];
- is.read(b);
- String content = new String(b, file.getCharset());
- return content;
- } catch (IOException e) {
- throw new RuntimeException(e); //TODO handle better
- } catch (CoreException e) {
- throw new RuntimeException(e); //TODO handle better
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.TextResource#setText(
- * java.lang.String)
- */
- public void setText(String text) {
- try {
- String charset = file.getCharset();
- ByteArrayInputStream is = new ByteArrayInputStream(
- text.getBytes(charset));
- file.setContents(is, IFile.KEEP_HISTORY, null);
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (Exception e) {
- //TODO handle better
- throw new RuntimeException(
- "Cannot set content on properties file.", e); //$NON-NLS-1$
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource
- * #getSource()
- */
- public Object getSource() {
- return file;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- return file.getFullPath().toString();
- }
-
- /**
- * Called before this object will be discarded.
- * If this object was listening to file changes: then unsubscribe it.
- */
- public void dispose() {
- if (this.listenerRegistry != null) {
- this.listenerRegistry.unsubscribe(this.fileListener);
- }
- }
-
-
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesReadOnlyResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesReadOnlyResource.java
deleted file mode 100644
index 48bb7e9c..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/PropertiesReadOnlyResource.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.resource;
-
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-
-
-/**
- * Properties file, where the underlying storage is unknown and read-only.
- * This is the case when properties are located inside a jar or the target platform.
- * This resource is not suitable to build the editor itself.
- * It is used during the build only.
- *
- * @author Pascal Essiembre
- * @author Hugues Malphettes
- * @see PropertiesFileResource
- */
-public class PropertiesReadOnlyResource extends AbstractPropertiesResource{
-
- private final String contents;
- private final String resourceLocationLabel;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param content The contents of the properties
- * @param resourceLocationLabel The label that explains to the user where
- * those properties are defined.
- */
- public PropertiesReadOnlyResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- String contents,
- String resourceLocationLabel) {
- super(locale, serializer, deserializer);
- this.contents = contents;
- this.resourceLocationLabel = resourceLocationLabel;
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.AbstractPropertiesResource
- * #getText()
- */
- public String getText() {
- return contents;
- }
-
- /**
- * Unsupported here. This is read-only.
- * @see org.eclipse.babel.core.message.resource.TextResource#setText(
- * java.lang.String)
- */
- public void setText(String text) {
- throw new UnsupportedOperationException(getResourceLocationLabel()
- + " resource is read-only"); //$NON-NLS-1$ (just an error message)
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource
- * #getSource()
- */
- public Object getSource() {
- return this;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- return resourceLocationLabel;
- }
-
- /**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this object.
- */
- public void dispose() {
- //nothing to do.
- }
-}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java
new file mode 100644
index 00000000..95512f4c
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.resource.internal;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.IMessagesResourceChangeListener;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+
+/**
+ * Base implementation of a {@link IMessagesResource} bound to a locale
+ * and providing ways to add and remove {@link IMessagesResourceChangeListener}
+ * instances.
+ * @author Pascal Essiembre
+ */
+public abstract class AbstractMessagesResource implements IMessagesResource {
+
+ private Locale locale;
+ private List<IMessagesResourceChangeListener> listeners = new ArrayList<IMessagesResourceChangeListener>();
+
+ /**
+ * Constructor.
+ * @param locale bound locale
+ */
+ public AbstractMessagesResource(Locale locale) {
+ super();
+ this.locale = locale;
+ }
+
+ /**
+ * @see org.eclipse.babel.core.bundle.resource.IMessagesResource#getLocale()
+ */
+ public Locale getLocale() {
+ return locale;
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#
+ * addMessagesResourceChangeListener(
+ * org.eclipse.babel.core.message.resource
+ * .IMessagesResourceChangeListener)
+ */
+ public void addMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener) {
+ listeners.add(0, listener);
+ }
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#
+ * removeMessagesResourceChangeListener(
+ * org.eclipse.babel.core.message.resource.IMessagesResourceChangeListener)
+ */
+ public void removeMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener) {
+ listeners.remove(listener);
+ }
+
+ /**
+ * Fires notification that a {@link IMessagesResource} changed.
+ * @param resource {@link IMessagesResource}
+ */
+ protected void fireResourceChange(IMessagesResource resource) {
+ for (IMessagesResourceChangeListener listener : listeners) {
+ listener.resourceChanged(resource);
+ }
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java
new file mode 100644
index 00000000..5b6b9fe0
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.resource.internal;
+
+import java.util.Locale;
+import java.util.Properties;
+
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+
+
+/**
+ * Based implementation of a text-based messages resource following
+ * the conventions defined by the Java {@link Properties} class for
+ * serialization and deserialization.
+ * @author Pascal Essiembre
+ */
+public abstract class AbstractPropertiesResource
+ extends AbstractMessagesResource {
+
+ private PropertiesDeserializer deserializer;
+ private PropertiesSerializer serializer;
+
+ /**
+ * Constructor.
+ * @param locale properties locale
+ * @param serializer properties serializer
+ * @param deserializer properties deserializer
+ */
+ public AbstractPropertiesResource(
+ Locale locale,
+ PropertiesSerializer serializer,
+ PropertiesDeserializer deserializer) {
+ super(locale);
+ this.deserializer = deserializer;
+ this.serializer = serializer;
+ //TODO initialises with configurations only...
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#serialize(
+ * org.eclipse.babel.core.message.internal.MessagesBundle)
+ */
+ public void serialize(IMessagesBundle messagesBundle) {
+ setText(serializer.serialize(messagesBundle));
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource
+ * #deserialize(org.eclipse.babel.core.message.internal.MessagesBundle)
+ */
+ public void deserialize(IMessagesBundle messagesBundle) {
+ deserializer.deserialize(messagesBundle, getText());
+ }
+
+ /**
+ * Gets the {@link Properties}-like formated text.
+ * @return formated text
+ */
+ protected abstract String getText();
+ /**
+ * Sets the {@link Properties}-like formated text.
+ * @param text formated text
+ */
+ protected abstract void setText(String text);
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java
new file mode 100644
index 00000000..bff9a1b7
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java
@@ -0,0 +1,192 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.resource.internal;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+import org.eclipse.babel.core.util.FileChangeListener;
+import org.eclipse.babel.core.util.FileMonitor;
+
+/**
+ * Properties file, where the underlying storage is a regular {@link File}. For
+ * files referenced through Eclipse workspace, implementors should use
+ * {@link PropertiesIFileResource}.
+ *
+ * @author Pascal Essiembre
+ * @see PropertiesIFileResource
+ */
+public class PropertiesFileResource extends AbstractPropertiesResource {
+
+ private File file;
+
+ private FileChangeListenerImpl fileChangeListener;
+
+ /**
+ * Constructor.
+ *
+ * @param locale
+ * the resource locale
+ * @param serializer
+ * resource serializer
+ * @param deserializer
+ * resource deserializer
+ * @param file
+ * the underlying file
+ * @throws FileNotFoundException
+ */
+ public PropertiesFileResource(Locale locale,
+ PropertiesSerializer serializer,
+ PropertiesDeserializer deserializer, File file)
+ throws FileNotFoundException {
+ super(locale, serializer, deserializer);
+ this.file = file;
+ this.fileChangeListener = new FileChangeListenerImpl();
+
+ FileMonitor.getInstance().addFileChangeListener(
+ this.fileChangeListener, file, 2000); // TODO make file scan
+ // delay configurable
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource
+ * #getText()
+ */
+ @Override
+ public String getText() {
+ FileReader inputStream = null;
+ StringWriter outputStream = null;
+ try {
+ if (!file.exists()) {
+ return "";
+ }
+ inputStream = new FileReader(file);
+ outputStream = new StringWriter();
+ int c;
+ while ((c = inputStream.read()) != -1) {
+ outputStream.write(c);
+ }
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException(
+ "Cannot get properties file text. Handle better.", e);
+ } finally {
+ closeReader(inputStream);
+ closeWriter(outputStream);
+ }
+ return outputStream.toString();
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource
+ * #setText(java.lang.String)
+ */
+ @Override
+ public void setText(String content) {
+ StringReader inputStream = null;
+ FileWriter outputStream = null;
+ try {
+ inputStream = new StringReader(content);
+ outputStream = new FileWriter(file);
+ int c;
+ while ((c = inputStream.read()) != -1) {
+ outputStream.write(c);
+ }
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException(
+ "Cannot get properties file text. Handle better.", e);
+ } finally {
+ closeReader(inputStream);
+ closeWriter(outputStream);
+
+ // IFile file =
+ // ResourcesPlugin.getWorkspace().getRoot().getFileForLocation( new
+ // Path(getResourceLocationLabel()));
+ // try {
+ // file.refreshLocal(IResource.DEPTH_ZERO, null);
+ // } catch (CoreException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ }
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource
+ * .IMessagesResource#getSource()
+ */
+ @Override
+ public Object getSource() {
+ return file;
+ }
+
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ @Override
+ public String getResourceLocationLabel() {
+ return file.getAbsolutePath();
+ }
+
+ // TODO move to util class for convinience???
+ private void closeWriter(Writer writer) {
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException("Cannot close writer stream.", e);
+ }
+ }
+ }
+
+ // TODO move to util class for convinience???
+ public void closeReader(Reader reader) {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ // TODO handle better.
+ throw new RuntimeException("Cannot close reader.", e);
+ }
+ }
+ }
+
+ /**
+ * Called before this object will be discarded. Nothing to do: we were not
+ * listening to changes to this file.
+ */
+ @Override
+ public void dispose() {
+ FileMonitor.getInstance().removeFileChangeListener(
+ this.fileChangeListener, file);
+ }
+
+ private class FileChangeListenerImpl implements FileChangeListener {
+
+ @Override
+ public void fileChanged(final File changedFile) {
+ fireResourceChange(PropertiesFileResource.this);
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java
new file mode 100644
index 00000000..68b6e6ce
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java
@@ -0,0 +1,153 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.resource.internal;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.internal.AbstractIFileChangeListener;
+import org.eclipse.babel.core.message.internal.AbstractIFileChangeListener.IFileChangeListenerRegistry;
+import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.runtime.CoreException;
+
+
+/**
+ * Properties file, where the underlying storage is a {@link IFile}.
+ * When dealing with {@link File} as opposed to {@link IFile},
+ * implementors should use {@link PropertiesFileResource}.
+ *
+ * @author Pascal Essiembre
+ * @see PropertiesFileResource
+ */
+public class PropertiesIFileResource extends AbstractPropertiesResource {
+
+ private final IFile file;
+
+ private final AbstractIFileChangeListener fileListener;
+ private final IFileChangeListenerRegistry listenerRegistry;
+
+ /**
+ * Constructor.
+ * @param locale the resource locale
+ * @param serializer resource serializer
+ * @param deserializer resource deserializer
+ * @param file the underlying {@link IFile}
+ * @param listenerRegistry It is the MessageEditorPlugin.
+ * Or null if we don't care for file changes.
+ * We could replace it by an activator in this plugin.
+ */
+ public PropertiesIFileResource(
+ Locale locale,
+ PropertiesSerializer serializer,
+ PropertiesDeserializer deserializer,
+ IFile file, IFileChangeListenerRegistry listenerRegistry) {
+ super(locale, serializer, deserializer);
+ this.file = file;
+ this.listenerRegistry = listenerRegistry;
+
+ //[hugues] FIXME: this object is built at the beginning
+ //of a build (no message editor)
+ //it is disposed of at the end of the build.
+ //during a build files are not changed.
+ //so it is I believe never called.
+ if (this.listenerRegistry != null) {
+ IResourceChangeListener rcl =
+ new IResourceChangeListener() {
+ public void resourceChanged(IResourceChangeEvent event) {
+ //no need to check: it is always the case as this
+ //is subscribed for a particular file.
+// if (event.getResource() != null
+// && PropertiesIFileResource.this.file.equals(event.getResource())) {
+ fireResourceChange(PropertiesIFileResource.this);
+// }
+ }
+ };
+ fileListener = AbstractIFileChangeListener
+ .wrapResourceChangeListener(rcl, file);
+ this.listenerRegistry.subscribe(fileListener);
+ } else {
+ fileListener = null;
+ }
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource
+ * #getText()
+ */
+ public String getText() {
+ try {
+ file.refreshLocal(IResource.DEPTH_INFINITE, null);
+ InputStream is = file.getContents();
+ int byteCount = is.available();
+ byte[] b = new byte[byteCount];
+ is.read(b);
+ String content = new String(b, file.getCharset());
+ return content;
+ } catch (IOException e) {
+ throw new RuntimeException(e); //TODO handle better
+ } catch (CoreException e) {
+ throw new RuntimeException(e); //TODO handle better
+ }
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText(
+ * java.lang.String)
+ */
+ public void setText(String text) {
+ try {
+ String charset = file.getCharset();
+ ByteArrayInputStream is = new ByteArrayInputStream(
+ text.getBytes(charset));
+ file.setContents(is, IFile.KEEP_HISTORY, null);
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ } catch (Exception e) {
+ //TODO handle better
+ throw new RuntimeException(
+ "Cannot set content on properties file.", e); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource
+ * #getSource()
+ */
+ public Object getSource() {
+ return file;
+ }
+
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ public String getResourceLocationLabel() {
+ return file.getFullPath().toString();
+ }
+
+ /**
+ * Called before this object will be discarded.
+ * If this object was listening to file changes: then unsubscribe it.
+ */
+ public void dispose() {
+ if (this.listenerRegistry != null) {
+ this.listenerRegistry.unsubscribe(this.fileListener);
+ }
+ }
+
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java
new file mode 100644
index 00000000..559aa1f1
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java
@@ -0,0 +1,94 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.resource.internal;
+
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+
+
+/**
+ * Properties file, where the underlying storage is unknown and read-only.
+ * This is the case when properties are located inside a jar or the target platform.
+ * This resource is not suitable to build the editor itself.
+ * It is used during the build only.
+ *
+ * @author Pascal Essiembre
+ * @author Hugues Malphettes
+ * @see PropertiesFileResource
+ */
+public class PropertiesReadOnlyResource extends AbstractPropertiesResource{
+
+ private final String contents;
+ private final String resourceLocationLabel;
+
+ /**
+ * Constructor.
+ * @param locale the resource locale
+ * @param serializer resource serializer
+ * @param deserializer resource deserializer
+ * @param content The contents of the properties
+ * @param resourceLocationLabel The label that explains to the user where
+ * those properties are defined.
+ */
+ public PropertiesReadOnlyResource(
+ Locale locale,
+ PropertiesSerializer serializer,
+ PropertiesDeserializer deserializer,
+ String contents,
+ String resourceLocationLabel) {
+ super(locale, serializer, deserializer);
+ this.contents = contents;
+ this.resourceLocationLabel = resourceLocationLabel;
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource
+ * #getText()
+ */
+ public String getText() {
+ return contents;
+ }
+
+ /**
+ * Unsupported here. This is read-only.
+ * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText(
+ * java.lang.String)
+ */
+ public void setText(String text) {
+ throw new UnsupportedOperationException(getResourceLocationLabel()
+ + " resource is read-only"); //$NON-NLS-1$ (just an error message)
+ }
+
+ /**
+ * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource
+ * #getSource()
+ */
+ public Object getSource() {
+ return this;
+ }
+
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ public String getResourceLocationLabel() {
+ return resourceLocationLabel;
+ }
+
+ /**
+ * Called before this object will be discarded.
+ * Nothing to do: we were not listening to changes to this object.
+ */
+ public void dispose() {
+ //nothing to do.
+ }
+}
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 6c4e23e3..c5eaee78 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,20 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
package org.eclipse.babel.core.message.resource.ser;
+/**
+ * Interface for the deserialization process.
+ *
+ * @author Alexej Strelzow
+ */
public interface IPropertiesDeserializerConfig {
/**
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 b42c6ac4..c3f77ed4 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,20 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
package org.eclipse.babel.core.message.resource.ser;
+/**
+ * Interface for the serialization process.
+ *
+ * @author Alexej Strelzow
+ */
public interface IPropertiesSerializerConfig {
/** New Line Type: Default. */
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java
index 5257413f..eed16cd2 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java
@@ -16,11 +16,11 @@
import java.util.Locale;
import java.util.Properties;
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.MessagesBundle;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.internal.Message;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
/**
* Class responsible for deserializing {@link Properties}-like text into
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java
index e5766671..0f134301 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java
@@ -13,9 +13,9 @@
import java.util.Arrays;
import java.util.Properties;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
/**
* Class responsible for serializing a {@link MessagesBundle} into
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
index 3e455aa9..3d1c5511 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
@@ -7,14 +7,15 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - TapJI integration, messagesBundleId
******************************************************************************/
package org.eclipse.babel.core.message.strategy;
import java.util.Locale;
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
+import org.eclipse.babel.core.message.internal.MessageException;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
index 3fc96493..2a2f8db4 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
@@ -7,6 +7,7 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - TapJI integration, messagesBundleId
******************************************************************************/
package org.eclipse.babel.core.message.strategy;
@@ -16,22 +17,19 @@
import java.util.Collection;
import java.util.Locale;
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesFileResource;
+import org.eclipse.babel.core.message.internal.MessageException;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.resource.internal.PropertiesFileResource;
import org.eclipse.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
import org.eclipse.babel.core.message.resource.ser.IPropertiesSerializerConfig;
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
import org.eclipse.babel.core.util.BabelUtils;
+import org.eclipse.babel.core.util.NameUtils;
import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
/**
@@ -169,27 +167,7 @@ public String createMessagesBundleId() {
IFile f = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(relativeFilePath);
- return getResourceBundleId(f);
- }
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
- public 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$
+ return NameUtils.getResourceBundleId(f);
}
public String getProjectName() {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java
deleted file mode 100644
index 987a93e7..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.tree;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.MessagesBundleGroupAdapter;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-
-
-/**
- * Hierarchical representation of all keys making up a
- * {@link MessagesBundleGroup}.
- *
- * Key tree model, using a delimiter to separate key sections
- * into nodes. For instance, a dot (.) delimiter on the following key...<p>
- * <code>person.address.street</code><P>
- * ... will result in the following node hierarchy:<p>
- * <pre>
- * person
- * address
- * street
- * </pre>
- *
- * @author Pascal Essiembre
- */
-public class AbstractKeyTreeModel implements IAbstractKeyTreeModel {
-
- private List<IKeyTreeModelListener> listeners = new ArrayList<IKeyTreeModelListener>();
- private Comparator<IKeyTreeNode> comparator;
-
- private KeyTreeNode rootNode = new KeyTreeNode(null, null, null, null);
-
- private String delimiter;
- private MessagesBundleGroup messagesBundleGroup;
-
- protected static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[]{};
-
- /**
- * Defaults to ".".
- */
- public AbstractKeyTreeModel(MessagesBundleGroup messagesBundleGroup) {
- this(messagesBundleGroup, "."); //$NON-NLS-1$
- }
-
- /**
- * Constructor.
- * @param messagesBundleGroup {@link MessagesBundleGroup} instance
- * @param delimiter key section delimiter
- */
- public AbstractKeyTreeModel(
- MessagesBundleGroup messagesBundleGroup, String delimiter) {
- super();
- this.messagesBundleGroup = messagesBundleGroup;
- this.delimiter = delimiter;
- createTree();
-
- messagesBundleGroup.addMessagesBundleGroupListener(
- new MessagesBundleGroupAdapter() {
- public void keyAdded(String key) {
- createTreeNodes(key);
- }
- public void keyRemoved(String key) {
- removeTreeNodes(key);
- }
- });
- }
-
- /**
- * Adds a key tree model listener.
- * @param listener key tree model listener
- */
- public void addKeyTreeModelListener(IKeyTreeModelListener listener) {
- listeners.add(0, listener);
- }
-
- /**
- * Removes a key tree model listener.
- * @param listener key tree model listener
- */
- public void removeKeyTreeModelListener(IKeyTreeModelListener listener) {
- listeners.remove(listener);
- }
-
- /**
- * Notify all listeners that a node was added.
- * @param node added node
- */
- protected void fireNodeAdded(KeyTreeNode node) {
- for (IKeyTreeModelListener listener : listeners) {
- listener.nodeAdded(node);
- }
- }
- /**
- * Notify all listeners that a node was removed.
- * @param node removed node
- */
- protected void fireNodeRemoved(KeyTreeNode node) {
- for (IKeyTreeModelListener listener : listeners) {
- listener.nodeRemoved(node);
- }
- }
-
- /**
- * Gets all nodes on a branch, starting (and including) with parent node.
- * This has the same effect of calling <code>getChildren(KeyTreeNode)</code>
- * recursively on all children.
- * @param parentNode root of a branch
- * @return all nodes on a branch
- */
- // TODO inline and remove this method.
- public KeyTreeNode[] getBranch(KeyTreeNode parentNode) {
- return parentNode.getBranch().toArray(new KeyTreeNode[]{});
- }
-
- /**
- * Accepts the visitor, visiting the given node argument, along with all
- * its children. Passing a <code>null</code> node will
- * walk the entire tree.
- * @param visitor the object to visit
- * @param node the starting key tree node
- */
- public void accept(IKeyTreeVisitor visitor, IKeyTreeNode node) {
- if (node == null) {
- return;
- }
-
- if (node != null) {
- visitor.visitKeyTreeNode(node);
- }
- IKeyTreeNode[] nodes = getChildren(node);
- for (int i = 0; i < nodes.length; i++) {
- accept(visitor, nodes[i]);
- }
- }
-
- /**
- * Gets the child nodes of a given key tree node.
- * @param node the node from which to get children
- * @return child nodes
- */
- public IKeyTreeNode[] getChildren(IKeyTreeNode node) {
- if (node == null) {
- return null;
- }
-
- IKeyTreeNode[] nodes = node.getChildren();
- if (getComparator() != null) {
- Arrays.sort(nodes, getComparator());
- }
- return nodes;
- }
-
- /**
- * Gets the comparator.
- * @return the comparator
- */
- public Comparator<IKeyTreeNode> getComparator() {
- return comparator;
- }
-
- /**
- * Sets the node comparator for sorting sibling nodes.
- * @param comparator node comparator
- */
- public void setComparator(Comparator<IKeyTreeNode> comparator) {
- this.comparator = comparator;
- }
-
- /**
- * Depth first for the first leaf node that is not filtered.
- * It makes the entire branch not not filtered
- *
- * @param filter The leaf filter.
- * @param node
- * @return true if this node or one of its descendant is in the filter (ie is displayed)
- */
- public boolean isBranchFiltered(IKeyTreeNodeLeafFilter filter, IKeyTreeNode node) {
- if (!((KeyTreeNode)node).hasChildren()) {
- return filter.isFilteredLeaf(node);
- } else {
- //depth first:
- for (IKeyTreeNode childNode : ((KeyTreeNode)node).getChildrenInternal()) {
- if (isBranchFiltered(filter, childNode)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Gets the delimiter.
- * @return delimiter
- */
- public String getDelimiter() {
- return delimiter;
- }
- /**
- * Sets the delimiter.
- * @param delimiter delimiter
- */
- public void setDelimiter(String delimiter) {
- this.delimiter = delimiter;
- }
-
- /**
- * Gets the key tree root nodes.
- * @return key tree root nodes
- */
- public IKeyTreeNode[] getRootNodes() {
- return getChildren(rootNode);
- }
-
- public IKeyTreeNode getRootNode() {
- return rootNode;
- }
-
- /**
- * Gets the parent node of the given node.
- * @param node node from which to get parent
- * @return parent node
- */
- public IKeyTreeNode getParent(IKeyTreeNode node) {
- return node.getParent();
- }
-
- /**
- * Gets the messages bundle group that this key tree represents.
- * @return messages bundle group
- */
- public MessagesBundleGroup getMessagesBundleGroup() {
- //TODO consider moving this method (and part of constructor) to super
- return messagesBundleGroup;
- }
-
- private void createTree() {
- rootNode = new KeyTreeNode(null, null, null, messagesBundleGroup);
- String[] keys = messagesBundleGroup.getMessageKeys();
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
- createTreeNodes(key);
- }
- }
-
- private void createTreeNodes(String bundleKey) {
- StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
- KeyTreeNode node = rootNode;
- String bundleKeyPart = ""; //$NON-NLS-1$
- while (tokens.hasMoreTokens()) {
- String name = tokens.nextToken();
- bundleKeyPart += name;
- KeyTreeNode child = (KeyTreeNode) node.getChild(name);
- if (child == null) {
- child = new KeyTreeNode(node, name, bundleKeyPart, messagesBundleGroup);
- fireNodeAdded(child);
- }
- bundleKeyPart += delimiter;
- node = child;
- }
- node.setUsedAsKey();
- }
- private void removeTreeNodes(String bundleKey) {
- if (bundleKey == null) {
- return;
- }
- StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
- KeyTreeNode node = rootNode;
- while (tokens.hasMoreTokens()) {
- String name = tokens.nextToken();
- node = (KeyTreeNode) node.getChild(name);
- if (node == null) {
- System.err.println(
- "No RegEx node matching bundleKey to remove"); //$NON-NLS-1$
- return;
- }
- }
- KeyTreeNode parentNode = (KeyTreeNode) node.getParent();
- parentNode.removeChild(node);
- fireNodeRemoved(node);
- while (parentNode != rootNode) {
- if (!parentNode.hasChildren() && !messagesBundleGroup.isMessageKey(
- parentNode.getMessageKey())) {
- ((KeyTreeNode)parentNode.getParent()).removeChild(parentNode);
- fireNodeRemoved(parentNode);
- }
- parentNode = (KeyTreeNode)parentNode.getParent();
- }
- }
-
-
- public interface IKeyTreeNodeLeafFilter {
- /**
- * @param leafNode A leaf node. Must not be called if the node has children
- * @return true if this node should be filtered.
- */
- boolean isFilteredLeaf(IKeyTreeNode leafNode);
- }
-
- public IKeyTreeNode getChild(String key) {
- return returnNodeWithKey(key, rootNode);
- }
-
- private IKeyTreeNode returnNodeWithKey(String key, IKeyTreeNode node) {
-
- if (!key.equals(node.getMessageKey())) {
- for (IKeyTreeNode n : node.getChildren()) {
- IKeyTreeNode returnNode = returnNodeWithKey(key, n);
- if (returnNode == null) {
- continue;
- } else {
- return returnNode;
- }
- }
- } else {
- return node;
- }
- return null;
- }
-}
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
new file mode 100644
index 00000000..8e87ae22
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.core.message.tree;
+
+
+public interface IAbstractKeyTreeModel {
+
+ IKeyTreeNode[] getChildren(IKeyTreeNode node);
+
+ IKeyTreeNode getChild(String key);
+
+ IKeyTreeNode[] getRootNodes();
+
+ IKeyTreeNode getRootNode();
+
+ IKeyTreeNode getParent(IKeyTreeNode node);
+
+ void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeModelListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeModelListener.java
deleted file mode 100644
index 4a823fe0..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeModelListener.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.tree;
-
-/**
- * Listener notified of changes to a {@link IKeyTreeModel}.
- * @author Pascal Essiembre
- */
-public interface IKeyTreeModelListener {
-
- /**
- * Invoked when a key tree node is added.
- * @param node key tree node
- */
- void nodeAdded(KeyTreeNode node);
- /**
- * Invoked when a key tree node is remove.
- * @param node key tree node
- */
- void nodeRemoved(KeyTreeNode node);
-}
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
new file mode 100644
index 00000000..f774382b
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.core.message.tree;
+
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+
+public interface IKeyTreeNode {
+
+ /**
+ * Returns the key of the corresponding Resource-Bundle entry.
+ *
+ * @return The key of the Resource-Bundle entry
+ */
+ String getMessageKey();
+
+ /**
+ * Returns the set of Resource-Bundle entries of the next deeper hierarchy
+ * level that share the represented entry as their common parent.
+ *
+ * @return The direct child Resource-Bundle entries
+ */
+ IKeyTreeNode[] getChildren();
+
+ /**
+ * The represented Resource-Bundle entry's id without the prefix defined by
+ * the entry's parent.
+ *
+ * @return The Resource-Bundle entry's display name.
+ */
+ String getName();
+
+ /**
+ * Returns the set of Resource-Bundle entries from all deeper hierarchy
+ * levels that share the represented entry as their common parent.
+ *
+ * @return All child Resource-Bundle entries
+ */
+ // Collection<? extends IKeyTreeItem> getNestedChildren();
+
+ /**
+ * Returns whether this Resource-Bundle entry is visible under the given
+ * filter expression.
+ *
+ * @param filter
+ * The filter expression
+ * @return True if the filter expression matches the represented
+ * Resource-Bundle entry
+ */
+ // boolean applyFilter(String filter);
+
+ /**
+ * The Resource-Bundle entries parent.
+ *
+ * @return The parent Resource-Bundle entry
+ */
+ IKeyTreeNode getParent();
+
+ /**
+ * The Resource-Bundles key representation.
+ *
+ * @return The Resource-Bundle reference, if known
+ */
+ IMessagesBundleGroup getMessagesBundleGroup();
+
+ boolean isUsedAsKey();
+
+ void setParent(IKeyTreeNode parentNode);
+
+ void addChild(IKeyTreeNode childNode);
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java
new file mode 100644
index 00000000..ac7a5355
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.tree;
+
+
+/**
+ * Objects implementing this interface can act as a visitor to a
+ * <code>IKeyTreeModel</code>.
+ *
+ * @author Pascal Essiembre ([email protected])
+ */
+public interface IKeyTreeVisitor {
+ /**
+ * Visits a key tree node.
+ *
+ * @param item
+ * key tree node to visit
+ */
+ void visitKeyTreeNode(IKeyTreeNode node);
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/KeyTreeNode.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/KeyTreeNode.java
deleted file mode 100644
index 183551bf..00000000
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/KeyTreeNode.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.core.message.tree;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Class representing a node in the tree of keys.
- *
- * @author Pascal Essiembre
- */
-public class KeyTreeNode implements Comparable<KeyTreeNode>, IKeyTreeNode {
-
- public static final KeyTreeNode[] EMPTY_KEY_TREE_NODES =
- new KeyTreeNode[] {};
-
- /**
- * the parent node, if any, which will have a <code>messageKey</code> field
- * the same as this object but with the last component (following the
- * last period) removed
- */
- private IKeyTreeNode parent;
-
- /**
- * the name, being the part of the full key that follows the last period
- */
- private final String name;
-
- /**
- * the full key, being a sequence of names separated by periods with the
- * last name being the name given by the <code>name</code> field of this
- * object
- */
- private String messageKey;
-
- private final Map<String, IKeyTreeNode> children = new TreeMap<String, IKeyTreeNode>();
-
- private boolean usedAsKey = false;
-
- private IMessagesBundleGroup messagesBundleGroup;
-
- /**
- * Constructor.
- * @param parent parent node
- * @param name node name
- * @param messageKey messages bundle key
- */
- public KeyTreeNode(
- IKeyTreeNode parent, String name, String messageKey, IMessagesBundleGroup messagesBundleGroup) {
- super();
- this.parent = parent;
- this.name = name;
- this.messageKey = messageKey;
- if (parent != null) {
- parent.addChild(this);
- }
- this.messagesBundleGroup = messagesBundleGroup;
- }
-
- /**
- * @return the name, being the part of the full key that follows the last period
- */
- public String getName() {
- return name;
- }
-
- /**
- * @return the parent node, if any, which will have a <code>messageKey</code> field
- * the same as this object but with the last component (following the
- * last period) removed
- */
- public IKeyTreeNode getParent() {
- return parent;
- }
-
- /**
- * @return the full key, being a sequence of names separated by periods with the
- * last name being the name given by the <code>name</code> field of this
- * object
- */
- public String getMessageKey() {
- return messageKey;
- }
-
- /**
- * Gets all notes from root to this node.
- * @return all notes from root to this node
- */
- /*default*/ IKeyTreeNode[] getPath() {
- List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>();
- IKeyTreeNode node = this;
- while (node != null && node.getName() != null) {
- nodes.add(0, node);
- node = node.getParent();
- }
- return nodes.toArray(EMPTY_KEY_TREE_NODES);
- }
-
- public IKeyTreeNode[] getChildren() {
- return children.values().toArray(EMPTY_KEY_TREE_NODES);
- }
- /*default*/ boolean hasChildren() {
- return !children.isEmpty();
- }
- public IKeyTreeNode getChild(String childName) {
- return children.get(childName);
- }
-
- /**
- * @return the children without creating a new object
- */
- Collection<IKeyTreeNode> getChildrenInternal() {
- return children.values();
- }
-
- /**
- * @see java.lang.Comparable#compareTo(java.lang.Object)
- */
- public int compareTo(KeyTreeNode node) {
- // TODO this is wrong. For example, menu.label and textbox.label are indicated as equal,
- // which means they overwrite each other in the tree set!!!
- if (parent == null && node.parent != null) {
- return -1;
- }
- if (parent != null && node.parent == null) {
- return 1;
- }
- return name.compareTo(node.name);
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof KeyTreeNode)) {
- return false;
- }
- KeyTreeNode node = (KeyTreeNode) obj;
- return BabelUtils.equals(name, node.name)
- && BabelUtils.equals(parent, node.parent);
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return messageKey;
-// return "KeyTreeNode=[[parent=" + parent //$NON-NLS-1$
-// + "][name=" + name //$NON-NLS-1$
-// + "][messageKey=" + messageKey + "]]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void addChild(IKeyTreeNode childNode) {
- children.put(childNode.getName(), childNode);
- }
- public void removeChild(KeyTreeNode childNode) {
- children.remove(childNode.getName());
- //TODO remove parent on child node?
- }
-
- // TODO: remove this, or simplify it using method getDescendants
- public Collection<KeyTreeNode> getBranch() {
- Collection<KeyTreeNode> childNodes = new ArrayList<KeyTreeNode>();
- childNodes.add(this);
- for (IKeyTreeNode childNode : this.getChildren()) {
- childNodes.addAll(((KeyTreeNode)childNode).getBranch());
- }
- return childNodes;
- }
-
- public Collection<IKeyTreeNode> getDescendants() {
- Collection<IKeyTreeNode> descendants = new ArrayList<IKeyTreeNode>();
- for (IKeyTreeNode child : children.values()) {
- descendants.add(child);
- descendants.addAll(((KeyTreeNode)child).getDescendants());
- }
- return descendants;
- }
-
- /**
- * Marks this node as representing an actual key.
- * <P>
- * For example, if the bundle contains two keys:
- * <UL>
- * <LI>foo.bar</LI>
- * <LI>foo.bar.tooltip</LI>
- * </UL>
- * This will create three nodes, foo, which has a child
- * node called bar, which has a child node called tooltip.
- * However foo is not an actual key but is only a parent node.
- * foo.bar is an actual key even though it is also a parent node.
- */
- public void setUsedAsKey() {
- usedAsKey = true;
- }
-
- public boolean isUsedAsKey() {
- return usedAsKey;
- }
-
- public IMessagesBundleGroup getMessagesBundleGroup() {
- return this.messagesBundleGroup;
- }
-
- public void setParent(IKeyTreeNode parentNode) {
- this.parent = parentNode;
- }
-
-}
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
new file mode 100644
index 00000000..67049e74
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.tree;
+
+/**
+ * Enum for two tree types. If a tree has the type {@link #Tree}, then it
+ * is displayed as tree. E.g. following key is given: parent.child.grandchild
+ * result:
+ * <pre>
+ * parent
+ * child
+ * grandchild
+ * </pre>
+ * If it is {@link #Flat}, it will be displayed as parent.child.grandchild.
+ *
+ * @author Alexej Strelzow
+ */
+public enum TreeType {
+ Tree, Flat
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java
new file mode 100644
index 00000000..ed4fceae
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java
@@ -0,0 +1,336 @@
+/*******************************************************************************
+ * 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
+ * Matthias Lettmayer - fixed bug in returnNodeWithKey()
+ ******************************************************************************/
+package org.eclipse.babel.core.message.tree.internal;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroupAdapter;
+import org.eclipse.babel.core.message.tree.IAbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
+
+
+/**
+ * Hierarchical representation of all keys making up a
+ * {@link MessagesBundleGroup}.
+ *
+ * Key tree model, using a delimiter to separate key sections
+ * into nodes. For instance, a dot (.) delimiter on the following key...<p>
+ * <code>person.address.street</code><P>
+ * ... will result in the following node hierarchy:<p>
+ * <pre>
+ * person
+ * address
+ * street
+ * </pre>
+ *
+ * @author Pascal Essiembre
+ */
+public class AbstractKeyTreeModel implements IAbstractKeyTreeModel {
+
+ private List<IKeyTreeModelListener> listeners = new ArrayList<IKeyTreeModelListener>();
+ private Comparator<IKeyTreeNode> comparator;
+
+ private KeyTreeNode rootNode = new KeyTreeNode(null, null, null, null);
+
+ private String delimiter;
+ private MessagesBundleGroup messagesBundleGroup;
+
+ protected static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[]{};
+
+ /**
+ * Defaults to ".".
+ */
+ public AbstractKeyTreeModel(MessagesBundleGroup messagesBundleGroup) {
+ this(messagesBundleGroup, "."); //$NON-NLS-1$
+ }
+
+ /**
+ * Constructor.
+ * @param messagesBundleGroup {@link MessagesBundleGroup} instance
+ * @param delimiter key section delimiter
+ */
+ public AbstractKeyTreeModel(
+ MessagesBundleGroup messagesBundleGroup, String delimiter) {
+ super();
+ this.messagesBundleGroup = messagesBundleGroup;
+ this.delimiter = delimiter;
+ createTree();
+
+ messagesBundleGroup.addMessagesBundleGroupListener(
+ new MessagesBundleGroupAdapter() {
+ public void keyAdded(String key) {
+ createTreeNodes(key);
+ }
+ public void keyRemoved(String key) {
+ removeTreeNodes(key);
+ }
+ });
+ }
+
+ /**
+ * Adds a key tree model listener.
+ * @param listener key tree model listener
+ */
+ public void addKeyTreeModelListener(IKeyTreeModelListener listener) {
+ listeners.add(0, listener);
+ }
+
+ /**
+ * Removes a key tree model listener.
+ * @param listener key tree model listener
+ */
+ public void removeKeyTreeModelListener(IKeyTreeModelListener listener) {
+ listeners.remove(listener);
+ }
+
+ /**
+ * Notify all listeners that a node was added.
+ * @param node added node
+ */
+ protected void fireNodeAdded(KeyTreeNode node) {
+ for (IKeyTreeModelListener listener : listeners) {
+ listener.nodeAdded(node);
+ }
+ }
+ /**
+ * Notify all listeners that a node was removed.
+ * @param node removed node
+ */
+ protected void fireNodeRemoved(KeyTreeNode node) {
+ for (IKeyTreeModelListener listener : listeners) {
+ listener.nodeRemoved(node);
+ }
+ }
+
+ /**
+ * Gets all nodes on a branch, starting (and including) with parent node.
+ * This has the same effect of calling <code>getChildren(KeyTreeNode)</code>
+ * recursively on all children.
+ * @param parentNode root of a branch
+ * @return all nodes on a branch
+ */
+ // TODO inline and remove this method.
+ public KeyTreeNode[] getBranch(KeyTreeNode parentNode) {
+ return parentNode.getBranch().toArray(new KeyTreeNode[]{});
+ }
+
+ /**
+ * Accepts the visitor, visiting the given node argument, along with all
+ * its children. Passing a <code>null</code> node will
+ * walk the entire tree.
+ * @param visitor the object to visit
+ * @param node the starting key tree node
+ */
+ public void accept(IKeyTreeVisitor visitor, IKeyTreeNode node) {
+ if (node == null) {
+ return;
+ }
+
+ if (node != null) {
+ visitor.visitKeyTreeNode(node);
+ }
+ IKeyTreeNode[] nodes = getChildren(node);
+ for (int i = 0; i < nodes.length; i++) {
+ accept(visitor, nodes[i]);
+ }
+ }
+
+ /**
+ * Gets the child nodes of a given key tree node.
+ * @param node the node from which to get children
+ * @return child nodes
+ */
+ public IKeyTreeNode[] getChildren(IKeyTreeNode node) {
+ if (node == null) {
+ return null;
+ }
+
+ IKeyTreeNode[] nodes = node.getChildren();
+ if (getComparator() != null) {
+ Arrays.sort(nodes, getComparator());
+ }
+ return nodes;
+ }
+
+ /**
+ * Gets the comparator.
+ * @return the comparator
+ */
+ public Comparator<IKeyTreeNode> getComparator() {
+ return comparator;
+ }
+
+ /**
+ * Sets the node comparator for sorting sibling nodes.
+ * @param comparator node comparator
+ */
+ public void setComparator(Comparator<IKeyTreeNode> comparator) {
+ this.comparator = comparator;
+ }
+
+ /**
+ * Depth first for the first leaf node that is not filtered.
+ * It makes the entire branch not not filtered
+ *
+ * @param filter The leaf filter.
+ * @param node
+ * @return true if this node or one of its descendant is in the filter (ie is displayed)
+ */
+ public boolean isBranchFiltered(IKeyTreeNodeLeafFilter filter, IKeyTreeNode node) {
+ if (!((KeyTreeNode)node).hasChildren()) {
+ return filter.isFilteredLeaf(node);
+ } else {
+ //depth first:
+ for (IKeyTreeNode childNode : ((KeyTreeNode)node).getChildrenInternal()) {
+ if (isBranchFiltered(filter, childNode)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the delimiter.
+ * @return delimiter
+ */
+ public String getDelimiter() {
+ return delimiter;
+ }
+ /**
+ * Sets the delimiter.
+ * @param delimiter delimiter
+ */
+ public void setDelimiter(String delimiter) {
+ this.delimiter = delimiter;
+ }
+
+ /**
+ * Gets the key tree root nodes.
+ * @return key tree root nodes
+ */
+ public IKeyTreeNode[] getRootNodes() {
+ return getChildren(rootNode);
+ }
+
+ public IKeyTreeNode getRootNode() {
+ return rootNode;
+ }
+
+ /**
+ * Gets the parent node of the given node.
+ * @param node node from which to get parent
+ * @return parent node
+ */
+ public IKeyTreeNode getParent(IKeyTreeNode node) {
+ return node.getParent();
+ }
+
+ /**
+ * Gets the messages bundle group that this key tree represents.
+ * @return messages bundle group
+ */
+ public MessagesBundleGroup getMessagesBundleGroup() {
+ //TODO consider moving this method (and part of constructor) to super
+ return messagesBundleGroup;
+ }
+
+ private void createTree() {
+ rootNode = new KeyTreeNode(null, null, null, messagesBundleGroup);
+ String[] keys = messagesBundleGroup.getMessageKeys();
+ for (int i = 0; i < keys.length; i++) {
+ String key = keys[i];
+ createTreeNodes(key);
+ }
+ }
+
+ private void createTreeNodes(String bundleKey) {
+ StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
+ KeyTreeNode node = rootNode;
+ String bundleKeyPart = ""; //$NON-NLS-1$
+ while (tokens.hasMoreTokens()) {
+ String name = tokens.nextToken();
+ bundleKeyPart += name;
+ KeyTreeNode child = (KeyTreeNode) node.getChild(name);
+ if (child == null) {
+ child = new KeyTreeNode(node, name, bundleKeyPart, messagesBundleGroup);
+ fireNodeAdded(child);
+ }
+ bundleKeyPart += delimiter;
+ node = child;
+ }
+ node.setUsedAsKey();
+ }
+ private void removeTreeNodes(String bundleKey) {
+ if (bundleKey == null) {
+ return;
+ }
+ StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
+ KeyTreeNode node = rootNode;
+ while (tokens.hasMoreTokens()) {
+ String name = tokens.nextToken();
+ node = (KeyTreeNode) node.getChild(name);
+ if (node == null) {
+ System.err.println(
+ "No RegEx node matching bundleKey to remove"); //$NON-NLS-1$
+ return;
+ }
+ }
+ KeyTreeNode parentNode = (KeyTreeNode) node.getParent();
+ parentNode.removeChild(node);
+ fireNodeRemoved(node);
+ while (parentNode != rootNode) {
+ if (!parentNode.hasChildren() && !messagesBundleGroup.isMessageKey(
+ parentNode.getMessageKey())) {
+ ((KeyTreeNode)parentNode.getParent()).removeChild(parentNode);
+ fireNodeRemoved(parentNode);
+ }
+ parentNode = (KeyTreeNode)parentNode.getParent();
+ }
+ }
+
+
+ public interface IKeyTreeNodeLeafFilter {
+ /**
+ * @param leafNode A leaf node. Must not be called if the node has children
+ * @return true if this node should be filtered.
+ */
+ boolean isFilteredLeaf(IKeyTreeNode leafNode);
+ }
+
+ public IKeyTreeNode getChild(String key) {
+ return returnNodeWithKey(key, rootNode);
+ }
+
+ private IKeyTreeNode returnNodeWithKey(String key, IKeyTreeNode node) {
+
+ if (!key.equals(node.getMessageKey())) {
+ for (IKeyTreeNode n : node.getChildren()) {
+ IKeyTreeNode returnNode = returnNodeWithKey(key, n);
+ if (returnNode == null) {
+ continue;
+ } else {
+ return returnNode;
+ }
+ }
+ } else {
+ return node;
+ }
+ return null;
+ }
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java
new file mode 100644
index 00000000..83da223f
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java
@@ -0,0 +1,29 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.tree.internal;
+
+/**
+ * Listener notified of changes to a {@link IKeyTreeModel}.
+ * @author Pascal Essiembre
+ */
+public interface IKeyTreeModelListener {
+
+ /**
+ * Invoked when a key tree node is added.
+ * @param node key tree node
+ */
+ void nodeAdded(KeyTreeNode node);
+ /**
+ * Invoked when a key tree node is remove.
+ * @param node key tree node
+ */
+ void nodeRemoved(KeyTreeNode node);
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java
new file mode 100644
index 00000000..81dbb02e
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java
@@ -0,0 +1,225 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.message.tree.internal;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.util.BabelUtils;
+
+/**
+ * Class representing a node in the tree of keys.
+ *
+ * @author Pascal Essiembre
+ */
+public class KeyTreeNode implements Comparable<KeyTreeNode>, IKeyTreeNode {
+
+ public static final KeyTreeNode[] EMPTY_KEY_TREE_NODES =
+ new KeyTreeNode[] {};
+
+ /**
+ * the parent node, if any, which will have a <code>messageKey</code> field
+ * the same as this object but with the last component (following the
+ * last period) removed
+ */
+ private IKeyTreeNode parent;
+
+ /**
+ * the name, being the part of the full key that follows the last period
+ */
+ private final String name;
+
+ /**
+ * the full key, being a sequence of names separated by periods with the
+ * last name being the name given by the <code>name</code> field of this
+ * object
+ */
+ private String messageKey;
+
+ private final Map<String, IKeyTreeNode> children = new TreeMap<String, IKeyTreeNode>();
+
+ private boolean usedAsKey = false;
+
+ private IMessagesBundleGroup messagesBundleGroup;
+
+ /**
+ * Constructor.
+ * @param parent parent node
+ * @param name node name
+ * @param messageKey messages bundle key
+ */
+ public KeyTreeNode(
+ IKeyTreeNode parent, String name, String messageKey, IMessagesBundleGroup messagesBundleGroup) {
+ super();
+ this.parent = parent;
+ this.name = name;
+ this.messageKey = messageKey;
+ if (parent != null) {
+ parent.addChild(this);
+ }
+ this.messagesBundleGroup = messagesBundleGroup;
+ }
+
+ /**
+ * @return the name, being the part of the full key that follows the last period
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @return the parent node, if any, which will have a <code>messageKey</code> field
+ * the same as this object but with the last component (following the
+ * last period) removed
+ */
+ public IKeyTreeNode getParent() {
+ return parent;
+ }
+
+ /**
+ * @return the full key, being a sequence of names separated by periods with the
+ * last name being the name given by the <code>name</code> field of this
+ * object
+ */
+ public String getMessageKey() {
+ return messageKey;
+ }
+
+ /**
+ * Gets all notes from root to this node.
+ * @return all notes from root to this node
+ */
+ /*default*/ IKeyTreeNode[] getPath() {
+ List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>();
+ IKeyTreeNode node = this;
+ while (node != null && node.getName() != null) {
+ nodes.add(0, node);
+ node = node.getParent();
+ }
+ return nodes.toArray(EMPTY_KEY_TREE_NODES);
+ }
+
+ public IKeyTreeNode[] getChildren() {
+ return children.values().toArray(EMPTY_KEY_TREE_NODES);
+ }
+ /*default*/ boolean hasChildren() {
+ return !children.isEmpty();
+ }
+ public IKeyTreeNode getChild(String childName) {
+ return children.get(childName);
+ }
+
+ /**
+ * @return the children without creating a new object
+ */
+ Collection<IKeyTreeNode> getChildrenInternal() {
+ return children.values();
+ }
+
+ /**
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ public int compareTo(KeyTreeNode node) {
+ // TODO this is wrong. For example, menu.label and textbox.label are indicated as equal,
+ // which means they overwrite each other in the tree set!!!
+ if (parent == null && node.parent != null) {
+ return -1;
+ }
+ if (parent != null && node.parent == null) {
+ return 1;
+ }
+ return name.compareTo(node.name);
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof KeyTreeNode)) {
+ return false;
+ }
+ KeyTreeNode node = (KeyTreeNode) obj;
+ return BabelUtils.equals(name, node.name)
+ && BabelUtils.equals(parent, node.parent);
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return messageKey;
+// return "KeyTreeNode=[[parent=" + parent //$NON-NLS-1$
+// + "][name=" + name //$NON-NLS-1$
+// + "][messageKey=" + messageKey + "]]"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void addChild(IKeyTreeNode childNode) {
+ children.put(childNode.getName(), childNode);
+ }
+ public void removeChild(KeyTreeNode childNode) {
+ children.remove(childNode.getName());
+ //TODO remove parent on child node?
+ }
+
+ // TODO: remove this, or simplify it using method getDescendants
+ public Collection<KeyTreeNode> getBranch() {
+ Collection<KeyTreeNode> childNodes = new ArrayList<KeyTreeNode>();
+ childNodes.add(this);
+ for (IKeyTreeNode childNode : this.getChildren()) {
+ childNodes.addAll(((KeyTreeNode)childNode).getBranch());
+ }
+ return childNodes;
+ }
+
+ public Collection<IKeyTreeNode> getDescendants() {
+ Collection<IKeyTreeNode> descendants = new ArrayList<IKeyTreeNode>();
+ for (IKeyTreeNode child : children.values()) {
+ descendants.add(child);
+ descendants.addAll(((KeyTreeNode)child).getDescendants());
+ }
+ return descendants;
+ }
+
+ /**
+ * Marks this node as representing an actual key.
+ * <P>
+ * For example, if the bundle contains two keys:
+ * <UL>
+ * <LI>foo.bar</LI>
+ * <LI>foo.bar.tooltip</LI>
+ * </UL>
+ * This will create three nodes, foo, which has a child
+ * node called bar, which has a child node called tooltip.
+ * However foo is not an actual key but is only a parent node.
+ * foo.bar is an actual key even though it is also a parent node.
+ */
+ public void setUsedAsKey() {
+ usedAsKey = true;
+ }
+
+ public boolean isUsedAsKey() {
+ return usedAsKey;
+ }
+
+ public IMessagesBundleGroup getMessagesBundleGroup() {
+ return this.messagesBundleGroup;
+ }
+
+ public void setParent(IKeyTreeNode parentNode) {
+ this.parent = parentNode;
+ }
+
+}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java
index 35ebbca6..5805c186 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java
@@ -10,7 +10,7 @@
******************************************************************************/
package org.eclipse.babel.core.message.tree.visitor;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
/**
* All purpose key testing. Use this interface to establish whether
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java
index ea59f255..724da52f 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java
@@ -13,10 +13,10 @@
import java.util.ArrayList;
import java.util.Collection;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
/**
@@ -52,9 +52,9 @@ public KeyCheckVisitor(MessagesBundleGroup messagesBundleGroup) {
}
/**
- * @see org.eclipse.babel.core.message.tree.visitor.IKeyTreeVisitor
+ * @see org.eclipse.babel.core.message.internal.tree.visitor.IKeyTreeVisitor
* #visitKeyTreeNode(
- * org.eclipse.babel.core.message.tree.KeyTreeNode)
+ * org.eclipse.babel.core.message.internal.tree.internal.KeyTreeNode)
*/
public void visitKeyTreeNode(IKeyTreeNode node) {
if (keyCheck == null) {
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java
index cfde1589..ead7a26a 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java
@@ -13,8 +13,8 @@
import java.util.ArrayList;
import java.util.List;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
/**
* Visitor for finding keys matching the given regular expression.
@@ -35,8 +35,8 @@ public NodePathRegexVisitor(String regex) {
}
/**
- * @see org.eclipse.babel.core.message.tree.visitor.IKeyTreeVisitor
- * #visitKeyTreeNode(org.eclipse.babel.core.message.tree.KeyTreeNode)
+ * @see org.eclipse.babel.core.message.internal.tree.visitor.IKeyTreeVisitor
+ * #visitKeyTreeNode(org.eclipse.babel.core.message.internal.tree.internal.KeyTreeNode)
*/
public void visitKeyTreeNode(IKeyTreeNode node) {
if (node.getMessageKey().matches(regex)) {
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
new file mode 100644
index 00000000..689b5a0b
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+
+import org.eclipse.babel.core.configuration.ConfigurationManager;
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.resource.internal.PropertiesFileResource;
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.ResourcesPlugin;
+
+/**
+ * Util class for File-I/O operations.
+ *
+ * @author Alexej Strelzow
+ */
+public class FileUtils {
+
+ public static void writeToFile(IMessagesBundle bundle) {
+ DirtyHack.setEditorModificationEnabled(false);
+
+ PropertiesSerializer ps = new PropertiesSerializer(ConfigurationManager
+ .getInstance().getSerializerConfig());
+ String editorContent = ps.serialize(bundle);
+ IFile file = getFile(bundle);
+ try {
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ file.setContents(
+ new ByteArrayInputStream(editorContent.getBytes()), false,
+ true, null);
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ DirtyHack.setEditorModificationEnabled(true);
+ }
+ }
+
+ public static IFile getFile(IMessagesBundle bundle) {
+ if (bundle.getResource() instanceof PropertiesFileResource) { // different
+ // ResourceLocationLabel
+ String path = bundle.getResource().getResourceLocationLabel(); // P:\Workspace\AST\TEST\src\messages\Messages_de.properties
+ int index = path.indexOf("src");
+ String pathBeforeSrc = path.substring(0, index - 1);
+ int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
+ String projectName = path.substring(lastIndexOf + 1, index - 1);
+ String relativeFilePath = path.substring(index, path.length());
+
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName).getFile(relativeFilePath);
+ } else {
+ String location = bundle.getResource().getResourceLocationLabel(); // /TEST/src/messages/Messages_en_IN.properties
+ String projectName = location.substring(1, location.indexOf("/", 1));
+ location = location.substring(projectName.length() + 1,
+ location.length());
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName).getFile(location);
+ }
+ }
+
+}
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
new file mode 100644
index 00000000..90ff2f52
--- /dev/null
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.core.util;
+
+import java.util.Locale;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.JavaCore;
+
+/**
+ * Contains methods, which return names/IDs or Objects by name.
+ *
+ * @author Alexej Strelzow
+ */
+public class NameUtils {
+
+
+ public static String getResourceBundleId(IResource resource) {
+ String packageFragment = "";
+
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment)
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
+
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
+ }
+
+ public 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 Locale getLocaleByName(String bundleName, String localeID) {
+ String theBundleName = bundleName;
+ if (theBundleName.contains(".")) {
+ // we entered this method with the rbID and not the name!
+ theBundleName = theBundleName.substring(theBundleName.indexOf(".") + 1);
+ }
+
+ // Check locale
+ Locale locale = null;
+ localeID = localeID.substring(0,
+ localeID.length() - "properties".length() - 1);
+ if (localeID.length() == theBundleName.length()) {
+ // default locale
+ return null;
+ } else {
+ localeID = localeID.substring(theBundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
+ break;
+ default:
+ locale = null;
+ break;
+ }
+ }
+
+ return locale;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/.classpath b/org.eclipse.babel.editor.rap.compat/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.core/.classpath
rename to org.eclipse.babel.editor.rap.compat/.classpath
diff --git a/org.eclipse.babel.editor.rap.compat/.project b/org.eclipse.babel.editor.rap.compat/.project
new file mode 100644
index 00000000..1b272699
--- /dev/null
+++ b/org.eclipse.babel.editor.rap.compat/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.editor.rap.compat</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.editor.rap.compat/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.core/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.editor.rap.compat/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/.settings/org.eclipse.pde.core.prefs b/org.eclipse.babel.editor.rap.compat/.settings/org.eclipse.pde.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.editor/.settings/org.eclipse.pde.core.prefs
rename to org.eclipse.babel.editor.rap.compat/.settings/org.eclipse.pde.core.prefs
diff --git a/org.eclipse.babel.editor.rap.compat/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.rap.compat/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..a69f2e02
--- /dev/null
+++ b/org.eclipse.babel.editor.rap.compat/META-INF/MANIFEST.MF
@@ -0,0 +1,11 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RAP Compatibility for Babel Editor
+Bundle-SymbolicName: org.eclipse.babel.editor.rap.compat
+Bundle-Version: 0.8.0.qualifier
+Bundle-Activator: org.eclipse.babel.editor.rap.compat.Activator
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Import-Package: org.osgi.framework;version="1.3.0"
+Require-Bundle: org.eclipse.rap.ui.forms;bundle-version="1.5.0",
+ org.eclipse.rap.ui;bundle-version="1.5.0"
+Export-Package: org.eclipse.babel.editor.compat
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/build.properties b/org.eclipse.babel.editor.rap.compat/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.core/build.properties
rename to org.eclipse.babel.editor.rap.compat/build.properties
diff --git a/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/compat/MyFormToolkit.java b/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/compat/MyFormToolkit.java
new file mode 100644
index 00000000..1a7ae928
--- /dev/null
+++ b/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/compat/MyFormToolkit.java
@@ -0,0 +1,16 @@
+package org.eclipse.babel.editor.compat;
+
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.forms.widgets.Form;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+
+public class MyFormToolkit extends FormToolkit {
+
+ public MyFormToolkit(Display display) {
+ super(display);
+ }
+
+ public void paintBordersFor(Composite comp) {
+ }
+}
diff --git a/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/compat/MySWT.java b/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/compat/MySWT.java
new file mode 100644
index 00000000..095390e2
--- /dev/null
+++ b/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/compat/MySWT.java
@@ -0,0 +1,27 @@
+package org.eclipse.babel.editor.compat;
+
+import org.eclipse.swt.SWT;
+
+public class MySWT extends SWT {
+
+ /**
+ * Style constant for right to left orientation (value is 1<<26).
+ * <p>
+ * When orientation is not explicitly specified, orientation is
+ * inherited. This means that children will be assigned the
+ * orientation of their parent. To override this behavior and
+ * force an orientation for a child, explicitly set the orientation
+ * of the child when that child is created.
+ * <br>Note that this is a <em>HINT</em>.
+ * </p>
+ * <p><b>Used By:</b><ul>
+ * <li><code>Control</code></li>
+ * <li><code>Menu</code></li>
+ * <li><code>GC</code></li>
+ * </ul></p>
+ *
+ * @since 2.1.2
+ */
+ public static final int RIGHT_TO_LEFT = 1 << 26;
+ //public static final int RIGHT_TO_LEFT = SWT.RIGHT;
+}
diff --git a/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/rap/compat/Activator.java b/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/rap/compat/Activator.java
new file mode 100644
index 00000000..4e5918b0
--- /dev/null
+++ b/org.eclipse.babel.editor.rap.compat/src/org/eclipse/babel/editor/rap/compat/Activator.java
@@ -0,0 +1,30 @@
+package org.eclipse.babel.editor.rap.compat;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ private static BundleContext context;
+
+ static BundleContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext bundleContext) throws Exception {
+ Activator.context = bundleContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext bundleContext) throws Exception {
+ Activator.context = null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/.classpath b/org.eclipse.babel.editor.rap/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.editor/.classpath
rename to org.eclipse.babel.editor.rap/.classpath
diff --git a/org.eclipse.babel.editor.rap/.project b/org.eclipse.babel.editor.rap/.project
new file mode 100644
index 00000000..07cfbbd4
--- /dev/null
+++ b/org.eclipse.babel.editor.rap/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.editor.rap</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.editor.rap/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.editor/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.editor.rap/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipse.babel.editor.rap/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.rap/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..64bcd1d9
--- /dev/null
+++ b/org.eclipse.babel.editor.rap/META-INF/MANIFEST.MF
@@ -0,0 +1,7 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RAP Fragment for Babel Editor
+Bundle-SymbolicName: org.eclipse.babel.editor.rap
+Bundle-Version: 0.8.0.qualifier
+Fragment-Host: org.eclipse.babel.editor;bundle-version="0.8.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/build.properties b/org.eclipse.babel.editor.rap/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.editor/build.properties
rename to org.eclipse.babel.editor.rap/build.properties
diff --git a/org.eclipse.babel.editor.rap/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java b/org.eclipse.babel.editor.rap/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
new file mode 100644
index 00000000..2d419a3e
--- /dev/null
+++ b/org.eclipse.babel.editor.rap/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
@@ -0,0 +1,15 @@
+package org.eclipse.babel.editor.tree.actions;
+
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+
+public class RenameKeyAction extends AbstractRenameKeyAction {
+ public RenameKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
+ super(editor, treeViewer);
+ }
+
+ @Override
+ public void run() {
+
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/.classpath b/org.eclipse.babel.editor.rcp.compat/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.rbe/.classpath
rename to org.eclipse.babel.editor.rcp.compat/.classpath
diff --git a/org.eclipse.babel.editor.rcp.compat/.project b/org.eclipse.babel.editor.rcp.compat/.project
new file mode 100644
index 00000000..d7075fed
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp.compat/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.editor.rcp.compat</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.editor.rcp.compat/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.rbe/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.editor.rcp.compat/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/.settings/org.eclipse.pde.core.prefs b/org.eclipse.babel.editor.rcp.compat/.settings/org.eclipse.pde.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.rbe/.settings/org.eclipse.pde.core.prefs
rename to org.eclipse.babel.editor.rcp.compat/.settings/org.eclipse.pde.core.prefs
diff --git a/org.eclipse.babel.editor.rcp.compat/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.rcp.compat/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..8062f44c
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp.compat/META-INF/MANIFEST.MF
@@ -0,0 +1,11 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RCP Compatibility for Babel Editor
+Bundle-SymbolicName: org.eclipse.babel.editor.rcp.compat
+Bundle-Version: 0.8.0.qualifier
+Bundle-Activator: org.eclipse.babel.editor.rcp.compat.Activator
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Import-Package: org.osgi.framework;version="1.3.0"
+Require-Bundle: org.eclipse.ui;bundle-version="3.7.0",
+ org.eclipse.ui.forms;bundle-version="3.5.101"
+Export-Package: org.eclipse.babel.editor.compat
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/build.properties b/org.eclipse.babel.editor.rcp.compat/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.rbe/build.properties
rename to org.eclipse.babel.editor.rcp.compat/build.properties
diff --git a/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/compat/MyFormToolkit.java b/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/compat/MyFormToolkit.java
new file mode 100644
index 00000000..ffffe0c9
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/compat/MyFormToolkit.java
@@ -0,0 +1,16 @@
+package org.eclipse.babel.editor.compat;
+
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.forms.FormColors;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+
+public class MyFormToolkit extends FormToolkit {
+
+ public MyFormToolkit(FormColors colors) {
+ super(colors);
+ }
+
+ public MyFormToolkit(Display display) {
+ super(display);
+ }
+}
diff --git a/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/compat/MySWT.java b/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/compat/MySWT.java
new file mode 100644
index 00000000..5827ae47
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/compat/MySWT.java
@@ -0,0 +1,7 @@
+package org.eclipse.babel.editor.compat;
+
+import org.eclipse.swt.SWT;
+
+public class MySWT extends SWT {
+
+}
diff --git a/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/rcp/compat/Activator.java b/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/rcp/compat/Activator.java
new file mode 100644
index 00000000..3d77342e
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp.compat/src/org/eclipse/babel/editor/rcp/compat/Activator.java
@@ -0,0 +1,30 @@
+package org.eclipse.babel.editor.rcp.compat;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ private static BundleContext context;
+
+ static BundleContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext bundleContext) throws Exception {
+ Activator.context = bundleContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext bundleContext) throws Exception {
+ Activator.context = null;
+ }
+
+}
diff --git a/org.eclipse.babel.editor.rcp/.classpath b/org.eclipse.babel.editor.rcp/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipse.babel.editor.rcp/.project b/org.eclipse.babel.editor.rcp/.project
new file mode 100644
index 00000000..74c83adf
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.editor.rcp</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipse.babel.editor.rcp/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.editor.rcp/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..c537b630
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipse.babel.editor.rcp/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.rcp/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..ebb39f4a
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/META-INF/MANIFEST.MF
@@ -0,0 +1,9 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RCP fragment for the Babel Editor
+Bundle-SymbolicName: org.eclipse.babel.editor.rcp
+Bundle-Version: 0.8.0.qualifier
+Fragment-Host: org.eclipse.babel.editor;bundle-version="0.8.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.eclipse.ltk.core.refactoring,
+ org.eclipse.ltk.ui.refactoring
diff --git a/org.eclipse.babel.editor.rcp/build.properties b/org.eclipse.babel.editor.rcp/build.properties
new file mode 100644
index 00000000..34d2e4d2
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/build.properties
@@ -0,0 +1,4 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java
similarity index 100%
rename from org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java
rename to org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java
diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
new file mode 100644
index 00000000..826d16fa
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * Copyright (c) 2009 Nigel Westbury
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Nigel Westbury - initial implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.refactoring;
+
+import java.text.MessageFormat;
+import java.util.Collection;
+
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+import org.eclipse.ltk.core.refactoring.Change;
+import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
+import org.eclipse.ltk.core.refactoring.RefactoringStatus;
+
+/**
+ * {@link Change} that renames a resource bundle key.
+ */
+public class RenameKeyChange extends Change {
+
+ private final MessagesBundleGroup fMessagesBundleGroup;
+
+ private final String fNewName;
+
+ private final boolean fRenameChildKeys;
+
+ private final KeyTreeNode fKeyTreeNode;
+
+ private ChangeDescriptor fDescriptor;
+
+ /**
+ * Creates the change.
+ *
+ * @param keyTreeNode the node in the model to rename
+ * @param newName the new name. Must not be empty
+ * @param renameChildKeys true if child keys are also to be renamed, false if just this one key is to be renamed
+ */
+ protected RenameKeyChange(MessagesBundleGroup messageBundleGroup, KeyTreeNode keyTreeNode, String newName, boolean renameChildKeys) {
+ if (keyTreeNode == null || newName == null || newName.length() == 0) {
+ throw new IllegalArgumentException();
+ }
+
+ fMessagesBundleGroup = messageBundleGroup;
+ fKeyTreeNode= keyTreeNode;
+ fNewName= newName;
+ fRenameChildKeys = renameChildKeys;
+ fDescriptor= null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.Change#getDescriptor()
+ */
+ public ChangeDescriptor getDescriptor() {
+ return fDescriptor;
+ }
+
+ /**
+ * Sets the change descriptor to be returned by {@link Change#getDescriptor()}.
+ *
+ * @param descriptor the change descriptor
+ */
+ public void setDescriptor(ChangeDescriptor descriptor) {
+ fDescriptor= descriptor;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.Change#getName()
+ */
+ public String getName() {
+ return MessageFormat.format("Rename {0} to {1}", new Object [] { fKeyTreeNode.getMessageKey(), fNewName});
+ }
+
+ /**
+ * Returns the new name.
+ *
+ * @return return the new name
+ */
+ public String getNewName() {
+ return fNewName;
+ }
+
+ /**
+ * This implementation of {@link Change#isValid(IProgressMonitor)} tests the modified resource using the validation method
+ * specified by {@link #setValidationMethod(int)}.
+ */
+ public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
+ pm.beginTask("", 2); //$NON-NLS-1$
+ try {
+ RefactoringStatus result = new RefactoringStatus();
+ return result;
+ } finally {
+ pm.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public void initializeValidationData(IProgressMonitor pm) {
+ }
+
+ public Object getModifiedElement() {
+ return "what is this for?";
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public Change perform(IProgressMonitor pm) throws CoreException {
+ try {
+ pm.beginTask("Rename resource bundle key", 1);
+
+ // Find the root - we will need this later
+ KeyTreeNode root = (KeyTreeNode) fKeyTreeNode.getParent();
+ while (root.getName() != null) {
+ root = (KeyTreeNode) root.getParent();
+ }
+
+ if (fRenameChildKeys) {
+ String key = fKeyTreeNode.getMessageKey();
+ String keyPrefix = fKeyTreeNode.getMessageKey() + ".";
+ Collection<KeyTreeNode> branchNodes = fKeyTreeNode.getBranch();
+ for (KeyTreeNode branchNode : branchNodes) {
+ String oldKey = branchNode.getMessageKey();
+ if (oldKey.equals(key) || oldKey.startsWith(keyPrefix)) {
+ String newKey = fNewName + oldKey.substring(key.length());
+ fMessagesBundleGroup.renameMessageKeys(oldKey, newKey);
+ }
+ }
+ } else {
+ fMessagesBundleGroup.renameMessageKeys(fKeyTreeNode.getMessageKey(), fNewName);
+ }
+
+ String oldName= fKeyTreeNode.getMessageKey();
+
+ // Find the node that was created with the new name
+ String segments [] = fNewName.split("\\.");
+ KeyTreeNode renamedKey = root;
+ for (String segment : segments) {
+ renamedKey = (KeyTreeNode) renamedKey.getChild(segment);
+ }
+
+ assert(renamedKey != null);
+ return new RenameKeyChange(fMessagesBundleGroup, renamedKey, oldName, fRenameChildKeys);
+ } finally {
+ pm.done();
+ }
+ }
+}
diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
new file mode 100644
index 00000000..9f73c3c6
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
@@ -0,0 +1,140 @@
+/*******************************************************************************
+ * Copyright (c) 2009 Nigel Westbury
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Nigel Westbury - initial implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.refactoring;
+
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.ltk.core.refactoring.Refactoring;
+import org.eclipse.ltk.core.refactoring.RefactoringContribution;
+import org.eclipse.ltk.core.refactoring.RefactoringCore;
+import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
+import org.eclipse.ltk.core.refactoring.RefactoringStatus;
+import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
+
+/**
+ * Refactoring descriptor for the rename resource bundle key refactoring.
+ * <p>
+ * An instance of this refactoring descriptor may be obtained by calling
+ * {@link RefactoringContribution#createDescriptor()} on a refactoring
+ * contribution requested by invoking
+ * {@link RefactoringCore#getRefactoringContribution(String)} with the
+ * refactoring id ({@link #ID}).
+ */
+public final class RenameKeyDescriptor extends RefactoringDescriptor {
+
+ public static final String ID = "org.eclipse.babel.editor.refactoring.renameKey"; //$NON-NLS-1$
+
+ /** The name attribute */
+ private String fNewName;
+
+ private KeyTreeNode fKeyNode;
+
+ private MessagesBundleGroup fMessagesBundleGroup;
+
+ /** Configures if references will be updated */
+ private boolean fRenameChildKeys;
+
+ /**
+ * Creates a new refactoring descriptor.
+ * <p>
+ * Clients should not instantiated this class but use {@link RefactoringCore#getRefactoringContribution(String)}
+ * with {@link #ID} to get the contribution that can create the descriptor.
+ * </p>
+ */
+ public RenameKeyDescriptor() {
+ super(ID, null, "N/A", null, RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE);
+ fNewName = null;
+ }
+
+ /**
+ * Sets the new name to rename the resource to.
+ *
+ * @param name
+ * the non-empty new name to set
+ */
+ public void setNewName(final String name) {
+ Assert.isNotNull(name);
+ Assert.isLegal(!"".equals(name), "Name must not be empty"); //$NON-NLS-1$//$NON-NLS-2$
+ fNewName = name;
+ }
+
+ /**
+ * Returns the new name to rename the resource to.
+ *
+ * @return
+ * the new name to rename the resource to
+ */
+ public String getNewName() {
+ return fNewName;
+ }
+
+ /**
+ * Sets the project name of this refactoring.
+ * <p>
+ * Note: If the resource to be renamed is of type {@link IResource#PROJECT},
+ * clients are required to to set the project name to <code>null</code>.
+ * </p>
+ * <p>
+ * The default is to associate the refactoring with the workspace.
+ * </p>
+ *
+ * @param project
+ * the non-empty project name to set, or <code>null</code> for
+ * the workspace
+ *
+ * @see #getProject()
+ */
+// public void setProject(final String project) {
+// super.setProject(project);
+// }
+
+ /**
+ * If set to <code>true</code>, this rename will also rename child keys. The default is to rename child keys.
+ *
+ * @param renameChildKeys <code>true</code> if this rename will rename child keys
+ */
+ public void setRenameChildKeys(boolean renameChildKeys) {
+ fRenameChildKeys = renameChildKeys;
+ }
+
+ public void setRenameChildKeys(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
+ this.fKeyNode = keyNode;
+ this.fMessagesBundleGroup = messagesBundleGroup;
+ }
+
+ /**
+ * Returns if this rename will also rename child keys
+ *
+ * @return returns <code>true</code> if this rename will rename child keys
+ */
+ public boolean isRenameChildKeys() {
+ return fRenameChildKeys;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.RefactoringDescriptor#createRefactoring(org.eclipse.ltk.core.refactoring.RefactoringStatus)
+ */
+ public Refactoring createRefactoring(RefactoringStatus status) throws CoreException {
+
+ String newName= getNewName();
+ if (newName == null || newName.length() == 0) {
+ status.addFatalError("The rename resource bundle key refactoring can not be performed as the new name is invalid");
+ return null;
+ }
+ RenameKeyProcessor processor = new RenameKeyProcessor(fKeyNode, fMessagesBundleGroup);
+ processor.setNewResourceName(newName);
+ processor.setRenameChildKeys(fRenameChildKeys);
+
+ return new RenameRefactoring(processor);
+ }
+}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
new file mode 100644
index 00000000..5ce68f52
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
@@ -0,0 +1,251 @@
+/*******************************************************************************
+ * Copyright (c) 2009 Nigel Westbury
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Nigel Westbury - initial implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.refactoring;
+
+import java.text.MessageFormat;
+
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.ltk.core.refactoring.Change;
+import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
+import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
+import org.eclipse.ltk.core.refactoring.RefactoringStatus;
+import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
+import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
+import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
+import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
+import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
+
+/**
+ * A rename processor for {@link IResource}. The processor will rename the resource and
+ * load rename participants if references should be renamed as well.
+ *
+ * @since 3.4
+ */
+public class RenameKeyProcessor extends RenameProcessor {
+
+ private KeyTreeNode fKeyNode;
+
+ private MessagesBundleGroup fMessageBundleGroup;
+
+ private String fNewResourceName;
+
+ private boolean fRenameChildKeys;
+
+ private RenameKeyArguments fRenameArguments; // set after checkFinalConditions
+
+ /**
+ * Creates a new rename resource processor.
+ *
+ * @param keyNode the resource to rename.
+ * @param messagesBundleGroup
+ */
+ public RenameKeyProcessor(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
+ if (keyNode == null) {
+ throw new IllegalArgumentException("key node must not be null"); //$NON-NLS-1$
+ }
+
+ fKeyNode = keyNode;
+ fMessageBundleGroup = messagesBundleGroup;
+ fRenameArguments= null;
+ fRenameChildKeys= true;
+ setNewResourceName(keyNode.getMessageKey()); // Initialize new name
+ }
+
+ /**
+ * Returns the new key node
+ *
+ * @return the new key node
+ */
+ public KeyTreeNode getNewKeyTreeNode() {
+ return fKeyNode;
+ }
+
+ /**
+ * Returns the new resource name
+ *
+ * @return the new resource name
+ */
+ public String getNewResourceName() {
+ return fNewResourceName;
+ }
+
+ /**
+ * Sets the new resource name
+ *
+ * @param newName the new resource name
+ */
+ public void setNewResourceName(String newName) {
+ Assert.isNotNull(newName);
+ fNewResourceName= newName;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
+ /*
+ * This method allows fatal and non-fatal problems to be shown to
+ * the user. Currently there are none so we return null to indicate
+ * this.
+ */
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
+ */
+ public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
+ pm.beginTask("", 1); //$NON-NLS-1$
+ try {
+ fRenameArguments = new RenameKeyArguments(getNewResourceName(), fRenameChildKeys, false);
+
+ ResourceChangeChecker checker = (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
+ IResourceChangeDescriptionFactory deltaFactory = checker.getDeltaFactory();
+
+ // TODO figure out what we want to do here....
+// ResourceModifications.buildMoveDelta(deltaFactory, fKeyNode, fRenameArguments);
+
+ return new RefactoringStatus();
+ } finally {
+ pm.done();
+ }
+ }
+
+ /**
+ * Validates if the a name is valid. This method does not change the name settings on the refactoring. It is intended to be used
+ * in a wizard to validate user input.
+ *
+ * @param newName the name to validate
+ * @return returns the resulting status of the validation
+ */
+ public RefactoringStatus validateNewElementName(String newName) {
+ Assert.isNotNull(newName);
+
+ if (newName.length() == 0) {
+ return RefactoringStatus.createFatalErrorStatus("New name for key must be entered");
+ }
+ if (newName.startsWith(".")) {
+ return RefactoringStatus.createFatalErrorStatus("Key cannot start with a '.'");
+ }
+ if (newName.endsWith(".")) {
+ return RefactoringStatus.createFatalErrorStatus("Key cannot end with a '.'");
+ }
+
+ String [] parts = newName.split("\\.");
+ for (String part : parts) {
+ if (part.length() == 0) {
+ return RefactoringStatus.createFatalErrorStatus("Key cannot contain an empty part between two periods");
+ }
+ if (!part.matches("([A-Z]|[a-z]|[0-9])*")) {
+ return RefactoringStatus.createFatalErrorStatus("Key can contain only letters, digits, and periods");
+ }
+ }
+
+ if (fMessageBundleGroup.isMessageKey(newName)) {
+ return RefactoringStatus.createFatalErrorStatus(MessagesEditorPlugin.getString("dialog.error.exists"));
+ }
+
+ return new RefactoringStatus();
+ }
+
+ protected RenameKeyDescriptor createDescriptor() {
+ RenameKeyDescriptor descriptor= new RenameKeyDescriptor();
+ descriptor.setDescription(MessageFormat.format("Rename resource bundle key ''{0}''", fKeyNode.getMessageKey()));
+ descriptor.setComment(MessageFormat.format("Rename resource ''{0}'' to ''{1}''", new Object[] { fKeyNode.getMessageKey(), fNewResourceName }));
+ descriptor.setFlags(RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE);
+ descriptor.setNewName(getNewResourceName());
+ descriptor.setRenameChildKeys(fRenameChildKeys);
+ return descriptor;
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public Change createChange(IProgressMonitor pm) throws CoreException {
+ pm.beginTask("", 1); //$NON-NLS-1$
+ try {
+ RenameKeyChange change = new RenameKeyChange(fMessageBundleGroup, getNewKeyTreeNode(), fNewResourceName, fRenameChildKeys);
+ change.setDescriptor(new RefactoringChangeDescriptor(createDescriptor()));
+ return change;
+ } finally {
+ pm.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
+ */
+ public Object[] getElements() {
+ return new Object[] { fKeyNode };
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getIdentifier()
+ */
+ public String getIdentifier() {
+ return "org.eclipse.babel.editor.refactoring.renameKeyProcessor"; //$NON-NLS-1$
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
+ */
+ public String getProcessorName() {
+ return "Rename Resource Bundle Key";
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
+ */
+ public boolean isApplicable() {
+ if (this.fKeyNode == null)
+ return false;
+ return true;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus, org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
+ */
+ public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
+ // TODO: figure out participants to return here
+ return new RefactoringParticipant[0];
+
+// String[] affectedNatures= ResourceProcessors.computeAffectedNatures(fResource);
+// return ParticipantManager.loadRenameParticipants(status, this, fResource, fRenameArguments, null, affectedNatures, shared);
+ }
+
+ /**
+ * Returns <code>true</code> if the refactoring processor also renames the child keys
+ *
+ * @return <code>true</code> if the refactoring processor also renames the child keys
+ */
+ public boolean getRenameChildKeys() {
+ return fRenameChildKeys;
+ }
+
+ /**
+ * Specifies if the refactoring processor also updates the child keys.
+ * The default behaviour is to update the child keys.
+ *
+ * @param renameChildKeys <code>true</code> if the refactoring processor should also rename the child keys
+ */
+ public void setRenameChildKeys(boolean renameChildKeys) {
+ fRenameChildKeys = renameChildKeys;
+ }
+
+}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
new file mode 100644
index 00000000..18b0f0c0
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
@@ -0,0 +1,163 @@
+/*******************************************************************************
+ * Copyright (c) 2009 Nigel Westbury
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Nigel Westbury - initial implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.refactoring;
+
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.ltk.core.refactoring.RefactoringStatus;
+import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
+import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
+import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * A wizard for the rename bundle key refactoring.
+ */
+public class RenameKeyWizard extends RefactoringWizard {
+
+ /**
+ * Creates a {@link RenameKeyWizard}.
+ *
+ * @param resource
+ * the bundle key to rename
+ * @param refactoring
+ */
+ public RenameKeyWizard(KeyTreeNode resource, RenameKeyProcessor refactoring) {
+ super(new RenameRefactoring(refactoring), DIALOG_BASED_USER_INTERFACE);
+ setDefaultPageTitle("Rename Resource Bundle Key");
+ setWindowTitle("Rename Resource Bundle Key");
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
+ */
+ protected void addUserInputPages() {
+ RenameKeyProcessor processor = (RenameKeyProcessor) getRefactoring().getAdapter(RenameKeyProcessor.class);
+ addPage(new RenameResourceRefactoringConfigurationPage(processor));
+ }
+
+ private static class RenameResourceRefactoringConfigurationPage extends UserInputWizardPage {
+
+ private final RenameKeyProcessor fRefactoringProcessor;
+ private Text fNameField;
+
+ public RenameResourceRefactoringConfigurationPage(RenameKeyProcessor processor) {
+ super("RenameResourceRefactoringInputPage"); //$NON-NLS-1$
+ fRefactoringProcessor= processor;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
+ */
+ public void createControl(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(2, false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ composite.setFont(parent.getFont());
+
+ Label label = new Label(composite, SWT.NONE);
+ label.setText("New name:");
+ label.setLayoutData(new GridData());
+
+ fNameField = new Text(composite, SWT.BORDER);
+ fNameField.setText(fRefactoringProcessor.getNewResourceName());
+ fNameField.setFont(composite.getFont());
+ fNameField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
+ fNameField.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ validatePage();
+ }
+ });
+
+ final Button includeChildKeysCheckbox = new Button(composite, SWT.CHECK);
+ if (fRefactoringProcessor.getNewKeyTreeNode().isUsedAsKey()) {
+ if (fRefactoringProcessor.getNewKeyTreeNode().getChildren().length == 0) {
+ // This is an actual key with no child keys.
+ includeChildKeysCheckbox.setSelection(false);
+ includeChildKeysCheckbox.setEnabled(false);
+ } else {
+ // This is both an actual key and it has child keys, so we
+ // let the user choose whether to also rename the child keys.
+ includeChildKeysCheckbox.setSelection(fRefactoringProcessor.getRenameChildKeys());
+ includeChildKeysCheckbox.setEnabled(true);
+ }
+ } else {
+ // This is no an actual key, just a containing node, so the option
+ // to rename child keys must be set (otherwise this rename would not
+ // do anything).
+ includeChildKeysCheckbox.setSelection(true);
+ includeChildKeysCheckbox.setEnabled(false);
+ }
+
+ includeChildKeysCheckbox.setText("Also rename child keys (other keys with this key as a prefix)");
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan= 2;
+ includeChildKeysCheckbox.setLayoutData(gd);
+ includeChildKeysCheckbox.addSelectionListener(new SelectionAdapter(){
+ public void widgetSelected(SelectionEvent e) {
+ fRefactoringProcessor.setRenameChildKeys(includeChildKeysCheckbox.getSelection());
+ }
+ });
+
+ fNameField.selectAll();
+ setPageComplete(false);
+ setControl(composite);
+ }
+
+ public void setVisible(boolean visible) {
+ if (visible) {
+ fNameField.setFocus();
+ }
+ super.setVisible(visible);
+ }
+
+ protected final void validatePage() {
+ String text= fNameField.getText();
+ RefactoringStatus status= fRefactoringProcessor.validateNewElementName(text);
+ setPageComplete(status);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#performFinish()
+ */
+ protected boolean performFinish() {
+ initializeRefactoring();
+ storeSettings();
+ return super.performFinish();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#getNextPage()
+ */
+ public IWizardPage getNextPage() {
+ initializeRefactoring();
+ storeSettings();
+ return super.getNextPage();
+ }
+
+ private void storeSettings() {
+ }
+
+ private void initializeRefactoring() {
+ fRefactoringProcessor.setNewResourceName(fNameField.getText());
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
new file mode 100644
index 00000000..cffce0a1
--- /dev/null
+++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
@@ -0,0 +1,34 @@
+package org.eclipse.babel.editor.tree.actions;
+
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.refactoring.RenameKeyProcessor;
+import org.eclipse.babel.editor.refactoring.RenameKeyWizard;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
+import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
+
+public class RenameKeyAction extends AbstractRenameKeyAction {
+
+ public RenameKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
+ super(editor, treeViewer);
+ }
+
+ @Override
+ public void run() {
+ KeyTreeNode node = getNodeSelection();
+
+ // Rename single item
+ RenameKeyProcessor refactoring = new RenameKeyProcessor(node,
+ getBundleGroup());
+
+ RefactoringWizard wizard = new RenameKeyWizard(node, refactoring);
+ try {
+ RefactoringWizardOpenOperation operation = new RefactoringWizardOpenOperation(
+ wizard);
+ operation.run(getShell(), "Introduce Indirection");
+ } catch (InterruptedException exception) {
+ // Do nothing
+ }
+ }
+}
diff --git a/org.eclipse.babel.editor/META-INF/MANIFEST.MF b/org.eclipse.babel.editor/META-INF/MANIFEST.MF
index e4e2225f..99303b36 100644
--- a/org.eclipse.babel.editor/META-INF/MANIFEST.MF
+++ b/org.eclipse.babel.editor/META-INF/MANIFEST.MF
@@ -4,23 +4,32 @@ Bundle-Name: %plugin.name
Bundle-SymbolicName: org.eclipse.babel.editor;singleton:=true
Bundle-Version: 0.8.0.qualifier
Bundle-Activator: org.eclipse.babel.editor.plugin.MessagesEditorPlugin
-Require-Bundle: org.eclipse.ui,
+Require-Bundle: org.eclipse.ui;resolution:=optional,
+ org.eclipse.babel.editor.rcp.compat;bundle-version="0.8.0";resolution:=optional,
org.eclipse.core.runtime,
- org.eclipse.jface.text,
- org.eclipse.ui.editors,
- org.eclipse.ui.ide,
- org.eclipse.ui.workbench.texteditor,
- org.eclipse.ui.views,
- org.eclipse.ui.forms;bundle-version="3.2.0",
+ org.eclipse.jface.text;resolution:=optional,
+ org.eclipse.ui.editors;resolution:=optional,
+ org.eclipse.babel.editor.rap.compat;bundle-version="0.8.0";resolution:=optional,
+ org.eclipse.ui.ide;resolution:=optional,
+ org.eclipse.ui.workbench.texteditor;resolution:=optional,
+ org.eclipse.ui.views;resolution:=optional,
org.eclipse.core.resources;bundle-version="3.2.0",
- org.eclipse.jdt.core;bundle-version="3.2.0",
- org.eclipse.ltk.core.refactoring,
- org.eclipse.ltk.ui.refactoring,
- org.eclipse.pde.core;bundle-version="3.2.0",
+ org.eclipse.jdt.core;bundle-version="3.2.0";resolution:=optional,
+ org.eclipse.ltk.core.refactoring;resolution:=optional,
+ org.eclipse.ltk.ui.refactoring;resolution:=optional,
org.junit;resolution:=optional,
- org.eclipse.babel.core;visibility:=reexport
+ org.eclipse.babel.core,
+ org.eclipse.pde.core;resolution:=optional,
+ org.eclipse.rap.ui;bundle-version="1.5.0";resolution:=optional,
+ org.eclipselabs.tapiji.translator.rap.supplemental;bundle-version="0.0.2";resolution:=optional,
+ org.eclipse.rap.ui.views;bundle-version="1.5.0";resolution:=optional,
+ org.eclipse.rap.rwt.supplemental.filedialog;bundle-version="1.5.0";resolution:=optional,
+ org.eclipse.rap.ui.forms;bundle-version="1.5.0";resolution:=optional,
+ org.eclipse.ui.forms;bundle-version="3.5.101";resolution:=optional
Bundle-ActivationPolicy: lazy
Bundle-Vendor: %plugin.provider
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-Localization: plugin
-Export-Package: org.eclipse.babel.editor.api
+Export-Package: org.eclipse.babel.editor,
+ org.eclipse.babel.editor.api,
+ org.eclipse.babel.editor.wizards
diff --git a/org.eclipse.babel.editor/icons/missing_translation.gif b/org.eclipse.babel.editor/icons/missing_translation.gif
new file mode 100644
index 00000000..af27508a
Binary files /dev/null and b/org.eclipse.babel.editor/icons/missing_translation.gif differ
diff --git a/org.eclipse.babel.editor/icons/missing_translation.png b/org.eclipse.babel.editor/icons/missing_translation.png
index fd405596..7cc7392c 100644
Binary files a/org.eclipse.babel.editor/icons/missing_translation.png and b/org.eclipse.babel.editor/icons/missing_translation.png differ
diff --git a/org.eclipse.babel.editor/icons/unused_and_missing_translations.png b/org.eclipse.babel.editor/icons/unused_and_missing_translations.png
index 2bc03e65..19a18b89 100644
Binary files a/org.eclipse.babel.editor/icons/unused_and_missing_translations.png and b/org.eclipse.babel.editor/icons/unused_and_missing_translations.png differ
diff --git a/org.eclipse.babel.editor/icons/unused_translation.png b/org.eclipse.babel.editor/icons/unused_translation.png
index d839c966..d449d03c 100644
Binary files a/org.eclipse.babel.editor/icons/unused_translation.png and b/org.eclipse.babel.editor/icons/unused_translation.png differ
diff --git a/org.eclipse.babel.editor/icons/warned_translation.png b/org.eclipse.babel.editor/icons/warned_translation.png
index 25346373..1713d913 100644
Binary files a/org.eclipse.babel.editor/icons/warned_translation.png and b/org.eclipse.babel.editor/icons/warned_translation.png differ
diff --git a/org.eclipse.babel.editor/messages.properties b/org.eclipse.babel.editor/messages.properties
index 7bd40e68..956d7e11 100644
--- a/org.eclipse.babel.editor/messages.properties
+++ b/org.eclipse.babel.editor/messages.properties
@@ -33,11 +33,16 @@ editor.wiz.add = Add -->
editor.wiz.browse = Browse...
editor.wiz.bundleName = &Base Name:
editor.wiz.creating = Creating
+editor.wiz.createfolder = The folder "%s" does not exist. Do you want to create it?
editor.wiz.desc = This wizard creates a set of new files with *.properties extension that can be opened by the ResourceBundle editor.
editor.wiz.error.bundleName = Base name must be specified.
editor.wiz.error.container = Files container must be specified.
editor.wiz.error.locale = At least one Locale must be added.
editor.wiz.error.extension = You can't specify an extension. It will be appended for you.
+editor.wiz.error.projectnotexist = Project "%s" does not exist.
+editor.wiz.error.invalidpath = You have specified an invalid path.
+editor.wiz.error.couldnotcreatefolder = Error creating folder "%s".
+editor.wiz.error.couldnotcreatefile = Error creating file "%s".
editor.wiz.folder = &Folder:
editor.wiz.opening = Opening properties files for editing...
editor.wiz.remove = <-- Remove
diff --git a/org.eclipse.babel.editor/plugin.xml b/org.eclipse.babel.editor/plugin.xml
index 0403cf88..bbf2d7fc 100644
--- a/org.eclipse.babel.editor/plugin.xml
+++ b/org.eclipse.babel.editor/plugin.xml
@@ -4,8 +4,8 @@
<extension
point="org.eclipse.ui.editors">
<editor
- class="org.eclipse.babel.editor.MessagesEditor"
- contributorClass="org.eclipse.babel.editor.MessagesEditorContributor"
+ class="org.eclipse.babel.editor.internal.MessagesEditor"
+ contributorClass="org.eclipse.babel.editor.internal.MessagesEditorContributor"
default="true"
extensions="properties"
icon="icons/propertiesfile.gif"
@@ -152,9 +152,9 @@
</category>
<wizard
category="org.eclipse.babel.editor.wizards.ResourceBundle"
- class="org.eclipse.babel.editor.wizards.ResourceBundleWizard"
+ class="org.eclipse.babel.editor.wizards.internal.ResourceBundleWizard"
icon="icons/resourcebundle.gif"
- id="org.eclipse.babel.editor.wizards.ResourceBundleWizard"
+ id="org.eclipse.babel.editor.wizards.internal.ResourceBundleWizard"
name="%wizard.rb.title">
<description>
%wizard.rb.description
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
new file mode 100644
index 00000000..dedc0e90
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java
@@ -0,0 +1,17 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Matthias Lettmayer - created interface to select a key in an editor (fixed issue 59)
+ ******************************************************************************/
+package org.eclipse.babel.editor;
+
+public interface IMessagesEditor {
+ String getSelectedKey();
+
+ void setSelectedKey(String key);
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java
index 593a3aa9..c37f6996 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java
@@ -10,7 +10,7 @@
******************************************************************************/
package org.eclipse.babel.editor;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditor.java
deleted file mode 100644
index c2f586d8..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditor.java
+++ /dev/null
@@ -1,435 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor;
-
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.editor.builder.ToggleNatureAction;
-import org.eclipse.babel.editor.bundle.MessagesBundleGroupFactory;
-import org.eclipse.babel.editor.i18n.I18NPage;
-import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipse.babel.editor.resource.EclipsePropertiesEditorResource;
-import org.eclipse.babel.editor.util.UIUtils;
-import org.eclipse.babel.editor.views.MessagesBundleGroupOutline;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.ide.IGotoMarker;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-/**
- * Multi-page editor for editing resource bundles.
- */
-public class MessagesEditor extends MultiPageEditorPart
- implements IGotoMarker {
-
- /** Editor ID, as defined in plugin.xml. */
- public static final String EDITOR_ID =
- "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$
-
- private String selectedKey;
- private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>(2);
-
- /** MessagesBundle group. */
- private MessagesBundleGroup messagesBundleGroup;
-
- /** Page with key tree and text fields for all locales. */
- private I18NPage i18nPage;
- private final List<Locale> localesIndex = new ArrayList<Locale>();
- private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>();
-
- private MessagesBundleGroupOutline outline;
-
- private MessagesEditorMarkers markers;
-
-
- private AbstractKeyTreeModel keyTreeModel;
-
- /**
- * Creates a multi-page editor example.
- */
- public MessagesEditor() {
- super();
- outline = new MessagesBundleGroupOutline(this);
- }
-
- public MessagesEditorMarkers getMarkers() {
- return markers;
- }
-
- private IPropertyChangeListener preferenceListener;
-
- /**
- * The <code>MultiPageEditorExample</code> implementation of this method
- * checks that the input is an instance of <code>IFileEditorInput</code>.
- */
- public void init(IEditorSite site, IEditorInput editorInput)
- throws PartInitException {
-
- if (editorInput instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) editorInput).getFile();
- if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) {
- IProject p = file.getProject();
- if (p != null && p.isAccessible()) {
- ToggleNatureAction.addOrRemoveNatureOnProject(p, true, true);
- }
- }
- try {
- messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup(site, file);
- } catch (MessageException e) {
- throw new PartInitException(
- "Cannot create bundle group.", e); //$NON-NLS-1$
- }
- markers = new MessagesEditorMarkers(messagesBundleGroup);
- setPartName(messagesBundleGroup.getName());
- setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
- closeIfAreadyOpen(site, file);
- super.init(site, editorInput);
- //TODO figure out model to use based on preferences
- keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
-// markerManager = new RBEMarkerManager(this);
- } else {
- throw new PartInitException(
- "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$
- }
- }
-
-// public RBEMarkerManager getMarkerManager() {
-// return markerManager;
-// }
-
- /**
- * Creates the pages of the multi-page editor.
- */
- protected void createPages() {
- // Create I18N page
- i18nPage = new I18NPage(
- getContainer(), SWT.NONE, this);
- int index = addPage(i18nPage);
- setPageText(index, MessagesEditorPlugin.getString(
- "editor.properties")); //$NON-NLS-1$
- setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
-
- // Create text editor pages for each locales
- try {
- Locale[] locales = messagesBundleGroup.getLocales();
- //first: sort the locales.
- UIUtils.sortLocales(locales);
- //second: filter+sort them according to the filter preferences.
- locales = UIUtils.filterLocales(locales);
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup.getMessagesBundle(locale);
- IMessagesResource resource = messagesBundle.getResource();
- TextEditor textEditor = (TextEditor) resource.getSource();
- index = addPage(textEditor, textEditor.getEditorInput());
- setPageText(index, UIUtils.getDisplayName(
- messagesBundle.getLocale()));
- setPageImage(index,
- UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE));
- localesIndex.add(locale);
- textEditorsIndex.add(textEditor);
- }
- } catch (PartInitException e) {
- ErrorDialog.openError(getSite().getShell(),
- "Error creating text editor page.", //$NON-NLS-1$
- null, e.getStatus());
- }
- }
-
- /**
- * Called when the editor's pages need to be reloaded.
- * For example when the filters of locale is changed.
- * <p>
- * Currently this only reloads the index page.
- * TODO: remove and add the new locales? it actually looks quite hard to do.
- * </p>
- */
- public void reloadDisplayedContents() {
- super.removePage(0);
- int currentlyActivePage = super.getActivePage();
- i18nPage.dispose();
- i18nPage = new I18NPage(
- getContainer(), SWT.NONE, this);
- super.addPage(0, i18nPage);
- if (currentlyActivePage == 0) {
- super.setActivePage(currentlyActivePage);
- }
- }
-
- /**
- * Saves the multi-page editor's document.
- */
- public void doSave(IProgressMonitor monitor) {
- for (ITextEditor textEditor : textEditorsIndex) {
- textEditor.doSave(monitor);
- }
-
- try { // [alst] remove in near future
- Thread.sleep(200);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- RBManager.getInstance(messagesBundleGroup.getProjectName()).fireEditorSaved();
- }
-
- /**
- * @see org.eclipse.ui.ISaveablePart#doSaveAs()
- */
- public void doSaveAs() {
- // Save As not allowed.
- }
-
- /**
- * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
- */
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- /**
- * Change current page based on locale. If there is no editors associated
- * with current locale, do nothing.
- * @param locale locale used to identify the page to change to
- */
- public void setActivePage(Locale locale) {
- int index = localesIndex.indexOf(locale);
- if (index > -1) {
- setActivePage(index + 1);
- }
- }
-
- /**
- * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(
- * org.eclipse.core.resources.IMarker)
- */
- public void gotoMarker(IMarker marker) {
-// String key = marker.getAttribute(RBEMarker.KEY, "");
-// if (key != null && key.length() > 0) {
-// setActivePage(0);
-// setSelectedKey(key);
-// getI18NPage().selectLocale(BabelUtils.parseLocale(
-// marker.getAttribute(RBEMarker.LOCALE, "")));
-// } else {
- IResource resource = marker.getResource();
- Locale[] locales = messagesBundleGroup.getLocales();
- for (int i = 0; i < locales.length; i++) {
- IMessagesResource messagesResource =
- ((MessagesBundle) messagesBundleGroup.getMessagesBundle(locales[i])).getResource();
- if (messagesResource instanceof EclipsePropertiesEditorResource) {
- EclipsePropertiesEditorResource propFile =
- (EclipsePropertiesEditorResource) messagesResource;
- if (resource.equals(propFile.getResource())) {
- //ok we got the locale.
- //try to open the master i18n page and select the corresponding key.
- try {
- String key = (String) marker.getAttribute(IMarker.LOCATION);
- if (key != null && key.length() > 0) {
- getI18NPage().selectLocale(locales[i]);
- setActivePage(0);
- setSelectedKey(key);
- return;
- }
- } catch (Exception e) {
- e.printStackTrace();//something better.s
- }
- //it did not work... fall back to the text editor.
- setActivePage(locales[i]);
- IDE.gotoMarker(
- (IEditorPart) propFile.getSource(), marker);
- break;
- }
- }
- }
-// }
- }
-
- /**
- * Calculates the contents of page GUI page when it is activated.
- */
- protected void pageChange(int newPageIndex) {
- super.pageChange(newPageIndex);
-// if (newPageIndex == 0) {
-// resourceMediator.reloadProperties();
-// i18nPage.refreshTextBoxes();
-// }
- }
-
-
- /**
- * Is the given file a member of this resource bundle.
- * @param file file to test
- * @return <code>true</code> if file is part of bundle
- */
- public boolean isBundleMember(IFile file) {
-// return resourceMediator.isResource(file);
- return false;
- }
-
- private void closeIfAreadyOpen(IEditorSite site, IFile file) {
- IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages();
- for (int i = 0; i < pages.length; i++) {
- IWorkbenchPage page = pages[i];
- IEditorReference[] editors = page.getEditorReferences();
- for (int j = 0; j < editors.length; j++) {
- IEditorPart editor = editors[j].getEditor(false);
- if (editor instanceof MessagesEditor) {
- MessagesEditor rbe = (MessagesEditor) editor;
- if (rbe.isBundleMember(file)) {
- page.closeEditor(editor, true);
- }
- }
- }
- }
- }
-
-
-
- /**
- * @see org.eclipse.ui.IWorkbenchPart#dispose()
- */
- public void dispose() {
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.editorDisposed();
- }
- i18nPage.dispose();
- for (ITextEditor textEditor : textEditorsIndex) {
- textEditor.dispose();
- }
- }
-
-
- /**
- * @return Returns the selectedKey.
- */
- public String getSelectedKey() {
- return selectedKey;
- }
- /**
- * @param selectedKey The selectedKey to set.
- */
- public void setSelectedKey(String activeKey) {
- if ((selectedKey == null && activeKey != null)
- || (selectedKey != null && activeKey == null)
- || (selectedKey != null && !selectedKey.equals(activeKey))) {
- String oldKey = this.selectedKey;
- this.selectedKey = activeKey;
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.selectedKeyChanged(oldKey, activeKey);
- }
- }
- }
-
- public void addChangeListener(IMessagesEditorChangeListener listener) {
- changeListeners.add(0, listener);
- }
-
- public void removeChangeListener(IMessagesEditorChangeListener listener) {
- changeListeners.remove(listener);
- }
-
- public Collection<IMessagesEditorChangeListener> getChangeListeners() {
- return changeListeners;
- }
-
- /**
- * @return Returns the messagesBundleGroup.
- */
- public MessagesBundleGroup getBundleGroup() {
- return messagesBundleGroup;
- }
-
- /**
- * @return Returns the keyTreeModel.
- */
- public AbstractKeyTreeModel getKeyTreeModel() {
- return keyTreeModel;
- }
-
- /**
- * @param keyTreeModel The keyTreeModel to set.
- */
- public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) {
- if ((this.keyTreeModel == null && newKeyTreeModel != null)
- || (keyTreeModel != null && newKeyTreeModel == null)
- || (!keyTreeModel.equals(newKeyTreeModel))) {
- AbstractKeyTreeModel oldModel = this.keyTreeModel;
- this.keyTreeModel = newKeyTreeModel;
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.keyTreeModelChanged(oldModel, newKeyTreeModel);
- }
- }
- }
-
- public I18NPage getI18NPage() {
- return i18nPage;
- }
-
- /** one of the SHOW_* constants defined in the {@link IMessagesEditorChangeListener} */
- private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL;
- /**
- * @return true when only unused and missing keys should be displayed. flase by default.
- */
- public int isShowOnlyUnusedAndMissingKeys() {
- return showOnlyMissingAndUnusedKeys;
- }
-
- public void setShowOnlyUnusedMissingKeys(int showFlag) {
- showOnlyMissingAndUnusedKeys = showFlag;
- for (IMessagesEditorChangeListener listener : getChangeListeners()) {
- listener.showOnlyUnusedAndMissingChanged(showFlag);
- }
- }
-
- public Object getAdapter(Class adapter) {
- Object obj = super.getAdapter(adapter);
- if (obj == null) {
- if (IContentOutlinePage.class.equals(adapter)) {
- return (outline);
- }
- }
- return (obj);
- }
-
- public ITextEditor getTextEditor(Locale locale) {
- int index = localesIndex.indexOf(locale);
- return textEditorsIndex.get(index);
- }
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorChangeAdapter.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorChangeAdapter.java
deleted file mode 100644
index 1e3e7197..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorChangeAdapter.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class MessagesEditorChangeAdapter implements IMessagesEditorChangeListener {
-
- /**
- *
- */
- public MessagesEditorChangeAdapter() {
- super();
- }
-
- /**
- * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
- */
- public void keyTreeVisibleChanged(boolean visible) {
- // do nothing
- }
- /**
- * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
- */
- public void showOnlyUnusedAndMissingChanged(int showFilterFlag) {
- // do nothing
- }
-
- /**
- * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#selectedKeyChanged(java.lang.String, java.lang.String)
- */
- public void selectedKeyChanged(String oldKey, String newKey) {
- // do nothing
- }
-
- /* (non-Javadoc)
- * @see org.eclilpse.babel.editor.editor.IMessagesEditorChangeListener#keyTreeModelChanged(org.eclipse.babel.core.message.tree.IKeyTreeModel, org.eclipse.babel.core.message.tree.IKeyTreeModel)
- */
- public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
- // do nothing
- }
-
- /**
- * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#editorDisposed()
- */
- public void editorDisposed() {
- // do nothing
- }
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorContributor.java
deleted file mode 100644
index 074575e4..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorContributor.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor;
-
-import org.eclipse.babel.editor.actions.FilterKeysAction;
-import org.eclipse.babel.editor.actions.KeyTreeVisibleAction;
-import org.eclipse.babel.editor.actions.NewLocaleAction;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-
-
-/**
- * Manages the installation/deinstallation of global actions for multi-page
- * editors. Responsible for the redirection of global actions to the active
- * editor.
- * Multi-page contributor replaces the contributors for the individual editors
- * in the multi-page editor.
- */
-public class MessagesEditorContributor
- extends MultiPageEditorActionBarContributor {
- private IEditorPart activeEditorPart;
-
- private KeyTreeVisibleAction toggleKeyTreeAction;
- private NewLocaleAction newLocaleAction;
- private IMenuManager resourceBundleMenu;
- private static String resourceBundleMenuID;
-
- /** singleton: probably not the cleanest way to access it from anywhere. */
- public static ActionGroup FILTERS = new FilterKeysActionGroup();
-
- /**
- * Creates a multi-page contributor.
- */
- public MessagesEditorContributor() {
- super();
- createActions();
- }
- /**
- * Returns the action registed with the given text editor.
- * @param editor eclipse text editor
- * @param actionID action id
- * @return IAction or null if editor is null.
- */
- protected IAction getAction(ITextEditor editor, String actionID) {
- return (editor == null ? null : editor.getAction(actionID));
- }
-
- /**
- * @see MultiPageEditorActionBarContributor
- * #setActivePage(org.eclipse.ui.IEditorPart)
- */
- public void setActivePage(IEditorPart part) {
- if (activeEditorPart == part) {
- return;
- }
-
- activeEditorPart = part;
-
- IActionBars actionBars = getActionBars();
- if (actionBars != null) {
-
- ITextEditor editor = (part instanceof ITextEditor)
- ? (ITextEditor) part : null;
-
- actionBars.setGlobalActionHandler(
- ActionFactory.DELETE.getId(),
- getAction(editor, ITextEditorActionConstants.DELETE));
- actionBars.setGlobalActionHandler(
- ActionFactory.UNDO.getId(),
- getAction(editor, ITextEditorActionConstants.UNDO));
- actionBars.setGlobalActionHandler(
- ActionFactory.REDO.getId(),
- getAction(editor, ITextEditorActionConstants.REDO));
- actionBars.setGlobalActionHandler(
- ActionFactory.CUT.getId(),
- getAction(editor, ITextEditorActionConstants.CUT));
- actionBars.setGlobalActionHandler(
- ActionFactory.COPY.getId(),
- getAction(editor, ITextEditorActionConstants.COPY));
- actionBars.setGlobalActionHandler(
- ActionFactory.PASTE.getId(),
- getAction(editor, ITextEditorActionConstants.PASTE));
- actionBars.setGlobalActionHandler(
- ActionFactory.SELECT_ALL.getId(),
- getAction(editor, ITextEditorActionConstants.SELECT_ALL));
- actionBars.setGlobalActionHandler(
- ActionFactory.FIND.getId(),
- getAction(editor, ITextEditorActionConstants.FIND));
- actionBars.setGlobalActionHandler(
- IDEActionFactory.BOOKMARK.getId(),
- getAction(editor, IDEActionFactory.BOOKMARK.getId()));
- actionBars.updateActionBars();
- }
- }
- private void createActions() {
-// sampleAction = new Action() {
-// public void run() {
-// MessageDialog.openInformation(null,
-// "ResourceBundle Editor Plug-in", "Sample Action Executed");
-// }
-// };
-// sampleAction.setText("Sample Action");
-// sampleAction.setToolTipText("Sample Action tool tip");
-// sampleAction.setImageDescriptor(
-// PlatformUI.getWorkbench().getSharedImages().
-// getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
-
- toggleKeyTreeAction = new KeyTreeVisibleAction();
- newLocaleAction = new NewLocaleAction();
-
-
-// toggleKeyTreeAction.setText("Show/Hide Key Tree");
-// toggleKeyTreeAction.setToolTipText("Click to show/hide the key tree");
-// toggleKeyTreeAction.setImageDescriptor(
-// PlatformUI.getWorkbench().getSharedImages().
-// getImageDescriptor(IDE.SharedImages.IMG_OPEN_MARKER));
-
- }
- /**
- * @see org.eclipse.ui.part.EditorActionBarContributor
- * #contributeToMenu(org.eclipse.jface.action.IMenuManager)
- */
- public void contributeToMenu(IMenuManager manager) {
-// System.out.println("active editor part:" +activeEditorPart);
-// System.out.println("menu editor:" + rbEditor);
- resourceBundleMenu = new MenuManager("&Messages", resourceBundleMenuID);
- manager.prependToGroup(IWorkbenchActionConstants.M_EDIT, resourceBundleMenu);
- resourceBundleMenu.add(toggleKeyTreeAction);
- resourceBundleMenu.add(newLocaleAction);
-
- FILTERS.fillContextMenu(resourceBundleMenu);
- }
- /**
- * @see org.eclipse.ui.part.EditorActionBarContributor
- * #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
- */
- public void contributeToToolBar(IToolBarManager manager) {
-// System.out.println("toolbar get page:" + getPage());
-// System.out.println("toolbar editor:" + rbEditor);
- manager.add(new Separator());
-// manager.add(sampleAction);
- manager.add(toggleKeyTreeAction);
- manager.add(newLocaleAction);
-
- ((FilterKeysActionGroup)FILTERS).fillActionBars(getActionBars());
- }
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.MultiPageEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
- */
- public void setActiveEditor(IEditorPart part) {
- super.setActiveEditor(part);
- MessagesEditor me = part instanceof MessagesEditor
- ? (MessagesEditor)part : null;
- toggleKeyTreeAction.setEditor(me);
- ((FilterKeysActionGroup) FILTERS).setActiveEditor(part);
- }
-
- /**
- * Groups the filter actions together.
- */
- private static class FilterKeysActionGroup extends ActionGroup {
- FilterKeysAction[] filtersAction = new FilterKeysAction[4];
-
- public FilterKeysActionGroup() {
- filtersAction[0] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ALL);
- filtersAction[1] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING);
- filtersAction[2] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED);
- filtersAction[3] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_UNUSED);
- }
-
- public void fillActionBars(IActionBars actionBars) {
- for (int i = 0; i < filtersAction.length; i++) {
- actionBars.getToolBarManager().add(filtersAction[i]);
- }
- }
-
- public void fillContextMenu(IMenuManager menu) {
- MenuManager filters = new MenuManager("Filters");
- for (int i = 0; i < filtersAction.length; i++) {
- filters.add(filtersAction[i]);
- }
- menu.add(filters);
- }
-
- public void updateActionBars() {
- for (int i = 0; i < filtersAction.length;i++) {
- filtersAction[i].update();
- }
- }
- public void setActiveEditor(IEditorPart part) {
- MessagesEditor me = part instanceof MessagesEditor
- ? (MessagesEditor)part : null;
- for (int i = 0; i < filtersAction.length; i++) {
- filtersAction[i].setEditor(me);
- }
- }
- }
-
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorMarkers.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorMarkers.java
deleted file mode 100644
index c8c9c4d0..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/MessagesEditorMarkers.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor;
-
-import java.beans.PropertyChangeEvent;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Observable;
-
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.MessagesBundleGroupAdapter;
-import org.eclipse.babel.core.message.checks.IMessageCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
-import org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy;
-import org.eclipse.babel.editor.resource.validator.MessagesBundleGroupValidator;
-import org.eclipse.babel.editor.resource.validator.ValidationFailureEvent;
-import org.eclipse.babel.editor.util.UIUtils;
-import org.eclipse.swt.widgets.Display;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class MessagesEditorMarkers
- extends Observable implements IValidationMarkerStrategy {
-
-// private final Collection validationEvents = new ArrayList();
- private final MessagesBundleGroup messagesBundleGroup;
-
- // private Map<String,Set<ValidationFailureEvent>> markersIndex = new HashMap();
- /** index is the name of the key. value is the collection of markers on that key */
- private Map<String, Collection<IMessageCheck>> markersIndex = new HashMap<String, Collection<IMessageCheck>>();
-
- /**
- * Maps a localized key (a locale and key pair) to the collection of markers
- * for that key and that locale. If no there are no markers for the key and
- * locale then there will be no entry in the map.
- */
- private Map<String, Collection<IMessageCheck>> localizedMarkersMap = new HashMap<String, Collection<IMessageCheck>>();
-
- /**
- * @param messagesBundleGroup
- */
- public MessagesEditorMarkers(final MessagesBundleGroup messagesBundleGroup) {
- super();
- this.messagesBundleGroup = messagesBundleGroup;
- validate();
- messagesBundleGroup.addMessagesBundleGroupListener(
- new MessagesBundleGroupAdapter() {
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- resetMarkers();
- }
- public void messagesBundleChanged(
- MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- resetMarkers();
- }
- });
- }
- public void propertyChange(PropertyChangeEvent evt) {
- resetMarkers();
- }
- private void resetMarkers() {
- clear();
- validate();
- }
- });
- }
-
- private String buildLocalizedKey(Locale locale, String key) {
- //the '=' is hack to make sure no local=key can ever conflict
- //with another local=key: in other words
- //it makes a hash of the combination (key+locale).
- if (locale == null) {
- locale = UIUtils.ROOT_LOCALE;
- }
- return locale + "=" + key;
- }
-
-
- /**
- * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
- */
- public void markFailed(ValidationFailureEvent event) {
- Collection<IMessageCheck> markersForKey = markersIndex.get(event.getKey());
- if (markersForKey == null) {
- markersForKey = new HashSet<IMessageCheck>();
- markersIndex.put(event.getKey(), markersForKey);
- }
- markersForKey.add(event.getCheck());
-
- String localizedKey = buildLocalizedKey(event.getLocale(), event.getKey());
- markersForKey = localizedMarkersMap.get(localizedKey);
- if (markersForKey == null) {
- markersForKey = new HashSet<IMessageCheck>();
- localizedMarkersMap.put(localizedKey, markersForKey);
- }
- markersForKey.add(event.getCheck());
-
- //System.out.println("CREATE EDITOR MARKER");
- setChanged();
- }
-
- public void clear() {
- markersIndex.clear();
- localizedMarkersMap.clear();
- setChanged();
- notifyObservers(this);
- }
-
- public boolean isMarked(String key) {
- return markersIndex.containsKey(key);
- }
-
- public Collection<IMessageCheck> getFailedChecks(String key) {
- return markersIndex.get(key);
- }
-
- /**
- *
- * @param key
- * @param locale
- * @return the collection of markers for the locale and key; the return value may be
- * null if there are no markers
- */
- public Collection<IMessageCheck> getFailedChecks(final String key, final Locale locale) {
- return localizedMarkersMap.get(buildLocalizedKey(locale, key));
- }
-
- private void validate() {
- //TODO in a UI thread
- Locale[] locales = messagesBundleGroup.getLocales();
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- MessagesBundleGroupValidator.validate(messagesBundleGroup, locale, this);
- }
-
- /*
- * If anything has changed in this observable, notify the observers.
- *
- * Something will have changed if, for example, multiple keys have the
- * same text. Note that notifyObservers will in fact do nothing if
- * nothing in the above call to 'validate' resulted in a call to
- * setChange.
- */
- notifyObservers(null);
- }
-
- /**
- * @param key
- * @return true when the key has a missing or unused issue
- */
- public boolean isMissingOrUnusedKey(String key) {
- Collection<IMessageCheck> markers = getFailedChecks(key);
- return markers != null && markersContainMissing(markers);
- }
-
- /**
- * @param key
- * @param isMissingOrUnused true when it has been assesed already
- * that it is missing or unused
- * @return true when the key is unused
- */
- public boolean isUnusedKey(String key, boolean isMissingOrUnused) {
- if (!isMissingOrUnused) {
- return false;
- }
- Collection<IMessageCheck> markers = getFailedChecks(key, UIUtils.ROOT_LOCALE);
- //if we get a missing on the root locale, it means the
- //that some localized resources are referring to a key that is not in
- //the default locale anymore: in other words, assuming the
- //the code is up to date with the default properties
- //file, the key is now unused.
- return markers != null && markersContainMissing(markers);
- }
-
- private boolean markersContainMissing(Collection<IMessageCheck> markers) {
- for (IMessageCheck marker : markers) {
- if (marker == MissingValueCheck.MISSING_KEY) {
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java
index 0e63cd28..03bbd23c 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java
@@ -11,12 +11,14 @@
package org.eclipse.babel.editor.actions;
import org.eclipse.babel.editor.IMessagesEditorChangeListener;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipse.babel.editor.MessagesEditorContributor;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
+import org.eclipse.babel.editor.internal.MessagesEditorContributor;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.graphics.Image;
/**
*
@@ -73,11 +75,27 @@ public void update() {
}
setText(getTextInternal());
setToolTipText(getTooltipInternal());
- setImageDescriptor(UIUtils.getImageDescriptor(getImageKey()));
+ setImageDescriptor(ImageDescriptor.createFromImage(getImage()));
}
- public String getImageKey() {
+ public Image getImage() {
+ switch (flagToSet) {
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
+ //return UIUtils.IMAGE_MISSING_TRANSLATION;
+ return UIUtils.getMissingTranslationImage();
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
+ //return UIUtils.IMAGE_UNUSED_AND_MISSING_TRANSLATIONS;
+ return UIUtils.getMissingAndUnusedTranslationsImage();
+ case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
+ //return UIUtils.IMAGE_UNUSED_TRANSLATION;
+ return UIUtils.getUnusedTranslationsImage();
+ case IMessagesEditorChangeListener.SHOW_ALL:
+ default:
+ return UIUtils.getImage(UIUtils.IMAGE_KEY);
+ }
+ }
+ /*public String getImageKey() {
switch (flagToSet) {
case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
return UIUtils.IMAGE_MISSING_TRANSLATION;
@@ -89,7 +107,7 @@ public String getImageKey() {
default:
return UIUtils.IMAGE_KEY;
}
- }
+ }*/
public String getTextInternal() {
switch (flagToSet) {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java
index 9bd4021e..c1d515f0 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java
@@ -10,8 +10,8 @@
******************************************************************************/
package org.eclipse.babel.editor.actions;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java
index 25322403..9e3b69a5 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java
@@ -10,7 +10,7 @@
******************************************************************************/
package org.eclipse.babel.editor.actions;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.action.Action;
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 54fdc72d..70b7bfc9 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,31 +1,28 @@
-/*
- * Copyright (C) 2011,
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
*
- * 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
- */
+ * Contributors:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
package org.eclipse.babel.editor.api;
import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer;
-import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-
+/**
+ * Provides the {@link ILevenshteinDistanceAnalyzer}
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
public class AnalyzerFactory {
+ /**
+ * @return An instance of the {@link LevenshteinDistanceAnalyzer}
+ */
public static ILevenshteinDistanceAnalyzer getLevenshteinDistanceAnalyzer () {
return (ILevenshteinDistanceAnalyzer) LevenshteinDistanceAnalyzer.getInstance();
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java
index fdf7e5f1..ed75d5b9 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java
@@ -1,14 +1,24 @@
package org.eclipse.babel.editor.api;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
import org.eclipse.babel.editor.i18n.I18NPage;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+/**
+ * Util class for editor operations.
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
public class EditorUtil {
+ /**
+ * @param page The {@link IWorkbenchPage}
+ * @return The selected {@link IKeyTreeNode} of the page.
+ */
public static IKeyTreeNode getSelectedKeyTreeNode (IWorkbenchPage page) {
MessagesEditor editor = (MessagesEditor)page.getActiveEditor();
if (editor.getSelectedPage() instanceof I18NPage) {
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
new file mode 100644
index 00000000..e3bf349c
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java
@@ -0,0 +1,17 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.editor.api;
+
+public interface ILevenshteinDistanceAnalyzer {
+
+ double analyse(Object value, Object pattern);
+
+}
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
new file mode 100644
index 00000000..6be0f20f
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.api;
+
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+
+public interface IValuedKeyTreeNode extends IKeyTreeNode {
+
+ public void initValues(Map<Locale, String> values);
+
+ public void addValue(Locale locale, String value);
+
+ public void setValue(Locale locale, String newValue);
+
+ public String getValue(Locale locale);
+
+ public Collection<String> getValues();
+
+ public void setInfo(Object info);
+
+ public Object getInfo();
+
+ public Collection<Locale> getLocales();
+
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java
index 5ccbb3d3..a5a2c770 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,22 +1,50 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
package org.eclipse.babel.editor.api;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.IAbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+/**
+ * Factory class for the tree or nodes of the tree.
+ * @see IAbstractKeyTreeModel
+ * @see IValuedKeyTreeNode
+ * <br><br>
+ *
+ * @author Alexej Strelzow
+ */
public class KeyTreeFactory {
+ /**
+ * @param messagesBundleGroup Input of the key tree model
+ * @return The {@link IAbstractKeyTreeModel}
+ */
public static IAbstractKeyTreeModel createModel(IMessagesBundleGroup messagesBundleGroup) {
return new AbstractKeyTreeModel((MessagesBundleGroup)messagesBundleGroup);
}
- public static IValuedKeyTreeNode createKeyTree(IKeyTreeNode parent, String name, String id, IMessagesBundleGroup bundle) {
- return new ValuedKeyTreeNode(parent, name, id, bundle);
+ /**
+ * @param parent The parent node
+ * @param name The name of the node
+ * @param id The id of the node (messages key)
+ * @param bundleGroup The {@link IMessagesBundleGroup}
+ * @return A new instance of {@link IValuedKeyTreeNode}
+ */
+ public static IValuedKeyTreeNode createKeyTree(IKeyTreeNode parent, String name, String id,
+ IMessagesBundleGroup bundleGroup) {
+ return new ValuedKeyTreeNode(parent, name, id, bundleGroup);
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/MessagesBundleFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/MessagesBundleFactory.java
deleted file mode 100644
index d7f5fdb5..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/MessagesBundleFactory.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.eclipse.babel.editor.api;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.Locale;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesFileResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class MessagesBundleFactory {
-
- static Logger logger = Logger.getLogger(MessagesBundleFactory.class.getSimpleName());
-
-// public static IMessagesBundleGroup createBundleGroup(IResource resource) {
-// // TODO �berlegen welche Strategy wann ziehen soll
-// //zB
-// if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() == null ||
-// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() == null) {
-// File ioFile = new File(resource.getRawLocation().toFile().getPath());
-//
-// logger.log(Level.INFO, "createBundleGroup: " + resource.getName());
-//
-// return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile, MsgEditorPreferences.getInstance().getSerializerConfig(),
-// MsgEditorPreferences.getInstance().getDeserializerConfig()));
-// } else {
-// return MessagesBundleGroupFactory.createBundleGroup(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorSite(), (IFile)resource);
-// }
-//
-// }
-
- public static IMessage createMessage(String key, Locale locale) {
- String l = locale == null ? "[default]" : locale.toString();
- logger.log(Level.INFO, "createMessage, key: " + key + " locale: " + l);
-
- return new Message(key, locale);
- }
-
- public static IMessagesBundle createBundle(Locale locale, File resource)
- throws MessageException {
- try {
- //TODO have the text de/serializer tied to Eclipse preferences,
- //singleton per project, and listening for changes
-
- String l = locale == null ? "[default]" : locale.toString();
- logger.log(Level.INFO, "createBundle: " + resource.getName() + " locale: " + l);
-
- return new MessagesBundle(new PropertiesFileResource(
- locale,
- new PropertiesSerializer(MsgEditorPreferences.getInstance().getSerializerConfig()),
- new PropertiesDeserializer(MsgEditorPreferences.getInstance().getDeserializerConfig()),
- resource));
- } catch (FileNotFoundException e) {
- throw new MessageException(
- "Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
- }
- }
-
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/PropertiesGenerator.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/PropertiesGenerator.java
deleted file mode 100644
index d2ae9ad4..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/PropertiesGenerator.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.eclipse.babel.editor.api;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class PropertiesGenerator {
-
- public static final String GENERATED_BY = PropertiesSerializer.GENERATED_BY;
-
- public static String generate(IMessagesBundle messagesBundle) {
- PropertiesSerializer ps = new PropertiesSerializer(MsgEditorPreferences.getInstance().getSerializerConfig());
- return ps.serialize(messagesBundle);
- }
-
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/PropertiesParser.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/PropertiesParser.java
deleted file mode 100644
index 8170ee60..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/PropertiesParser.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.eclipse.babel.editor.api;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipse.core.resources.IResource;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class PropertiesParser {
-
- public static IMessagesBundle parse(Locale locale, IResource resource) {
- PropertiesDeserializer pd = new PropertiesDeserializer(MsgEditorPreferences.getInstance().getDeserializerConfig());
-
- File file = resource.getRawLocation().toFile();
- File ioFile = new File(file.getPath());
- IMessagesBundle messagesBundle = MessagesBundleFactory.createBundle(locale, ioFile);
- pd.deserialize(messagesBundle, readFileAsString(file));
- return messagesBundle;
- }
-
- private static String readFileAsString(File filePath) {
- String content = "";
-
- if (!filePath.exists()) {
- return content;
- }
- BufferedReader fileReader = null;
- try {
- fileReader = new BufferedReader(new FileReader(filePath));
- String line = "";
-
- while ((line = fileReader.readLine()) != null) {
- content += line + "\n";
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (fileReader != null) {
- try {
- fileReader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- return content;
- }
-
-}
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 92d2b55d..0a02dd6d 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,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.editor.api;
import java.util.ArrayList;
@@ -7,10 +17,9 @@
import java.util.Locale;
import java.util.Map;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
public class ValuedKeyTreeNode extends KeyTreeNode implements IValuedKeyTreeNode {
@@ -35,6 +44,12 @@ public String getValue (Locale locale) {
return values.get(locale);
}
+ public void setValue(Locale locale, String newValue) {
+ if (values.containsKey(locale))
+ values.remove(locale);
+ addValue(locale, newValue);
+ }
+
public Collection<String> getValues () {
return values.values();
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java
index b8dad81b..93fb1470 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java
@@ -18,8 +18,9 @@
import java.util.Map;
import java.util.Set;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.babel.core.message.manager.RBManager;
import org.eclipse.babel.editor.bundle.MessagesBundleGroupFactory;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
@@ -37,7 +38,6 @@
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
/**
* @author Pascal Essiembre
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java
index a4e4b8f1..d3addff3 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java
@@ -10,7 +10,7 @@
******************************************************************************/
package org.eclipse.babel.editor.bundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.core.resources.IResource;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java
index 3279bce7..71cbe540 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java
@@ -7,6 +7,7 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - TapJI integration, messagesBundleId
******************************************************************************/
package org.eclipse.babel.editor.bundle;
@@ -14,9 +15,10 @@
import java.util.Collection;
import java.util.Locale;
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesIFileResource;
+import org.eclipse.babel.core.message.internal.MessageException;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+import org.eclipse.babel.core.message.resource.internal.PropertiesIFileResource;
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
import org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy;
@@ -38,7 +40,6 @@
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.part.FileEditorInput;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
/**
@@ -91,11 +92,11 @@ public DefaultBundleGroupStrategy(IEditorSite site, IFile file) {
}
/**
- * @see org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy
+ * @see org.eclipse.babel.core.message.internal.strategy.IMessagesBundleGroupStrategy
* #createMessagesBundleGroupName()
*/
public String createMessagesBundleGroupName() {
- return baseName + "[...]." + file.getFileExtension(); //$NON-NLS-1$
+ return getProjectName()+"*.properties";
}
public String createMessagesBundleId() {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java
index 411343db..a7877043 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java
@@ -18,7 +18,7 @@
import java.util.ArrayList;
import java.util.Collection;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.core.resources.IContainer;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
index 7ed2e770..2611de92 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
@@ -25,9 +25,9 @@
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesIFileResource;
-import org.eclipse.babel.core.message.resource.PropertiesReadOnlyResource;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.resource.internal.PropertiesIFileResource;
+import org.eclipse.babel.core.message.resource.internal.PropertiesReadOnlyResource;
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
@@ -134,7 +134,7 @@ public MessagesBundle createMessagesBundle(Locale locale) {
}
/**
- * @see org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy
+ * @see org.eclipse.babel.core.message.internal.strategy.IMessagesBundleGroupStrategy
* #createMessagesBundleGroupName()
*/
public String createMessagesBundleGroupName() {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java
index 766cf605..cd7faa9b 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java
@@ -17,7 +17,7 @@
import java.util.Set;
import java.util.StringTokenizer;
-import org.eclipse.babel.core.message.MessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
import org.eclipse.babel.core.util.BabelUtils;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.core.resources.IContainer;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java
index d21a31db..a7549dec 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java
@@ -17,13 +17,13 @@
import java.util.Observable;
import java.util.Observer;
-import org.eclipse.babel.core.message.checks.DuplicateValueCheck;
import org.eclipse.babel.core.message.checks.IMessageCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
+import org.eclipse.babel.core.message.checks.internal.DuplicateValueCheck;
+import org.eclipse.babel.core.message.checks.internal.MissingValueCheck;
import org.eclipse.babel.editor.i18n.actions.ShowDuplicateAction;
import org.eclipse.babel.editor.i18n.actions.ShowMissingAction;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java
index 66551208..f3ee616d 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NEntry.java
@@ -7,16 +7,20 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - updateKey
******************************************************************************/
package org.eclipse.babel.editor.i18n;
import java.util.Locale;
-import org.eclipse.babel.core.message.Message;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.Message;
import org.eclipse.babel.core.message.manager.RBManager;
import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.babel.editor.widgets.NullableText;
import org.eclipse.swt.SWT;
@@ -32,9 +36,6 @@
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
/**
* Tree for displaying and navigating through resource bundle keys.
@@ -277,7 +278,10 @@ private void updateModel() {
IMessage entry = messagesBundleGroup.getMessage(key, locale);
if (entry == null) {
entry = new Message(key, locale);
- messagesBundleGroup.getMessagesBundle(locale).addMessage(entry);
+ IMessagesBundle messagesBundle = messagesBundleGroup.getMessagesBundle(locale);
+ if (messagesBundle != null) {
+ messagesBundle.addMessage(entry);
+ }
}
entry.setText(textBox.getText());
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java
index cebfa1be..752aef19 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java
@@ -7,6 +7,7 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - TapiJI integration, fixed issues 37, 48
******************************************************************************/
package org.eclipse.babel.editor.i18n;
@@ -15,16 +16,18 @@
import java.util.Locale;
import java.util.Map;
+import org.eclipse.babel.core.message.IMessagesBundle;
import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
import org.eclipse.babel.core.message.manager.RBManager;
import org.eclipse.babel.editor.IMessagesEditorChangeListener;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
@@ -32,7 +35,6 @@
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
/**
* Internationalization page where one can edit all resource bundle entries
@@ -220,4 +222,8 @@ public void removeSelectionChangedListener(ISelectionChangedListener listener) {
public void setSelection(ISelection selection) {
keysComposite.getTreeViewer().setSelection(selection);
}
+
+ public TreeViewer getTreeViewer() {
+ return keysComposite.getTreeViewer();
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java
index f82e997a..23c37be5 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java
@@ -10,12 +10,12 @@
******************************************************************************/
package org.eclipse.babel.editor.i18n;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.tree.KeyTreeContributor;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.tree.actions.CollapseAllAction;
import org.eclipse.babel.editor.tree.actions.ExpandAllAction;
import org.eclipse.babel.editor.tree.actions.FlatModelAction;
import org.eclipse.babel.editor.tree.actions.TreeModelAction;
+import org.eclipse.babel.editor.tree.internal.KeyTreeContributor;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.viewers.TreeViewer;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java
index 286f0315..3cab8a48 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.java
@@ -10,9 +10,10 @@
******************************************************************************/
package org.eclipse.babel.editor.i18n;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
import org.eclipse.babel.core.message.tree.visitor.NodePathRegexVisitor;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
@@ -26,7 +27,6 @@
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
/**
* Tree for displaying and navigating through resource bundle keys.
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java
index 7381db99..6feca3b4 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java
@@ -17,51 +17,54 @@
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
-
/**
* @author Pascal Essiembre
- *
+ *
*/
public class ShowDuplicateAction extends Action {
- private final String[] keys;
- private final String key;
- private final Locale locale;
-
- /**
+ private final String[] keys;
+ private final String key;
+ private final Locale locale;
+
+ /**
*
*/
- public ShowDuplicateAction(String[] keys, String key, Locale locale) {
- super();
- this.keys = keys;
- this.key = key;
- this.locale = locale;
- setText("Show duplicate keys.");
- setImageDescriptor(
- UIUtils.getImageDescriptor("duplicate.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
+ public ShowDuplicateAction(String[] keys, String key, Locale locale) {
+ super();
+ this.keys = keys;
+ this.key = key;
+ this.locale = locale;
+ setText("Show duplicate keys.");
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_DUPLICATE));
+ setToolTipText("Check duplicate values");
+ }
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- //TODO have preference for whether to do cross locale checking
- StringBuffer buf = new StringBuffer("\"" + key + "\" (" + UIUtils.getDisplayName(locale) + ") has the same "
- + "value as the following key(s): \n\n");
- for (int i = 0; i < keys.length; i++) {
- String duplKey = keys[i];
- if (!key.equals(duplKey)) {
- buf.append(" · ");
- buf.append(duplKey);
- buf.append(" (" + UIUtils.getDisplayName(locale) + ")");
- buf.append("\n");
- }
- }
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(),
- "Duplicate value",
- buf.toString());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.action.IAction#run()
+ */
+ public void run() {
+ // TODO have preference for whether to do cross locale checking
+ StringBuffer buf = new StringBuffer("\"" + key + "\" ("
+ + UIUtils.getDisplayName(locale) + ") has the same "
+ + "value as the following key(s): \n\n");
+
+ if (keys != null) { // keys = duplicated values
+ for (int i = 0; i < keys.length; i++) {
+ String duplKey = keys[i];
+ if (!key.equals(duplKey)) {
+ buf.append(" · ");
+ buf.append(duplKey);
+ buf.append(" (" + UIUtils.getDisplayName(locale) + ")");
+ buf.append("\n");
+ }
+ }
+ MessageDialog.openInformation(
+ Display.getDefault().getActiveShell(), "Duplicate value",
+ buf.toString());
+ }
+ }
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java
new file mode 100644
index 00000000..52d04d4f
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java
@@ -0,0 +1,547 @@
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - TapJI integration, bug fixes & enhancements
+ * - issue 35, 36, 48, 73
+ ******************************************************************************/
+package org.eclipse.babel.editor.internal;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.internal.MessageException;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+import org.eclipse.babel.editor.IMessagesEditor;
+import org.eclipse.babel.editor.IMessagesEditorChangeListener;
+import org.eclipse.babel.editor.builder.ToggleNatureAction;
+import org.eclipse.babel.editor.bundle.MessagesBundleGroupFactory;
+import org.eclipse.babel.editor.i18n.I18NPage;
+import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
+import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
+import org.eclipse.babel.editor.resource.EclipsePropertiesEditorResource;
+import org.eclipse.babel.editor.util.UIUtils;
+import org.eclipse.babel.editor.views.MessagesBundleGroupOutline;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.dialogs.ErrorDialog;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorReference;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.editors.text.TextEditor;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.ui.ide.IGotoMarker;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipse.ui.part.MultiPageEditorPart;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
+
+/**
+ * Multi-page editor for editing resource bundles.
+ */
+public class MessagesEditor extends MultiPageEditorPart implements IGotoMarker,
+ IMessagesEditor {
+
+ /** Editor ID, as defined in plugin.xml. */
+ public static final String EDITOR_ID = "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$
+
+ private String selectedKey;
+ private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>(
+ 2);
+
+ /** MessagesBundle group. */
+ private MessagesBundleGroup messagesBundleGroup;
+
+ /** Page with key tree and text fields for all locales. */
+ private I18NPage i18nPage;
+ private final List<Locale> localesIndex = new ArrayList<Locale>();
+ private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>();
+
+ private MessagesBundleGroupOutline outline;
+
+ private MessagesEditorMarkers markers;
+
+ private AbstractKeyTreeModel keyTreeModel;
+
+ private IFile file; // init
+
+ private boolean updateSelectedKey;
+
+ /**
+ * Creates a multi-page editor example.
+ */
+ public MessagesEditor() {
+ super();
+ outline = new MessagesBundleGroupOutline(this);
+ }
+
+ public MessagesEditorMarkers getMarkers() {
+ return markers;
+ }
+
+ private IPropertyChangeListener preferenceListener;
+
+ /**
+ * The <code>MultiPageEditorExample</code> implementation of this method
+ * checks that the input is an instance of <code>IFileEditorInput</code>.
+ */
+ @Override
+ public void init(IEditorSite site, IEditorInput editorInput)
+ throws PartInitException {
+
+ if (editorInput instanceof IFileEditorInput) {
+ file = ((IFileEditorInput) editorInput).getFile();
+ if (MsgEditorPreferences.getInstance()
+ .isBuilderSetupAutomatically()) {
+ IProject p = file.getProject();
+ if (p != null && p.isAccessible()) {
+ ToggleNatureAction
+ .addOrRemoveNatureOnProject(p, true, true);
+ }
+ }
+ try {
+ messagesBundleGroup = MessagesBundleGroupFactory
+ .createBundleGroup(site, file);
+ } catch (MessageException e) {
+ throw new PartInitException("Cannot create bundle group.", e); //$NON-NLS-1$
+ }
+ markers = new MessagesEditorMarkers(messagesBundleGroup);
+ setPartName(messagesBundleGroup.getName());
+ setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
+ closeIfAreadyOpen(site, file);
+ super.init(site, editorInput);
+ // TODO figure out model to use based on preferences
+ keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
+ // markerManager = new RBEMarkerManager(this);
+ } else {
+ throw new PartInitException(
+ "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$
+ }
+ }
+
+ // public RBEMarkerManager getMarkerManager() {
+ // return markerManager;
+ // }
+
+ /**
+ * Creates the pages of the multi-page editor.
+ */
+ @Override
+ protected void createPages() {
+ // Create I18N page
+ i18nPage = new I18NPage(getContainer(), SWT.NONE, this);
+ int index = addPage(i18nPage);
+ setPageText(index, MessagesEditorPlugin.getString("editor.properties")); //$NON-NLS-1$
+ setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
+
+ // Create text editor pages for each locales
+ try {
+ Locale[] locales = messagesBundleGroup.getLocales();
+ // first: sort the locales.
+ UIUtils.sortLocales(locales);
+ // second: filter+sort them according to the filter preferences.
+ locales = UIUtils.filterLocales(locales);
+ for (int i = 0; i < locales.length; i++) {
+ Locale locale = locales[i];
+ MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup
+ .getMessagesBundle(locale);
+ IMessagesResource resource = messagesBundle.getResource();
+ TextEditor textEditor = (TextEditor) resource.getSource();
+ index = addPage(textEditor, textEditor.getEditorInput());
+ setPageText(index,
+ UIUtils.getDisplayName(messagesBundle.getLocale()));
+ setPageImage(index,
+ UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE));
+ localesIndex.add(locale);
+ textEditorsIndex.add(textEditor);
+ }
+ } catch (PartInitException e) {
+ ErrorDialog.openError(getSite().getShell(),
+ "Error creating text editor page.", //$NON-NLS-1$
+ null, e.getStatus());
+ }
+ }
+
+ /**
+ * Called when the editor's pages need to be reloaded. For example when the
+ * filters of locale is changed.
+ * <p>
+ * Currently this only reloads the index page. TODO: remove and add the new
+ * locales? it actually looks quite hard to do.
+ * </p>
+ */
+ public void reloadDisplayedContents() {
+ super.removePage(0);
+ int currentlyActivePage = super.getActivePage();
+ i18nPage.dispose();
+ i18nPage = new I18NPage(getContainer(), SWT.NONE, this);
+ super.addPage(0, i18nPage);
+ if (currentlyActivePage == 0) {
+ super.setActivePage(currentlyActivePage);
+ }
+ }
+
+ /**
+ * Saves the multi-page editor's document.
+ */
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ for (ITextEditor textEditor : textEditorsIndex) {
+ textEditor.doSave(monitor);
+ }
+
+ try { // [alst] remove in near future
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ updateSelectedKey = true;
+
+ RBManager instance = RBManager.getInstance(messagesBundleGroup
+ .getProjectName());
+
+ refreshKeyTreeModel(); // keeps editor and I18NPage in sync
+
+ instance.fireEditorSaved();
+
+ // // maybe new init?
+ }
+
+ private void refreshKeyTreeModel() {
+ String selectedKey = getSelectedKey(); // memorize
+
+ if (messagesBundleGroup == null) {
+ messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup(
+ (IEditorSite) getSite(), file);
+ }
+
+ AbstractKeyTreeModel oldModel = this.keyTreeModel;
+ this.keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
+
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.keyTreeModelChanged(oldModel, this.keyTreeModel);
+ }
+
+ i18nPage.getTreeViewer().expandAll();
+
+ if (selectedKey != null) {
+ setSelectedKey(selectedKey);
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.ISaveablePart#doSaveAs()
+ */
+ @Override
+ public void doSaveAs() {
+ // Save As not allowed.
+ }
+
+ /**
+ * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
+ */
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
+
+ /**
+ * Change current page based on locale. If there is no editors associated
+ * with current locale, do nothing.
+ *
+ * @param locale
+ * locale used to identify the page to change to
+ */
+ public void setActivePage(Locale locale) {
+ int index = localesIndex.indexOf(locale);
+ if (index > -1) {
+ setActivePage(index + 1);
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(org.eclipse.core.resources.IMarker)
+ */
+ public void gotoMarker(IMarker marker) {
+ // String key = marker.getAttribute(RBEMarker.KEY, "");
+ // if (key != null && key.length() > 0) {
+ // setActivePage(0);
+ // setSelectedKey(key);
+ // getI18NPage().selectLocale(BabelUtils.parseLocale(
+ // marker.getAttribute(RBEMarker.LOCALE, "")));
+ // } else {
+ IResource resource = marker.getResource();
+ Locale[] locales = messagesBundleGroup.getLocales();
+ for (int i = 0; i < locales.length; i++) {
+ IMessagesResource messagesResource = ((MessagesBundle) messagesBundleGroup
+ .getMessagesBundle(locales[i])).getResource();
+ if (messagesResource instanceof EclipsePropertiesEditorResource) {
+ EclipsePropertiesEditorResource propFile = (EclipsePropertiesEditorResource) messagesResource;
+ if (resource.equals(propFile.getResource())) {
+ // ok we got the locale.
+ // try to open the master i18n page and select the
+ // corresponding key.
+ try {
+ String key = (String) marker
+ .getAttribute(IMarker.LOCATION);
+ if (key != null && key.length() > 0) {
+ getI18NPage().selectLocale(locales[i]);
+ setActivePage(0);
+ setSelectedKey(key);
+ return;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();// something better.s
+ }
+ // it did not work... fall back to the text editor.
+ setActivePage(locales[i]);
+ IDE.gotoMarker((IEditorPart) propFile.getSource(), marker);
+ break;
+ }
+ }
+ }
+ // }
+ }
+
+ /**
+ * Calculates the contents of page GUI page when it is activated.
+ */
+ @Override
+ protected void pageChange(int newPageIndex) {
+ super.pageChange(newPageIndex);
+ if (newPageIndex != 0) { // if we just want the default page -> == 1
+ setSelection(newPageIndex);
+ } else if (newPageIndex == 0 && updateSelectedKey) {
+ // TODO: find better way
+ for (IMessagesBundle bundle : messagesBundleGroup
+ .getMessagesBundles()) {
+ RBManager.getInstance(messagesBundleGroup.getProjectName())
+ .fireResourceChanged(bundle);
+ }
+ updateSelectedKey = false;
+ }
+
+ // if (newPageIndex == 0) {
+ // resourceMediator.reloadProperties();
+ // i18nPage.refreshTextBoxes();
+ // }
+ }
+
+ private void setSelection(int newPageIndex) {
+ ITextEditor editor = textEditorsIndex.get(--newPageIndex);
+ String selectedKey = getSelectedKey();
+ if (selectedKey != null) {
+ if (editor.getEditorInput() instanceof FileEditorInput) {
+ FileEditorInput input = (FileEditorInput) editor
+ .getEditorInput();
+ try {
+ IFile file = input.getFile();
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(file.getContents()));
+ String line = "";
+ int selectionIndex = 0;
+ boolean found = false;
+
+ while ((line = reader.readLine()) != null) {
+ int index = line.indexOf('=');
+ if (index != -1) {
+ if (selectedKey.equals(line.substring(0, index)
+ .trim())) {
+ found = true;
+ break;
+ }
+ }
+ selectionIndex += line.length() + 2; // + \r\n
+ }
+
+ if (found) {
+ editor.selectAndReveal(selectionIndex, 0);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Is the given file a member of this resource bundle.
+ *
+ * @param file
+ * file to test
+ * @return <code>true</code> if file is part of bundle
+ */
+ public boolean isBundleMember(IFile file) {
+ // return resourceMediator.isResource(file);
+ return false;
+ }
+
+ private void closeIfAreadyOpen(IEditorSite site, IFile file) {
+ IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages();
+ for (int i = 0; i < pages.length; i++) {
+ IWorkbenchPage page = pages[i];
+ IEditorReference[] editors = page.getEditorReferences();
+ for (int j = 0; j < editors.length; j++) {
+ IEditorPart editor = editors[j].getEditor(false);
+ if (editor instanceof MessagesEditor) {
+ MessagesEditor rbe = (MessagesEditor) editor;
+ if (rbe.isBundleMember(file)) {
+ page.closeEditor(editor, true);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IWorkbenchPart#dispose()
+ */
+ @Override
+ public void dispose() {
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.editorDisposed();
+ }
+ i18nPage.dispose();
+ for (ITextEditor textEditor : textEditorsIndex) {
+ textEditor.dispose();
+ }
+ }
+
+ /**
+ * @return Returns the selectedKey.
+ */
+ public String getSelectedKey() {
+ return selectedKey;
+ }
+
+ /**
+ * @param selectedKey
+ * The selectedKey to set.
+ */
+ public void setSelectedKey(String activeKey) {
+ if ((selectedKey == null && activeKey != null)
+ || (selectedKey != null && activeKey == null)
+ || (selectedKey != null && !selectedKey.equals(activeKey))) {
+ String oldKey = this.selectedKey;
+ this.selectedKey = activeKey;
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.selectedKeyChanged(oldKey, activeKey);
+ }
+ }
+ }
+
+ public void addChangeListener(IMessagesEditorChangeListener listener) {
+ changeListeners.add(0, listener);
+ }
+
+ public void removeChangeListener(IMessagesEditorChangeListener listener) {
+ changeListeners.remove(listener);
+ }
+
+ public Collection<IMessagesEditorChangeListener> getChangeListeners() {
+ return changeListeners;
+ }
+
+ /**
+ * @return Returns the messagesBundleGroup.
+ */
+ public MessagesBundleGroup getBundleGroup() {
+ return messagesBundleGroup;
+ }
+
+ /**
+ * @return Returns the keyTreeModel.
+ */
+ public AbstractKeyTreeModel getKeyTreeModel() {
+ return keyTreeModel;
+ }
+
+ /**
+ * @param keyTreeModel
+ * The keyTreeModel to set.
+ */
+ public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) {
+ if ((this.keyTreeModel == null && newKeyTreeModel != null)
+ || (keyTreeModel != null && newKeyTreeModel == null)
+ || (!keyTreeModel.equals(newKeyTreeModel))) {
+ AbstractKeyTreeModel oldModel = this.keyTreeModel;
+ this.keyTreeModel = newKeyTreeModel;
+ for (IMessagesEditorChangeListener listener : changeListeners) {
+ listener.keyTreeModelChanged(oldModel, newKeyTreeModel);
+ }
+ }
+ }
+
+ public I18NPage getI18NPage() {
+ return i18nPage;
+ }
+
+ /**
+ * one of the SHOW_* constants defined in the
+ * {@link IMessagesEditorChangeListener}
+ */
+ private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL;
+
+ /**
+ * @return true when only unused and missing keys should be displayed. flase
+ * by default.
+ */
+ public int isShowOnlyUnusedAndMissingKeys() {
+ return showOnlyMissingAndUnusedKeys;
+ }
+
+ public void setShowOnlyUnusedMissingKeys(int showFlag) {
+ showOnlyMissingAndUnusedKeys = showFlag;
+ for (IMessagesEditorChangeListener listener : getChangeListeners()) {
+ listener.showOnlyUnusedAndMissingChanged(showFlag);
+ }
+ }
+
+ @Override
+ public Object getAdapter(Class adapter) {
+ Object obj = super.getAdapter(adapter);
+ if (obj == null) {
+ if (IContentOutlinePage.class.equals(adapter)) {
+ return (outline);
+ }
+ }
+ return (obj);
+ }
+
+ public ITextEditor getTextEditor(Locale locale) {
+ int index = localesIndex.indexOf(locale);
+ return textEditorsIndex.get(index);
+ }
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java
new file mode 100644
index 00000000..de1eeb1a
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.java
@@ -0,0 +1,62 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.internal;
+
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+import org.eclipse.babel.editor.IMessagesEditorChangeListener;
+
+/**
+ * @author Pascal Essiembre
+ *
+ */
+public class MessagesEditorChangeAdapter implements IMessagesEditorChangeListener {
+
+ /**
+ *
+ */
+ public MessagesEditorChangeAdapter() {
+ super();
+ }
+
+ /**
+ * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
+ */
+ public void keyTreeVisibleChanged(boolean visible) {
+ // do nothing
+ }
+ /**
+ * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
+ */
+ public void showOnlyUnusedAndMissingChanged(int showFilterFlag) {
+ // do nothing
+ }
+
+ /**
+ * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#selectedKeyChanged(java.lang.String, java.lang.String)
+ */
+ public void selectedKeyChanged(String oldKey, String newKey) {
+ // do nothing
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclilpse.babel.editor.editor.IMessagesEditorChangeListener#keyTreeModelChanged(org.eclipse.babel.core.message.internal.tree.internal.IKeyTreeModel, org.eclipse.babel.core.message.internal.tree.internal.IKeyTreeModel)
+ */
+ public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
+ // do nothing
+ }
+
+ /**
+ * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#editorDisposed()
+ */
+ public void editorDisposed() {
+ // do nothing
+ }
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java
new file mode 100644
index 00000000..182cad8e
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java
@@ -0,0 +1,220 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.internal;
+
+import org.eclipse.babel.editor.IMessagesEditorChangeListener;
+import org.eclipse.babel.editor.actions.FilterKeysAction;
+import org.eclipse.babel.editor.actions.KeyTreeVisibleAction;
+import org.eclipse.babel.editor.actions.NewLocaleAction;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.actions.ActionFactory;
+import org.eclipse.ui.actions.ActionGroup;
+import org.eclipse.ui.ide.IDEActionFactory;
+import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.texteditor.ITextEditorActionConstants;
+
+
+/**
+ * Manages the installation/deinstallation of global actions for multi-page
+ * editors. Responsible for the redirection of global actions to the active
+ * editor.
+ * Multi-page contributor replaces the contributors for the individual editors
+ * in the multi-page editor.
+ */
+public class MessagesEditorContributor
+ extends MultiPageEditorActionBarContributor {
+ private IEditorPart activeEditorPart;
+
+ private KeyTreeVisibleAction toggleKeyTreeAction;
+ private NewLocaleAction newLocaleAction;
+ private IMenuManager resourceBundleMenu;
+ private static String resourceBundleMenuID;
+
+ /** singleton: probably not the cleanest way to access it from anywhere. */
+ public static ActionGroup FILTERS = new FilterKeysActionGroup();
+
+ /**
+ * Creates a multi-page contributor.
+ */
+ public MessagesEditorContributor() {
+ super();
+ createActions();
+ }
+ /**
+ * Returns the action registed with the given text editor.
+ * @param editor eclipse text editor
+ * @param actionID action id
+ * @return IAction or null if editor is null.
+ */
+ protected IAction getAction(ITextEditor editor, String actionID) {
+ return (editor == null ? null : editor.getAction(actionID));
+ }
+
+ /**
+ * @see MultiPageEditorActionBarContributor
+ * #setActivePage(org.eclipse.ui.IEditorPart)
+ */
+ public void setActivePage(IEditorPart part) {
+ if (activeEditorPart == part) {
+ return;
+ }
+
+ activeEditorPart = part;
+
+ IActionBars actionBars = getActionBars();
+ if (actionBars != null) {
+
+ ITextEditor editor = (part instanceof ITextEditor)
+ ? (ITextEditor) part : null;
+
+ actionBars.setGlobalActionHandler(
+ ActionFactory.DELETE.getId(),
+ getAction(editor, ITextEditorActionConstants.DELETE));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.UNDO.getId(),
+ getAction(editor, ITextEditorActionConstants.UNDO));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.REDO.getId(),
+ getAction(editor, ITextEditorActionConstants.REDO));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.CUT.getId(),
+ getAction(editor, ITextEditorActionConstants.CUT));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.COPY.getId(),
+ getAction(editor, ITextEditorActionConstants.COPY));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.PASTE.getId(),
+ getAction(editor, ITextEditorActionConstants.PASTE));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.SELECT_ALL.getId(),
+ getAction(editor, ITextEditorActionConstants.SELECT_ALL));
+ actionBars.setGlobalActionHandler(
+ ActionFactory.FIND.getId(),
+ getAction(editor, ITextEditorActionConstants.FIND));
+ actionBars.setGlobalActionHandler(
+ IDEActionFactory.BOOKMARK.getId(),
+ getAction(editor, IDEActionFactory.BOOKMARK.getId()));
+ actionBars.updateActionBars();
+ }
+ }
+ private void createActions() {
+// sampleAction = new Action() {
+// public void run() {
+// MessageDialog.openInformation(null,
+// "ResourceBundle Editor Plug-in", "Sample Action Executed");
+// }
+// };
+// sampleAction.setText("Sample Action");
+// sampleAction.setToolTipText("Sample Action tool tip");
+// sampleAction.setImageDescriptor(
+// PlatformUI.getWorkbench().getSharedImages().
+// getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
+
+ toggleKeyTreeAction = new KeyTreeVisibleAction();
+ newLocaleAction = new NewLocaleAction();
+
+
+// toggleKeyTreeAction.setText("Show/Hide Key Tree");
+// toggleKeyTreeAction.setToolTipText("Click to show/hide the key tree");
+// toggleKeyTreeAction.setImageDescriptor(
+// PlatformUI.getWorkbench().getSharedImages().
+// getImageDescriptor(IDE.SharedImages.IMG_OPEN_MARKER));
+
+ }
+ /**
+ * @see org.eclipse.ui.part.EditorActionBarContributor
+ * #contributeToMenu(org.eclipse.jface.action.IMenuManager)
+ */
+ public void contributeToMenu(IMenuManager manager) {
+// System.out.println("active editor part:" +activeEditorPart);
+// System.out.println("menu editor:" + rbEditor);
+ resourceBundleMenu = new MenuManager("&Messages", resourceBundleMenuID);
+ manager.prependToGroup(IWorkbenchActionConstants.M_EDIT, resourceBundleMenu);
+ resourceBundleMenu.add(toggleKeyTreeAction);
+ resourceBundleMenu.add(newLocaleAction);
+
+ FILTERS.fillContextMenu(resourceBundleMenu);
+ }
+ /**
+ * @see org.eclipse.ui.part.EditorActionBarContributor
+ * #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
+ */
+ public void contributeToToolBar(IToolBarManager manager) {
+// System.out.println("toolbar get page:" + getPage());
+// System.out.println("toolbar editor:" + rbEditor);
+ manager.add(new Separator());
+// manager.add(sampleAction);
+ manager.add(toggleKeyTreeAction);
+ manager.add(newLocaleAction);
+
+ ((FilterKeysActionGroup)FILTERS).fillActionBars(getActionBars());
+ }
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.part.MultiPageEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
+ */
+ public void setActiveEditor(IEditorPart part) {
+ super.setActiveEditor(part);
+ MessagesEditor me = part instanceof MessagesEditor
+ ? (MessagesEditor)part : null;
+ toggleKeyTreeAction.setEditor(me);
+ ((FilterKeysActionGroup) FILTERS).setActiveEditor(part);
+ }
+
+ /**
+ * Groups the filter actions together.
+ */
+ private static class FilterKeysActionGroup extends ActionGroup {
+ FilterKeysAction[] filtersAction = new FilterKeysAction[4];
+
+ public FilterKeysActionGroup() {
+ filtersAction[0] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ALL);
+ filtersAction[1] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING);
+ filtersAction[2] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED);
+ filtersAction[3] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_UNUSED);
+ }
+
+ public void fillActionBars(IActionBars actionBars) {
+ for (int i = 0; i < filtersAction.length; i++) {
+ actionBars.getToolBarManager().add(filtersAction[i]);
+ }
+ }
+
+ public void fillContextMenu(IMenuManager menu) {
+ MenuManager filters = new MenuManager("Filters");
+ for (int i = 0; i < filtersAction.length; i++) {
+ filters.add(filtersAction[i]);
+ }
+ menu.add(filters);
+ }
+
+ public void updateActionBars() {
+ for (int i = 0; i < filtersAction.length;i++) {
+ filtersAction[i].update();
+ }
+ }
+ public void setActiveEditor(IEditorPart part) {
+ MessagesEditor me = part instanceof MessagesEditor
+ ? (MessagesEditor)part : null;
+ for (int i = 0; i < filtersAction.length; i++) {
+ filtersAction[i].setEditor(me);
+ }
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java
new file mode 100644
index 00000000..4854b1bb
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java
@@ -0,0 +1,227 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.internal;
+
+import java.beans.PropertyChangeEvent;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Observable;
+
+import org.eclipse.babel.core.message.checks.IMessageCheck;
+import org.eclipse.babel.core.message.checks.internal.DuplicateValueCheck;
+import org.eclipse.babel.core.message.checks.internal.MissingValueCheck;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroupAdapter;
+import org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy;
+import org.eclipse.babel.editor.resource.validator.MessagesBundleGroupValidator;
+import org.eclipse.babel.editor.resource.validator.ValidationFailureEvent;
+import org.eclipse.babel.editor.util.UIUtils;
+import org.eclipse.swt.widgets.Display;
+
+
+/**
+ * @author Pascal Essiembre
+ *
+ */
+public class MessagesEditorMarkers
+ extends Observable implements IValidationMarkerStrategy {
+
+// private final Collection validationEvents = new ArrayList();
+ private final MessagesBundleGroup messagesBundleGroup;
+
+ // private Map<String,Set<ValidationFailureEvent>> markersIndex = new HashMap();
+ /** index is the name of the key. value is the collection of markers on that key */
+ private Map<String, Collection<IMessageCheck>> markersIndex = new HashMap<String, Collection<IMessageCheck>>();
+
+ /**
+ * Maps a localized key (a locale and key pair) to the collection of markers
+ * for that key and that locale. If no there are no markers for the key and
+ * locale then there will be no entry in the map.
+ */
+ private Map<String, Collection<IMessageCheck>> localizedMarkersMap = new HashMap<String, Collection<IMessageCheck>>();
+
+ /**
+ * @param messagesBundleGroup
+ */
+ public MessagesEditorMarkers(final MessagesBundleGroup messagesBundleGroup) {
+ super();
+ this.messagesBundleGroup = messagesBundleGroup;
+ validate();
+ messagesBundleGroup.addMessagesBundleGroupListener(
+ new MessagesBundleGroupAdapter() {
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ resetMarkers();
+ }
+ public void messagesBundleChanged(
+ MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ Display.getDefault().asyncExec(new Runnable(){
+ public void run() {
+ resetMarkers();
+ }
+ });
+ }
+ public void propertyChange(PropertyChangeEvent evt) {
+ resetMarkers();
+ }
+ private void resetMarkers() {
+ clear();
+ validate();
+ }
+ });
+ }
+
+ private String buildLocalizedKey(Locale locale, String key) {
+ //the '=' is hack to make sure no local=key can ever conflict
+ //with another local=key: in other words
+ //it makes a hash of the combination (key+locale).
+ if (locale == null) {
+ locale = UIUtils.ROOT_LOCALE;
+ }
+ return locale + "=" + key;
+ }
+
+
+ /**
+ * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
+ */
+ public void markFailed(ValidationFailureEvent event) {
+ Collection<IMessageCheck> markersForKey = markersIndex.get(event.getKey());
+ if (markersForKey == null) {
+ markersForKey = new HashSet<IMessageCheck>();
+ markersIndex.put(event.getKey(), markersForKey);
+ }
+ markersForKey.add(event.getCheck());
+
+ String localizedKey = buildLocalizedKey(event.getLocale(), event.getKey());
+ markersForKey = localizedMarkersMap.get(localizedKey);
+ if (markersForKey == null) {
+ markersForKey = new HashSet<IMessageCheck>();
+ localizedMarkersMap.put(localizedKey, markersForKey);
+ }
+ markersForKey.add(event.getCheck());
+
+ //System.out.println("CREATE EDITOR MARKER");
+ setChanged();
+ }
+
+ public void clear() {
+ markersIndex.clear();
+ localizedMarkersMap.clear();
+ setChanged();
+ notifyObservers(this);
+ }
+
+ public boolean isMarked(String key) {
+ return markersIndex.containsKey(key);
+ }
+
+ public Collection<IMessageCheck> getFailedChecks(String key) {
+ return markersIndex.get(key);
+ }
+
+ /**
+ *
+ * @param key
+ * @param locale
+ * @return the collection of markers for the locale and key; the return value may be
+ * null if there are no markers
+ */
+ public Collection<IMessageCheck> getFailedChecks(final String key, final Locale locale) {
+ return localizedMarkersMap.get(buildLocalizedKey(locale, key));
+ }
+
+ private void validate() {
+ //TODO in a UI thread
+ Locale[] locales = messagesBundleGroup.getLocales();
+ for (int i = 0; i < locales.length; i++) {
+ Locale locale = locales[i];
+ MessagesBundleGroupValidator.validate(messagesBundleGroup, locale, this);
+ }
+
+ /*
+ * If anything has changed in this observable, notify the observers.
+ *
+ * Something will have changed if, for example, multiple keys have the
+ * same text. Note that notifyObservers will in fact do nothing if
+ * nothing in the above call to 'validate' resulted in a call to
+ * setChange.
+ */
+ notifyObservers(null);
+ }
+
+ /**
+ * @param key
+ * @return true when the key has a missing or unused issue
+ */
+ public boolean isMissingOrUnusedKey(String key) {
+ Collection<IMessageCheck> markers = getFailedChecks(key);
+ return markers != null && markersContainMissing(markers);
+ }
+
+ /**
+ * @param key
+ * @return true when the key has a missing issue
+ */
+ public boolean isMissingKey(String key) {
+ Collection<IMessageCheck> markers = getFailedChecks(key);
+ return markers != null && markersContainMissing(markers);
+ }
+
+ /**
+ * @param key
+ * @param isMissingOrUnused true when it has been assesed already
+ * that it is missing or unused
+ * @return true when the key is unused
+ */
+ public boolean isUnusedKey(String key, boolean isMissingOrUnused) {
+ if (!isMissingOrUnused) {
+ return false;
+ }
+ Collection<IMessageCheck> markers = getFailedChecks(key, UIUtils.ROOT_LOCALE);
+ //if we get a missing on the root locale, it means the
+ //that some localized resources are referring to a key that is not in
+ //the default locale anymore: in other words, assuming the
+ //the code is up to date with the default properties
+ //file, the key is now unused.
+ return markers != null && markersContainMissing(markers);
+ }
+
+ /**
+ *
+ * @param key
+ * @return true when the value is a duplicate value
+ */
+ public boolean isDuplicateValue(String key) {
+ Collection<IMessageCheck> markers = getFailedChecks(key);
+ for (IMessageCheck marker : markers) {
+ if (marker instanceof DuplicateValueCheck) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean markersContainMissing(Collection<IMessageCheck> markers) {
+ for (IMessageCheck marker : markers) {
+ if (marker == MissingValueCheck.MISSING_KEY) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java
index 72371314..ca6713ee 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java
@@ -20,9 +20,10 @@
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Set;
+import java.util.Stack;
-import org.eclipse.babel.core.message.AbstractIFileChangeListener;
-import org.eclipse.babel.core.message.AbstractIFileChangeListener.IFileChangeListenerRegistry;
+import org.eclipse.babel.core.message.internal.AbstractIFileChangeListener;
+import org.eclipse.babel.core.message.internal.AbstractIFileChangeListener.IFileChangeListenerRegistry;
import org.eclipse.babel.editor.builder.ToggleNatureAction;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
import org.eclipse.core.resources.IResource;
@@ -36,6 +37,12 @@
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.pde.nls.internal.ui.model.ResourceBundleModel;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
@@ -77,6 +84,49 @@ public class MessagesEditorPlugin extends AbstractUIPlugin implements IFileChang
public MessagesEditorPlugin() {
resourceChangeSubscribers = new HashMap<String,Set<AbstractIFileChangeListener>>();
}
+
+ private static class UndoKeyListener implements Listener {
+
+ public void handleEvent(Event event) {
+ Control focusControl = event.display.getFocusControl();
+ if (event.stateMask == SWT.CONTROL && focusControl instanceof Text) {
+
+ Text txt = (Text) focusControl;
+ String actText = txt.getText();
+ Stack<String> undoStack = (Stack<String>) txt.getData("UNDO");
+ Stack<String> redoStack = (Stack<String>) txt.getData("REDO");
+
+ if (event.keyCode == 'z' && undoStack != null && redoStack != null) { // Undo
+ event.doit = false;
+
+ if (undoStack.size() > 0) {
+ String peek = undoStack.peek();
+ if (actText != null && !txt.getText().equals(peek)) {
+ String pop = undoStack.pop();
+ txt.setText(pop);
+ txt.setSelection(pop.length());
+ redoStack.push(actText);
+ }
+ }
+ } else if (event.keyCode == 'y' && undoStack != null && redoStack != null) { // Redo
+
+ event.doit = false;
+
+ if (redoStack.size() > 0) {
+ String peek = redoStack.peek();
+
+ if (actText != null && !txt.getText().equals(peek)) {
+ String pop = redoStack.pop();
+ txt.setText(pop);
+ txt.setSelection(pop.length());
+ undoStack.push(actText);
+ }
+ }
+ }
+ }
+ }
+
+ }
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(
@@ -121,6 +171,17 @@ public void resourceChanged(IResourceChangeEvent event) {
}
};
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener);
+ try {
+ Display.getDefault().asyncExec(new Runnable() {
+
+ public void run() {
+ Display.getDefault().addFilter(SWT.KeyUp, new UndoKeyListener());
+
+ }
+ });
+ } catch (NullPointerException e) {
+ // TODO [RAP] Session not loaded yet -> Display is null
+ }
}
/**
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java
index 0f4b97d3..8c90bb31 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java
@@ -7,6 +7,8 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - externalized IPropertiesSerializerConfig and
+ * IPropertiesDeserializerConfig for better reuse
******************************************************************************/
package org.eclipse.babel.editor.preferences;
@@ -15,9 +17,9 @@
import org.eclipse.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
import org.eclipse.babel.core.message.resource.ser.IPropertiesSerializerConfig;
import org.eclipse.babel.editor.IMessagesEditorChangeListener;
-import org.eclipse.babel.editor.MessagesEditor;
import org.eclipse.babel.editor.builder.Builder;
import org.eclipse.babel.editor.builder.ToggleNatureAction;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java
index 6b2bd923..bf144a93 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java
@@ -1,6 +1,14 @@
-/**
- *
- */
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - moved code to here
+ ******************************************************************************/
package org.eclipse.babel.editor.preferences;
import org.eclipse.babel.core.configuration.ConfigurationManager;
@@ -9,11 +17,12 @@
import org.eclipse.core.runtime.Preferences;
/**
- * @author ala
- *
+ * The concrete implementation of {@link IPropertiesDeserializerConfig}.
+ *
+ * @author Alexej Strelzow
*/
public class PropertiesDeserializerConfig implements
- IPropertiesDeserializerConfig {
+ IPropertiesDeserializerConfig { // Moved from MsgEditorPreferences, to make it more flexible.
/** MsgEditorPreferences. */
private static final Preferences PREFS =
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java
index d8b19778..06a0db9c 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java
@@ -1,6 +1,14 @@
-/**
- *
- */
+/*******************************************************************************
+ * 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
+ * Alexej Strelzow - moved code to here
+ ******************************************************************************/
package org.eclipse.babel.editor.preferences;
import org.eclipse.babel.core.configuration.ConfigurationManager;
@@ -9,10 +17,12 @@
import org.eclipse.core.runtime.Preferences;
/**
- * @author ala
- *
+ * The concrete implementation of {@link IPropertiesSerializerConfig}.
+ *
+ * @author Alexej Strelzow
*/
public class PropertiesSerializerConfig implements IPropertiesSerializerConfig {
+ // Moved from MsgEditorPreferences, to make it more flexible.
/** MsgEditorPreferences. */
private static final Preferences PREFS =
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
deleted file mode 100644
index 83c3f70d..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.refactoring;
-
-import java.text.MessageFormat;
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-
-/**
- * {@link Change} that renames a resource bundle key.
- */
-public class RenameKeyChange extends Change {
-
- private final MessagesBundleGroup fMessagesBundleGroup;
-
- private final String fNewName;
-
- private final boolean fRenameChildKeys;
-
- private final KeyTreeNode fKeyTreeNode;
-
- private ChangeDescriptor fDescriptor;
-
- /**
- * Creates the change.
- *
- * @param keyTreeNode the node in the model to rename
- * @param newName the new name. Must not be empty
- * @param renameChildKeys true if child keys are also to be renamed, false if just this one key is to be renamed
- */
- protected RenameKeyChange(MessagesBundleGroup messageBundleGroup, KeyTreeNode keyTreeNode, String newName, boolean renameChildKeys) {
- if (keyTreeNode == null || newName == null || newName.length() == 0) {
- throw new IllegalArgumentException();
- }
-
- fMessagesBundleGroup = messageBundleGroup;
- fKeyTreeNode= keyTreeNode;
- fNewName= newName;
- fRenameChildKeys = renameChildKeys;
- fDescriptor= null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#getDescriptor()
- */
- public ChangeDescriptor getDescriptor() {
- return fDescriptor;
- }
-
- /**
- * Sets the change descriptor to be returned by {@link Change#getDescriptor()}.
- *
- * @param descriptor the change descriptor
- */
- public void setDescriptor(ChangeDescriptor descriptor) {
- fDescriptor= descriptor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#getName()
- */
- public String getName() {
- return MessageFormat.format("Rename {0} to {1}", new Object [] { fKeyTreeNode.getMessageKey(), fNewName});
- }
-
- /**
- * Returns the new name.
- *
- * @return return the new name
- */
- public String getNewName() {
- return fNewName;
- }
-
- /**
- * This implementation of {@link Change#isValid(IProgressMonitor)} tests the modified resource using the validation method
- * specified by {@link #setValidationMethod(int)}.
- */
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- pm.beginTask("", 2); //$NON-NLS-1$
- try {
- RefactoringStatus result = new RefactoringStatus();
- return result;
- } finally {
- pm.done();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor)
- */
- public void initializeValidationData(IProgressMonitor pm) {
- }
-
- public Object getModifiedElement() {
- return "what is this for?";
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("Rename resource bundle key", 1);
-
- // Find the root - we will need this later
- KeyTreeNode root = (KeyTreeNode) fKeyTreeNode.getParent();
- while (root.getName() != null) {
- root = (KeyTreeNode) root.getParent();
- }
-
- if (fRenameChildKeys) {
- String key = fKeyTreeNode.getMessageKey();
- String keyPrefix = fKeyTreeNode.getMessageKey() + ".";
- Collection<KeyTreeNode> branchNodes = fKeyTreeNode.getBranch();
- for (KeyTreeNode branchNode : branchNodes) {
- String oldKey = branchNode.getMessageKey();
- if (oldKey.equals(key) || oldKey.startsWith(keyPrefix)) {
- String newKey = fNewName + oldKey.substring(key.length());
- fMessagesBundleGroup.renameMessageKeys(oldKey, newKey);
- }
- }
- } else {
- fMessagesBundleGroup.renameMessageKeys(fKeyTreeNode.getMessageKey(), fNewName);
- }
-
- String oldName= fKeyTreeNode.getMessageKey();
-
- // Find the node that was created with the new name
- String segments [] = fNewName.split("\\.");
- KeyTreeNode renamedKey = root;
- for (String segment : segments) {
- renamedKey = (KeyTreeNode) renamedKey.getChild(segment);
- }
-
- assert(renamedKey != null);
- return new RenameKeyChange(fMessagesBundleGroup, renamedKey, oldName, fRenameChildKeys);
- } finally {
- pm.done();
- }
- }
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
deleted file mode 100644
index 1d2b68e5..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.refactoring;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-
-/**
- * Refactoring descriptor for the rename resource bundle key refactoring.
- * <p>
- * An instance of this refactoring descriptor may be obtained by calling
- * {@link RefactoringContribution#createDescriptor()} on a refactoring
- * contribution requested by invoking
- * {@link RefactoringCore#getRefactoringContribution(String)} with the
- * refactoring id ({@link #ID}).
- */
-public final class RenameKeyDescriptor extends RefactoringDescriptor {
-
- public static final String ID = "org.eclipse.babel.editor.refactoring.renameKey"; //$NON-NLS-1$
-
- /** The name attribute */
- private String fNewName;
-
- private KeyTreeNode fKeyNode;
-
- private MessagesBundleGroup fMessagesBundleGroup;
-
- /** Configures if references will be updated */
- private boolean fRenameChildKeys;
-
- /**
- * Creates a new refactoring descriptor.
- * <p>
- * Clients should not instantiated this class but use {@link RefactoringCore#getRefactoringContribution(String)}
- * with {@link #ID} to get the contribution that can create the descriptor.
- * </p>
- */
- public RenameKeyDescriptor() {
- super(ID, null, "N/A", null, RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE);
- fNewName = null;
- }
-
- /**
- * Sets the new name to rename the resource to.
- *
- * @param name
- * the non-empty new name to set
- */
- public void setNewName(final String name) {
- Assert.isNotNull(name);
- Assert.isLegal(!"".equals(name), "Name must not be empty"); //$NON-NLS-1$//$NON-NLS-2$
- fNewName = name;
- }
-
- /**
- * Returns the new name to rename the resource to.
- *
- * @return
- * the new name to rename the resource to
- */
- public String getNewName() {
- return fNewName;
- }
-
- /**
- * Sets the project name of this refactoring.
- * <p>
- * Note: If the resource to be renamed is of type {@link IResource#PROJECT},
- * clients are required to to set the project name to <code>null</code>.
- * </p>
- * <p>
- * The default is to associate the refactoring with the workspace.
- * </p>
- *
- * @param project
- * the non-empty project name to set, or <code>null</code> for
- * the workspace
- *
- * @see #getProject()
- */
-// public void setProject(final String project) {
-// super.setProject(project);
-// }
-
- /**
- * If set to <code>true</code>, this rename will also rename child keys. The default is to rename child keys.
- *
- * @param renameChildKeys <code>true</code> if this rename will rename child keys
- */
- public void setRenameChildKeys(boolean renameChildKeys) {
- fRenameChildKeys = renameChildKeys;
- }
-
- public void setRenameChildKeys(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
- this.fKeyNode = keyNode;
- this.fMessagesBundleGroup = messagesBundleGroup;
- }
-
- /**
- * Returns if this rename will also rename child keys
- *
- * @return returns <code>true</code> if this rename will rename child keys
- */
- public boolean isRenameChildKeys() {
- return fRenameChildKeys;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.RefactoringDescriptor#createRefactoring(org.eclipse.ltk.core.refactoring.RefactoringStatus)
- */
- public Refactoring createRefactoring(RefactoringStatus status) throws CoreException {
-
- String newName= getNewName();
- if (newName == null || newName.length() == 0) {
- status.addFatalError("The rename resource bundle key refactoring can not be performed as the new name is invalid");
- return null;
- }
- RenameKeyProcessor processor = new RenameKeyProcessor(fKeyNode, fMessagesBundleGroup);
- processor.setNewResourceName(newName);
- processor.setRenameChildKeys(fRenameChildKeys);
-
- return new RenameRefactoring(processor);
- }
-}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
deleted file mode 100644
index 3368b3b1..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.refactoring;
-
-import java.text.MessageFormat;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-
-/**
- * A rename processor for {@link IResource}. The processor will rename the resource and
- * load rename participants if references should be renamed as well.
- *
- * @since 3.4
- */
-public class RenameKeyProcessor extends RenameProcessor {
-
- private KeyTreeNode fKeyNode;
-
- private MessagesBundleGroup fMessageBundleGroup;
-
- private String fNewResourceName;
-
- private boolean fRenameChildKeys;
-
- private RenameKeyArguments fRenameArguments; // set after checkFinalConditions
-
- /**
- * Creates a new rename resource processor.
- *
- * @param keyNode the resource to rename.
- * @param messagesBundleGroup
- */
- public RenameKeyProcessor(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
- if (keyNode == null) {
- throw new IllegalArgumentException("key node must not be null"); //$NON-NLS-1$
- }
-
- fKeyNode = keyNode;
- fMessageBundleGroup = messagesBundleGroup;
- fRenameArguments= null;
- fRenameChildKeys= true;
- setNewResourceName(keyNode.getMessageKey()); // Initialize new name
- }
-
- /**
- * Returns the new key node
- *
- * @return the new key node
- */
- public KeyTreeNode getNewKeyTreeNode() {
- return fKeyNode;
- }
-
- /**
- * Returns the new resource name
- *
- * @return the new resource name
- */
- public String getNewResourceName() {
- return fNewResourceName;
- }
-
- /**
- * Sets the new resource name
- *
- * @param newName the new resource name
- */
- public void setNewResourceName(String newName) {
- Assert.isNotNull(newName);
- fNewResourceName= newName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- /*
- * This method allows fatal and non-fatal problems to be shown to
- * the user. Currently there are none so we return null to indicate
- * this.
- */
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- fRenameArguments = new RenameKeyArguments(getNewResourceName(), fRenameChildKeys, false);
-
- ResourceChangeChecker checker = (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IResourceChangeDescriptionFactory deltaFactory = checker.getDeltaFactory();
-
- // TODO figure out what we want to do here....
-// ResourceModifications.buildMoveDelta(deltaFactory, fKeyNode, fRenameArguments);
-
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- /**
- * Validates if the a name is valid. This method does not change the name settings on the refactoring. It is intended to be used
- * in a wizard to validate user input.
- *
- * @param newName the name to validate
- * @return returns the resulting status of the validation
- */
- public RefactoringStatus validateNewElementName(String newName) {
- Assert.isNotNull(newName);
-
- if (newName.length() == 0) {
- return RefactoringStatus.createFatalErrorStatus("New name for key must be entered");
- }
- if (newName.startsWith(".")) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot start with a '.'");
- }
- if (newName.endsWith(".")) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot end with a '.'");
- }
-
- String [] parts = newName.split("\\.");
- for (String part : parts) {
- if (part.length() == 0) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot contain an empty part between two periods");
- }
- if (!part.matches("([A-Z]|[a-z]|[0-9])*")) {
- return RefactoringStatus.createFatalErrorStatus("Key can contain only letters, digits, and periods");
- }
- }
-
- if (fMessageBundleGroup.isMessageKey(newName)) {
- return RefactoringStatus.createFatalErrorStatus(MessagesEditorPlugin.getString("dialog.error.exists"));
- }
-
- return new RefactoringStatus();
- }
-
- protected RenameKeyDescriptor createDescriptor() {
- RenameKeyDescriptor descriptor= new RenameKeyDescriptor();
- descriptor.setDescription(MessageFormat.format("Rename resource bundle key ''{0}''", fKeyNode.getMessageKey()));
- descriptor.setComment(MessageFormat.format("Rename resource ''{0}'' to ''{1}''", new Object[] { fKeyNode.getMessageKey(), fNewResourceName }));
- descriptor.setFlags(RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE);
- descriptor.setNewName(getNewResourceName());
- descriptor.setRenameChildKeys(fRenameChildKeys);
- return descriptor;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- RenameKeyChange change = new RenameKeyChange(fMessageBundleGroup, getNewKeyTreeNode(), fNewResourceName, fRenameChildKeys);
- change.setDescriptor(new RefactoringChangeDescriptor(createDescriptor()));
- return change;
- } finally {
- pm.done();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
- */
- public Object[] getElements() {
- return new Object[] { fKeyNode };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getIdentifier()
- */
- public String getIdentifier() {
- return "org.eclipse.babel.editor.refactoring.renameKeyProcessor"; //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
- */
- public String getProcessorName() {
- return "Rename Resource Bundle Key";
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
- */
- public boolean isApplicable() {
- if (this.fKeyNode == null)
- return false;
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus, org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
- */
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- // TODO: figure out participants to return here
- return new RefactoringParticipant[0];
-
-// String[] affectedNatures= ResourceProcessors.computeAffectedNatures(fResource);
-// return ParticipantManager.loadRenameParticipants(status, this, fResource, fRenameArguments, null, affectedNatures, shared);
- }
-
- /**
- * Returns <code>true</code> if the refactoring processor also renames the child keys
- *
- * @return <code>true</code> if the refactoring processor also renames the child keys
- */
- public boolean getRenameChildKeys() {
- return fRenameChildKeys;
- }
-
- /**
- * Specifies if the refactoring processor also updates the child keys.
- * The default behaviour is to update the child keys.
- *
- * @param renameChildKeys <code>true</code> if the refactoring processor should also rename the child keys
- */
- public void setRenameChildKeys(boolean renameChildKeys) {
- fRenameChildKeys = renameChildKeys;
- }
-
-}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
deleted file mode 100644
index 73d6b49e..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.refactoring;
-
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * A wizard for the rename bundle key refactoring.
- */
-public class RenameKeyWizard extends RefactoringWizard {
-
- /**
- * Creates a {@link RenameKeyWizard}.
- *
- * @param resource
- * the bundle key to rename
- * @param refactoring
- */
- public RenameKeyWizard(KeyTreeNode resource, RenameKeyProcessor refactoring) {
- super(new RenameRefactoring(refactoring), DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle("Rename Resource Bundle Key");
- setWindowTitle("Rename Resource Bundle Key");
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
- RenameKeyProcessor processor = (RenameKeyProcessor) getRefactoring().getAdapter(RenameKeyProcessor.class);
- addPage(new RenameResourceRefactoringConfigurationPage(processor));
- }
-
- private static class RenameResourceRefactoringConfigurationPage extends UserInputWizardPage {
-
- private final RenameKeyProcessor fRefactoringProcessor;
- private Text fNameField;
-
- public RenameResourceRefactoringConfigurationPage(RenameKeyProcessor processor) {
- super("RenameResourceRefactoringInputPage"); //$NON-NLS-1$
- fRefactoringProcessor= processor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setFont(parent.getFont());
-
- Label label = new Label(composite, SWT.NONE);
- label.setText("New name:");
- label.setLayoutData(new GridData());
-
- fNameField = new Text(composite, SWT.BORDER);
- fNameField.setText(fRefactoringProcessor.getNewResourceName());
- fNameField.setFont(composite.getFont());
- fNameField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
- fNameField.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
- });
-
- final Button includeChildKeysCheckbox = new Button(composite, SWT.CHECK);
- if (fRefactoringProcessor.getNewKeyTreeNode().isUsedAsKey()) {
- if (fRefactoringProcessor.getNewKeyTreeNode().getChildren().length == 0) {
- // This is an actual key with no child keys.
- includeChildKeysCheckbox.setSelection(false);
- includeChildKeysCheckbox.setEnabled(false);
- } else {
- // This is both an actual key and it has child keys, so we
- // let the user choose whether to also rename the child keys.
- includeChildKeysCheckbox.setSelection(fRefactoringProcessor.getRenameChildKeys());
- includeChildKeysCheckbox.setEnabled(true);
- }
- } else {
- // This is no an actual key, just a containing node, so the option
- // to rename child keys must be set (otherwise this rename would not
- // do anything).
- includeChildKeysCheckbox.setSelection(true);
- includeChildKeysCheckbox.setEnabled(false);
- }
-
- includeChildKeysCheckbox.setText("Also rename child keys (other keys with this key as a prefix)");
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- includeChildKeysCheckbox.setLayoutData(gd);
- includeChildKeysCheckbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- fRefactoringProcessor.setRenameChildKeys(includeChildKeysCheckbox.getSelection());
- }
- });
-
- fNameField.selectAll();
- setPageComplete(false);
- setControl(composite);
- }
-
- public void setVisible(boolean visible) {
- if (visible) {
- fNameField.setFocus();
- }
- super.setVisible(visible);
- }
-
- protected final void validatePage() {
- String text= fNameField.getText();
- RefactoringStatus status= fRefactoringProcessor.validateNewElementName(text);
- setPageComplete(status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#performFinish()
- */
- protected boolean performFinish() {
- initializeRefactoring();
- storeSettings();
- return super.performFinish();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#getNextPage()
- */
- public IWizardPage getNextPage() {
- initializeRefactoring();
- storeSettings();
- return super.getNextPage();
- }
-
- private void storeSettings() {
- }
-
- private void initializeRefactoring() {
- fRefactoringProcessor.setNewResourceName(fNameField.getText());
- }
- }
-}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java
index aa6d00bb..36008896 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java
@@ -7,13 +7,14 @@
*
* Contributors:
* Pascal Essiembre - initial API and implementation
+ * Alexej Strelzow - TapJI integration -> DirtyHack
******************************************************************************/
package org.eclipse.babel.editor.resource;
import java.util.Locale;
import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.resource.AbstractPropertiesResource;
+import org.eclipse.babel.core.message.resource.internal.AbstractPropertiesResource;
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
import org.eclipse.core.resources.IResource;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java
index 39270edb..ee9d1f39 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/FileMarkerStrategy.java
@@ -10,9 +10,9 @@
******************************************************************************/
package org.eclipse.babel.editor.resource.validator;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.checks.DuplicateValueCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
+import org.eclipse.babel.core.message.checks.internal.DuplicateValueCheck;
+import org.eclipse.babel.core.message.checks.internal.MissingValueCheck;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
import org.eclipse.babel.core.util.BabelUtils;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java
index f98c0cea..ad58478f 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.java
@@ -12,9 +12,9 @@
import java.util.Locale;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.checks.DuplicateValueCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
+import org.eclipse.babel.core.message.checks.internal.DuplicateValueCheck;
+import org.eclipse.babel.core.message.checks.internal.MissingValueCheck;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java
index a7b438e8..b49e1ded 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.java
@@ -12,8 +12,8 @@
import java.util.Locale;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
import org.eclipse.babel.core.message.checks.IMessageCheck;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
/**
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
new file mode 100644
index 00000000..e4d1bf07
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java
@@ -0,0 +1,23 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.tree;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.jface.viewers.TreeViewer;
+
+public interface IKeyTreeContributor {
+
+ void contribute(final TreeViewer treeViewer);
+
+ IKeyTreeNode getKeyTreeNode(String key);
+
+ IKeyTreeNode[] getRootKeyItems();
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeContentProvider.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeContentProvider.java
deleted file mode 100644
index b52cfec0..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeContentProvider.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.tree;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-
-/**
- * Content provider for key tree viewer.
- * @author Pascal Essiembre
- */
-public class KeyTreeContentProvider implements ITreeContentProvider {
-
- private AbstractKeyTreeModel keyTreeModel;
- private Viewer viewer;
- private TreeType treeType;
-
- /**
- * @param treeType
- *
- */
- public KeyTreeContentProvider(TreeType treeType) {
- this.treeType = treeType;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(
- * java.lang.Object)
- */
- public Object[] getChildren(Object parentElement) {
- KeyTreeNode parentNode = (KeyTreeNode) parentElement;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren(parentNode);
- case Flat:
- return new KeyTreeNode[0];
- default:
- // Should not happen
- return new KeyTreeNode[0];
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#
- * getParent(java.lang.Object)
- */
- public Object getParent(Object element) {
- KeyTreeNode node = (KeyTreeNode) element;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getParent(node);
- case Flat:
- return keyTreeModel;
- default:
- // Should not happen
- return null;
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#
- * hasChildren(java.lang.Object)
- */
- public boolean hasChildren(Object element) {
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren((KeyTreeNode) element).length > 0;
- case Flat:
- return false;
- default:
- // Should not happen
- return false;
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#
- * getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- switch (treeType) {
- case Tree:
- return 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 KeyTreeNode[0];
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- public void dispose() {}
-
- /**
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(
- * org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (TreeViewer) viewer;
- this.keyTreeModel = (AbstractKeyTreeModel) newInput;
- }
-
- public TreeType getTreeType() {
- return treeType;
- }
-
- public void setTreeType(TreeType treeType) {
- if (this.treeType != treeType) {
- this.treeType = treeType;
- viewer.refresh();
- }
- }
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeContributor.java
deleted file mode 100644
index 7b2a86fe..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeContributor.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.tree;
-
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.IKeyTreeModelListener;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.IMessagesEditorChangeListener;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipse.babel.editor.MessagesEditorMarkers;
-import org.eclipse.babel.editor.tree.actions.AddKeyAction;
-import org.eclipse.babel.editor.tree.actions.DeleteKeyAction;
-import org.eclipse.babel.editor.tree.actions.RenameKeyAction;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeContributor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class KeyTreeContributor implements IKeyTreeContributor {
-
- private MessagesEditor editor;
- private AbstractKeyTreeModel treeModel;
- private TreeType treeType;
-
- /**
- *
- */
- public KeyTreeContributor(final MessagesEditor editor) {
- super();
- this.editor = editor;
- this.treeModel = new AbstractKeyTreeModel(editor.getBundleGroup());
- this.treeType = TreeType.Tree;
- }
-
- /**
- *
- */
- public void contribute(final TreeViewer treeViewer) {
-
- KeyTreeContentProvider contentProvider = new KeyTreeContentProvider(treeType);
- treeViewer.setContentProvider(contentProvider);
- treeViewer.setLabelProvider(new KeyTreeLabelProvider(editor, treeModel, contentProvider));
- if (treeViewer.getInput() == null)
- treeViewer.setUseHashlookup(true);
-
- ViewerFilter onlyUnusedAndMissingKeysFilter = new OnlyUnsuedAndMissingKey();
- ViewerFilter[] filters = {onlyUnusedAndMissingKeysFilter};
- treeViewer.setFilters(filters);
-
-// IKeyBindingService service = editor.getSite().getKeyBindingService();
-// service.setScopes(new String[]{"org.eclilpse.babel.editor.editor.tree"});
-
- contributeActions(treeViewer);
-
- contributeKeySync(treeViewer);
-
- contributeModelChanges(treeViewer);
-
- contributeDoubleClick(treeViewer);
-
- contributeMarkers(treeViewer);
-
- // Set input model
- treeViewer.setInput(treeModel);
- treeViewer.expandAll();
- }
-
- private class OnlyUnsuedAndMissingKey extends ViewerFilter implements
- AbstractKeyTreeModel.IKeyTreeNodeLeafFilter {
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
- */
- public boolean select(Viewer viewer, Object parentElement,
- Object element) {
- if (editor.isShowOnlyUnusedAndMissingKeys() == IMessagesEditorChangeListener.SHOW_ALL
- || !(element instanceof KeyTreeNode)) {
- //no filtering. the element is displayed by default.
- return true;
- }
- if (editor.getI18NPage() != null && editor.getI18NPage().isKeyTreeVisible()) {
- return editor.getKeyTreeModel().isBranchFiltered(this, (KeyTreeNode)element);
- } else {
- return isFilteredLeaf((KeyTreeNode)element);
- }
- }
-
- /**
- * @param node
- * @return true if this node should be in the filter. Does not navigate the tree
- * of KeyTreeNode. false unless the node is a missing or unused key.
- */
- public boolean isFilteredLeaf(IKeyTreeNode node) {
- MessagesEditorMarkers markers = KeyTreeContributor.this.editor.getMarkers();
- String key = node.getMessageKey();
- boolean missingOrUnused = markers.isMissingOrUnusedKey(key);
- if (!missingOrUnused) {
- return false;
- }
- switch (editor.isShowOnlyUnusedAndMissingKeys()) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return missingOrUnused;
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return !markers.isUnusedKey(key, missingOrUnused);
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return markers.isUnusedKey(key, missingOrUnused);
- default:
- return false;
- }
- }
-
- }
-
-
- /**
- * Contributes markers.
- * @param treeViewer tree viewer
- */
- private void contributeMarkers(final TreeViewer treeViewer) {
- editor.getMarkers().addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh();
- }
- });
- }
- });
-// editor.addChangeListener(new MessagesEditorChangeAdapter() {
-// public void editorDisposed() {
-// editor.getMarkers().clear();
-// }
-// });
-
-
-
-
-
-
-
-
-// final IMarkerListener markerListener = new IMarkerListener() {
-// public void markerAdded(IMarker marker) {
-// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
-// public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
-// treeViewer.refresh(true);
-// }
-// }
-// });
-// }
-// public void markerRemoved(IMarker marker) {
-// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
-// public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
-// treeViewer.refresh(true);
-// }
-// }
-// });
-// }
-// };
-// editor.getMarkerManager().addMarkerListener(markerListener);
-// editor.addChangeListener(new MessagesEditorChangeAdapter() {
-// public void editorDisposed() {
-// editor.getMarkerManager().removeMarkerListener(markerListener);
-// }
-// });
- }
-
-
-
- /**
- * Contributes double-click support, expanding/collapsing nodes.
- * @param treeViewer tree viewer
- */
- private void contributeDoubleClick(final TreeViewer treeViewer) {
- treeViewer.getTree().addMouseListener(new MouseAdapter() {
- public void mouseDoubleClick(MouseEvent event) {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
- Object element = selection.getFirstElement();
- if (treeViewer.isExpandable(element)) {
- if (treeViewer.getExpandedState(element)) {
- treeViewer.collapseToLevel(element, 1);
- } else {
- treeViewer.expandToLevel(element, 1);
- }
- }
- }
- });
- }
-
- /**
- * Contributes key synchronization between editor and tree selected keys.
- * @param treeViewer tree viewer
- */
- private void contributeModelChanges(final TreeViewer treeViewer) {
- final IKeyTreeModelListener keyTreeListener = new IKeyTreeModelListener() {
- //TODO be smarter about refreshes.
- public void nodeAdded(KeyTreeNode node) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh(true);
- }
- });
- };
-// public void nodeChanged(KeyTreeNode node) {
-// treeViewer.refresh(true);
-// };
- public void nodeRemoved(KeyTreeNode node) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh(true);
- }
- });
- };
- };
- treeModel.addKeyTreeModelListener(keyTreeListener);
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
- oldModel.removeKeyTreeModelListener(keyTreeListener);
- newModel.addKeyTreeModelListener(keyTreeListener);
- treeViewer.setInput(newModel);
- treeViewer.refresh();
- }
- public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
- treeViewer.refresh();
- }
- });
- }
-
- /**
- * Contributes key synchronization between editor and tree selected keys.
- * @param treeViewer tree viewer
- */
- private void contributeKeySync(final TreeViewer treeViewer) {
- // changes in tree selected key update the editor
- treeViewer.getTree().addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
- if (selection != null && selection.getFirstElement() != null) {
- KeyTreeNode node =
- (KeyTreeNode) selection.getFirstElement();
- System.out.println("viewer key/hash:" + node.getMessageKey() + "/" + node.hashCode());
- editor.setSelectedKey(node.getMessageKey());
- } else {
- editor.setSelectedKey(null);
- }
- }
- });
- // changes in editor selected key updates the tree
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void selectedKeyChanged(String oldKey, String newKey) {
- ITreeContentProvider provider =
- (ITreeContentProvider) treeViewer.getContentProvider();
- if (provider != null) { // alst workaround
- KeyTreeNode node = findKeyTreeNode(
- provider, provider.getElements(null), newKey);
-
- // String[] test = newKey.split("\\.");
- // treeViewer.setSelection(new StructuredSelection(test), true);
-
-
- if (node != null) {
- treeViewer.setSelection(new StructuredSelection(node),
- true);
- treeViewer.getTree().showSelection();
- }
- }
- }
- });
- }
-
-
-
- /**
- * Contributes actions to the tree.
- * @param treeViewer tree viewer
- */
- private void contributeActions(final TreeViewer treeViewer) {
- Tree tree = treeViewer.getTree();
-
- // Add menu
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(tree);
-
- // Add
- final IAction addAction = new AddKeyAction(editor, treeViewer);
- menuManager.add(addAction);
- // Delete
- final IAction deleteAction = new DeleteKeyAction(editor, treeViewer);
- menuManager.add(deleteAction);
- // Rename
- final IAction renameAction = new RenameKeyAction(editor, treeViewer);
- menuManager.add(renameAction);
-
- menuManager.update(true);
- tree.setMenu(menu);
-
- // Bind actions to tree
- tree.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- if (event.character == SWT.DEL) {
- deleteAction.run();
- } else if (event.keyCode == SWT.F2) {
- renameAction.run();
- }
- }
- });
- }
-
- private KeyTreeNode findKeyTreeNode(
- ITreeContentProvider provider, Object[] nodes, String key) {
- for (int i = 0; i < nodes.length; i++) {
- KeyTreeNode node = (KeyTreeNode) nodes[i];
- if (node.getMessageKey().equals(key)) {
- return node;
- }
- node = findKeyTreeNode(provider, provider.getChildren(node), key);
- if (node != null) {
- return node;
- }
- }
- return null;
- }
-
- public IKeyTreeNode getKeyTreeNode(String key) {
- return getKeyTreeNode(key, null);
- }
-
- // TODO, think about a hashmap
- private IKeyTreeNode getKeyTreeNode(String key, IKeyTreeNode node) {
- if (node == null) {
- for (IKeyTreeNode ktn : treeModel.getRootNodes()) {
- String id = ktn.getMessageKey();
- if (key.equals(id)) {
- return ktn;
- } else {
- getKeyTreeNode(key, ktn);
- }
- }
- } else {
- for (IKeyTreeNode ktn : node.getChildren()) {
- String id = ktn.getMessageKey();
- if (key.equals(id)) {
- return ktn;
- } else {
- getKeyTreeNode(key, ktn);
- }
- }
- }
- return null;
- }
-
- public IKeyTreeNode[] getRootKeyItems() {
- return treeModel.getRootNodes();
- }
-
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeLabelProvider.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeLabelProvider.java
deleted file mode 100644
index f2c8c7e7..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/KeyTreeLabelProvider.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.tree;
-
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.checks.IMessageCheck;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.MessagesEditorMarkers;
-import org.eclipse.babel.editor.util.OverlayImageIcon;
-import org.eclipse.babel.editor.util.UIUtils;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.IFontProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-/**
- * Label provider for key tree viewer.
- * @author Pascal Essiembre
- */
-public class KeyTreeLabelProvider
- extends LabelProvider implements IFontProvider, IColorProvider {
-
- private static final int KEY_DEFAULT = 1 << 1;
- private static final int KEY_COMMENTED = 1 << 2;
- private static final int KEY_VIRTUAL = 1 << 3;
- private static final int BADGE_WARNING = 1 << 4;
- private static final int BADGE_WARNING_GREY = 1 << 5;
-
- /** Registry instead of UIUtils one for image not keyed by file name. */
- private static ImageRegistry imageRegistry = new ImageRegistry();
-
-
- private MessagesEditor editor;
- private MessagesBundleGroup messagesBundleGroup;
-
- /**
- * This label provider keeps a reference to the content provider.
- * This is only because the way the nodes are labeled depends on whether
- * the node is being displayed in a tree or a flat structure.
- * <P>
- * This label provider does not have to listen to changes in the tree/flat
- * selection because such a change would cause the content provider to do
- * a full refresh anyway.
- */
- private KeyTreeContentProvider contentProvider;
-
- /**
- *
- */
- public KeyTreeLabelProvider(
- MessagesEditor editor,
- AbstractKeyTreeModel treeModel,
- KeyTreeContentProvider contentProvider) {
- super();
- this.editor = editor;
- this.messagesBundleGroup = editor.getBundleGroup();
- this.contentProvider = contentProvider;
- }
-
- /**
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- if (element instanceof KeyTreeNode) {
- KeyTreeNode node = (KeyTreeNode)element;
- Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(node.getMessageKey());
- if (c == null || c.isEmpty()) {
- return UIUtils.getImage(UIUtils.IMAGE_KEY);
- }
- boolean isMissingOrUnused = editor.getMarkers().isMissingOrUnusedKey(node.getMessageKey());
- if (isMissingOrUnused) {
- if (editor.getMarkers().isUnusedKey(node.getMessageKey(), isMissingOrUnused)) {
- return UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
- } else {
- return UIUtils.getImage(UIUtils.IMAGE_MISSING_TRANSLATION);
- }
- } else {
- return UIUtils.getImage(UIUtils.IMAGE_WARNED_TRANSLATION);
- }
- } else {
-/* // Figure out background icon
- if (messagesBundleGroup.isMessageKey(key)) {
- //TODO create check (or else)
-// if (!noInactiveKeyCheck.checkKey(messagesBundleGroup, node.getPath())) {
-// iconFlags += KEY_COMMENTED;
-// } else {
- iconFlags += KEY_DEFAULT;
-
-// }
- } else {
- iconFlags += KEY_VIRTUAL;
- }*/
- return UIUtils.getImage(UIUtils.IMAGE_KEY);
- }
-
- }
-
-
- /**
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- /*
- * We look to the content provider to see if the node is being
- * displayed in flat or tree mode.
- */
- KeyTreeNode node = (KeyTreeNode) element;
- switch (contentProvider.getTreeType()) {
- case Tree:
- return node.getName();
- case Flat:
- return node.getMessageKey();
- default:
- // Should not happen
- return "error";
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
- */
- public void dispose() {
-//TODO imageRegistry.dispose(); could do if version 3.1
- }
-
- /**
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- return null;
- }
-
- /**
- * Generates an image based on icon flags.
- * @param iconFlags
- * @return generated image
- */
- private Image generateImage(int iconFlags) {
- Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
- if (image == null) {
- // Figure background image
- if ((iconFlags & KEY_COMMENTED) != 0) {
- image = getRegistryImage("keyCommented.png"); //$NON-NLS-1$
- } else if ((iconFlags & KEY_VIRTUAL) != 0) {
- image = getRegistryImage("keyVirtual.png"); //$NON-NLS-1$
- } else {
- image = getRegistryImage("keyDefault.png"); //$NON-NLS-1$
- }
-
- // Add warning icon
- if ((iconFlags & BADGE_WARNING) != 0) {
- image = overlayImage(image, "warning.gif", //$NON-NLS-1$
- OverlayImageIcon.BOTTOM_RIGHT, iconFlags);
- } else if ((iconFlags & BADGE_WARNING_GREY) != 0) {
- image = overlayImage(image, "warningGrey.gif", //$NON-NLS-1$
- OverlayImageIcon.BOTTOM_RIGHT, iconFlags);
- }
- }
- return image;
- }
-
- private Image overlayImage(
- Image baseImage, String imageName, int location, int iconFlags) {
- /* To obtain a unique key, we assume here that the baseImage and
- * location are always the same for each imageName and keyFlags
- * combination.
- */
- String imageKey = imageName + iconFlags;
- Image image = imageRegistry.get(imageKey);
- if (image == null) {
- image = new OverlayImageIcon(baseImage, getRegistryImage(
- imageName), location).createImage();
- imageRegistry.put(imageKey, image);
- }
- return image;
- }
-
- private Image getRegistryImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = UIUtils.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-
- private boolean isOneChildrenMarked(IKeyTreeNode parentNode) {
- MessagesEditorMarkers markers = editor.getMarkers();
- IKeyTreeNode[] childNodes =
- editor.getKeyTreeModel().getChildren(parentNode);
- for (int i = 0; i < childNodes.length; i++) {
- IKeyTreeNode node = childNodes[i];
- if (markers.isMarked(node.getMessageKey())) {
- return true;
- }
- if (isOneChildrenMarked(node)) {
- return true;
- }
- }
- return false;
- }
-
-
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractRenameKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractRenameKeyAction.java
new file mode 100644
index 00000000..cf142b41
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractRenameKeyAction.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.tree.actions;
+
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
+import org.eclipse.babel.editor.util.UIUtils;
+import org.eclipse.jface.viewers.TreeViewer;
+
+/**
+ * @author Pascal Essiembre
+ *
+ */
+public abstract class AbstractRenameKeyAction extends AbstractTreeAction {
+
+
+ public static final String INSTANCE_CLASS = "org.eclipse.babel.editor.tree.actions.RenameKeyAction";
+
+ public AbstractRenameKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
+ super(editor, treeViewer);
+ setText(MessagesEditorPlugin.getString("key.rename") + " ..."); //$NON-NLS-1$
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_RENAME));
+ setToolTipText("TODO put something here"); // TODO put tooltip
+ }
+
+ /**
+ * @see org.eclipse.jface.action.Action#run()
+ */
+ @Override
+ public abstract void run();
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java
index 5dcea4b5..44cae78c 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java
@@ -10,10 +10,10 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java
index 3167aa30..ef192c3a 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.java
@@ -10,9 +10,9 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.dialogs.IInputValidator;
@@ -22,7 +22,7 @@
/**
* @author Pascal Essiembre
- *
+ *
*/
public class AddKeyAction extends AbstractTreeAction {
@@ -30,38 +30,37 @@ public class AddKeyAction extends AbstractTreeAction {
*
*/
public AddKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.add")); //$NON-NLS-1$
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_ADD));
- setToolTipText("TODO put something here"); //TODO put tooltip
+ super(editor, treeViewer);
+ setText(MessagesEditorPlugin.getString("key.add") + " ..."); //$NON-NLS-1$
+ setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_ADD));
+ setToolTipText("TODO put something here"); // TODO put tooltip
}
-
/**
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
- KeyTreeNode node = getNodeSelection();
- String key = node.getMessageKey();
- String msgHead = MessagesEditorPlugin.getString("dialog.add.head");
- String msgBody = MessagesEditorPlugin.getString("dialog.add.body");
- InputDialog dialog = new InputDialog(
- getShell(), msgHead, msgBody, key, new IInputValidator() {
- public String isValid(String newText) {
- if (getBundleGroup().isMessageKey(newText)) {
- return MessagesEditorPlugin.getString(
- "dialog.error.exists");
- }
- return null;
- }
- });
- dialog.open();
- if (dialog.getReturnCode() == Window.OK ) {
- String inputKey = dialog.getValue();
- MessagesBundleGroup messagesBundleGroup = getBundleGroup();
- messagesBundleGroup.addMessages(inputKey);
- }
+ KeyTreeNode node = getNodeSelection();
+ String key = node.getMessageKey();
+ String msgHead = MessagesEditorPlugin.getString("dialog.add.head");
+ String msgBody = MessagesEditorPlugin.getString("dialog.add.body");
+ InputDialog dialog = new InputDialog(getShell(), msgHead, msgBody, key,
+ new IInputValidator() {
+ public String isValid(String newText) {
+ if (getBundleGroup().isMessageKey(newText)) {
+ return MessagesEditorPlugin
+ .getString("dialog.error.exists");
+ }
+ return null;
+ }
+ });
+ dialog.open();
+ if (dialog.getReturnCode() == Window.OK) {
+ String inputKey = dialog.getValue();
+ MessagesBundleGroup messagesBundleGroup = getBundleGroup();
+ messagesBundleGroup.addMessages(inputKey);
+ }
}
-
-
+
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java
index b4f2708e..39057f1a 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.java
@@ -10,7 +10,7 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.viewers.TreeViewer;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java
index dfcec4cd..2c02ef83 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/DeleteKeyAction.java
@@ -10,9 +10,9 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java
index 6f6cbdfe..825c3988 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java
@@ -10,7 +10,7 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.viewers.TreeViewer;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java
index 637b7ce6..6beffea2 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.java
@@ -10,13 +10,13 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.babel.editor.tree.KeyTreeContentProvider;
+import org.eclipse.babel.editor.tree.internal.KeyTreeContentProvider;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
/**
* @author Pascal Essiembre
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
deleted file mode 100644
index e77d9883..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.tree.actions;
-
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.babel.editor.refactoring.RenameKeyProcessor;
-import org.eclipse.babel.editor.refactoring.RenameKeyWizard;
-import org.eclipse.babel.editor.util.UIUtils;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class RenameKeyAction extends AbstractTreeAction {
-
- /**
- *
- */
- public RenameKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.rename")); //$NON-NLS-1$
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_RENAME));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- KeyTreeNode node = getNodeSelection();
-
- // Rename single item
- RenameKeyProcessor refactoring = new RenameKeyProcessor(node, getBundleGroup());
-
- RefactoringWizard wizard = new RenameKeyWizard(node, refactoring);
- try {
- RefactoringWizardOpenOperation operation= new RefactoringWizardOpenOperation(wizard);
- operation.run(getShell(), "Introduce Indirection");
- } catch (InterruptedException exception) {
- // Do nothing
- }
- }
-}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java
index 5f4017aa..4d95e9d8 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.java
@@ -10,13 +10,13 @@
******************************************************************************/
package org.eclipse.babel.editor.tree.actions;
-import org.eclipse.babel.editor.MessagesEditor;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.babel.editor.tree.KeyTreeContentProvider;
+import org.eclipse.babel.editor.tree.internal.KeyTreeContentProvider;
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
/**
* @author Pascal Essiembre
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java
new file mode 100644
index 00000000..ff039893
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java
@@ -0,0 +1,144 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.tree.internal;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+
+
+/**
+ * Content provider for key tree viewer.
+ * @author Pascal Essiembre
+ */
+public class KeyTreeContentProvider implements ITreeContentProvider {
+
+ private AbstractKeyTreeModel keyTreeModel;
+ private Viewer viewer;
+ private TreeType treeType;
+
+ /**
+ * @param treeType
+ *
+ */
+ public KeyTreeContentProvider(TreeType treeType) {
+ this.treeType = treeType;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(
+ * java.lang.Object)
+ */
+ public Object[] getChildren(Object parentElement) {
+ KeyTreeNode parentNode = (KeyTreeNode) parentElement;
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getChildren(parentNode);
+ case Flat:
+ return new KeyTreeNode[0];
+ default:
+ // Should not happen
+ return new KeyTreeNode[0];
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#
+ * getParent(java.lang.Object)
+ */
+ public Object getParent(Object element) {
+ KeyTreeNode node = (KeyTreeNode) element;
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getParent(node);
+ case Flat:
+ return keyTreeModel;
+ default:
+ // Should not happen
+ return null;
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#
+ * hasChildren(java.lang.Object)
+ */
+ public boolean hasChildren(Object element) {
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getChildren((KeyTreeNode) element).length > 0;
+ case Flat:
+ return false;
+ default:
+ // Should not happen
+ return false;
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IStructuredContentProvider#
+ * getElements(java.lang.Object)
+ */
+ public Object[] getElements(Object inputElement) {
+ switch (treeType) {
+ case Tree:
+ return 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 KeyTreeNode[0];
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IContentProvider#dispose()
+ */
+ public void dispose() {}
+
+ /**
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(
+ * org.eclipse.jface.viewers.Viewer,
+ * java.lang.Object, java.lang.Object)
+ */
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ this.viewer = (TreeViewer) viewer;
+ this.keyTreeModel = (AbstractKeyTreeModel) newInput;
+ }
+
+ public TreeType getTreeType() {
+ return treeType;
+ }
+
+ public void setTreeType(TreeType treeType) {
+ if (this.treeType != treeType) {
+ this.treeType = treeType;
+ viewer.refresh();
+ }
+ }
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java
new file mode 100644
index 00000000..9493bb85
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java
@@ -0,0 +1,411 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.tree.internal;
+
+import java.lang.reflect.Constructor;
+import java.util.Observable;
+import java.util.Observer;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.internal.IKeyTreeModelListener;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.IMessagesEditorChangeListener;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter;
+import org.eclipse.babel.editor.internal.MessagesEditorMarkers;
+import org.eclipse.babel.editor.tree.IKeyTreeContributor;
+import org.eclipse.babel.editor.tree.actions.AddKeyAction;
+import org.eclipse.babel.editor.tree.actions.DeleteKeyAction;
+import org.eclipse.babel.editor.tree.actions.AbstractRenameKeyAction;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.ui.IWorkbenchWindow;
+
+/**
+ * @author Pascal Essiembre
+ *
+ */
+public class KeyTreeContributor implements IKeyTreeContributor {
+
+ private MessagesEditor editor;
+ private AbstractKeyTreeModel treeModel;
+ private TreeType treeType;
+
+ /**
+ *
+ */
+ public KeyTreeContributor(final MessagesEditor editor) {
+ super();
+ this.editor = editor;
+ this.treeModel = new AbstractKeyTreeModel(editor.getBundleGroup());
+ this.treeType = TreeType.Tree;
+ }
+
+ /**
+ *
+ */
+ public void contribute(final TreeViewer treeViewer) {
+
+ KeyTreeContentProvider contentProvider = new KeyTreeContentProvider(treeType);
+ treeViewer.setContentProvider(contentProvider);
+ ColumnViewerToolTipSupport.enableFor (treeViewer);
+ treeViewer.setLabelProvider(new KeyTreeLabelProvider(editor, treeModel, contentProvider));
+ if (treeViewer.getInput() == null)
+ treeViewer.setUseHashlookup(true);
+
+ ViewerFilter onlyUnusedAndMissingKeysFilter = new OnlyUnsuedAndMissingKey();
+ ViewerFilter[] filters = {onlyUnusedAndMissingKeysFilter};
+ treeViewer.setFilters(filters);
+
+// IKeyBindingService service = editor.getSite().getKeyBindingService();
+// service.setScopes(new String[]{"org.eclilpse.babel.editor.editor.tree"});
+
+ contributeActions(treeViewer);
+
+ contributeKeySync(treeViewer);
+
+ contributeModelChanges(treeViewer);
+
+ contributeDoubleClick(treeViewer);
+
+ contributeMarkers(treeViewer);
+
+ // Set input model
+ treeViewer.setInput(treeModel);
+ treeViewer.expandAll();
+ }
+
+ private class OnlyUnsuedAndMissingKey extends ViewerFilter implements
+ AbstractKeyTreeModel.IKeyTreeNodeLeafFilter {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
+ * java.lang.Object, java.lang.Object)
+ */
+ public boolean select(Viewer viewer, Object parentElement,
+ Object element) {
+ if (editor.isShowOnlyUnusedAndMissingKeys() == IMessagesEditorChangeListener.SHOW_ALL
+ || !(element instanceof KeyTreeNode)) {
+ //no filtering. the element is displayed by default.
+ return true;
+ }
+ if (editor.getI18NPage() != null && editor.getI18NPage().isKeyTreeVisible()) {
+ return editor.getKeyTreeModel().isBranchFiltered(this, (KeyTreeNode)element);
+ } else {
+ return isFilteredLeaf((KeyTreeNode)element);
+ }
+ }
+
+ /**
+ * @param node
+ * @return true if this node should be in the filter. Does not navigate the tree
+ * of KeyTreeNode. false unless the node is a missing or unused key.
+ */
+ public boolean isFilteredLeaf(IKeyTreeNode node) {
+ MessagesEditorMarkers markers = KeyTreeContributor.this.editor.getMarkers();
+ String key = node.getMessageKey();
+ boolean missingOrUnused = markers.isMissingOrUnusedKey(key);
+ if (!missingOrUnused) {
+ return false;
+ }
+ switch (editor.isShowOnlyUnusedAndMissingKeys()) {
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
+ return missingOrUnused;
+ case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
+ return !markers.isUnusedKey(key, missingOrUnused);
+ case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
+ return markers.isUnusedKey(key, missingOrUnused);
+ default:
+ return false;
+ }
+ }
+
+ }
+
+
+ /**
+ * Contributes markers.
+ * @param treeViewer tree viewer
+ */
+ private void contributeMarkers(final TreeViewer treeViewer) {
+ editor.getMarkers().addObserver(new Observer() {
+ public void update(Observable o, Object arg) {
+ Display.getDefault().asyncExec(new Runnable(){
+ public void run() {
+ treeViewer.refresh();
+ }
+ });
+ }
+ });
+// editor.addChangeListener(new MessagesEditorChangeAdapter() {
+// public void editorDisposed() {
+// editor.getMarkers().clear();
+// }
+// });
+
+
+
+
+
+
+
+
+// final IMarkerListener markerListener = new IMarkerListener() {
+// public void markerAdded(IMarker marker) {
+// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
+// public void run() {
+// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
+// treeViewer.refresh(true);
+// }
+// }
+// });
+// }
+// public void markerRemoved(IMarker marker) {
+// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
+// public void run() {
+// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
+// treeViewer.refresh(true);
+// }
+// }
+// });
+// }
+// };
+// editor.getMarkerManager().addMarkerListener(markerListener);
+// editor.addChangeListener(new MessagesEditorChangeAdapter() {
+// public void editorDisposed() {
+// editor.getMarkerManager().removeMarkerListener(markerListener);
+// }
+// });
+ }
+
+
+
+ /**
+ * Contributes double-click support, expanding/collapsing nodes.
+ * @param treeViewer tree viewer
+ */
+ private void contributeDoubleClick(final TreeViewer treeViewer) {
+ treeViewer.getTree().addMouseListener(new MouseAdapter() {
+ public void mouseDoubleClick(MouseEvent event) {
+ IStructuredSelection selection =
+ (IStructuredSelection) treeViewer.getSelection();
+ Object element = selection.getFirstElement();
+ if (treeViewer.isExpandable(element)) {
+ if (treeViewer.getExpandedState(element)) {
+ treeViewer.collapseToLevel(element, 1);
+ } else {
+ treeViewer.expandToLevel(element, 1);
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Contributes key synchronization between editor and tree selected keys.
+ * @param treeViewer tree viewer
+ */
+ private void contributeModelChanges(final TreeViewer treeViewer) {
+ final IKeyTreeModelListener keyTreeListener = new IKeyTreeModelListener() {
+ //TODO be smarter about refreshes.
+ public void nodeAdded(KeyTreeNode node) {
+ Display.getDefault().asyncExec(new Runnable(){
+ public void run() {
+ treeViewer.refresh(true);
+ }
+ });
+ };
+// public void nodeChanged(KeyTreeNode node) {
+// treeViewer.refresh(true);
+// };
+ public void nodeRemoved(KeyTreeNode node) {
+ Display.getDefault().asyncExec(new Runnable(){
+ public void run() {
+ treeViewer.refresh(true);
+ }
+ });
+ };
+ };
+ treeModel.addKeyTreeModelListener(keyTreeListener);
+ editor.addChangeListener(new MessagesEditorChangeAdapter() {
+ public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
+ oldModel.removeKeyTreeModelListener(keyTreeListener);
+ newModel.addKeyTreeModelListener(keyTreeListener);
+ treeViewer.setInput(newModel);
+ treeViewer.refresh();
+ }
+ public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
+ treeViewer.refresh();
+ }
+ });
+ }
+
+ /**
+ * Contributes key synchronization between editor and tree selected keys.
+ * @param treeViewer tree viewer
+ */
+ private void contributeKeySync(final TreeViewer treeViewer) {
+ // changes in tree selected key update the editor
+ treeViewer.getTree().addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ IStructuredSelection selection =
+ (IStructuredSelection) treeViewer.getSelection();
+ if (selection != null && selection.getFirstElement() != null) {
+ KeyTreeNode node =
+ (KeyTreeNode) selection.getFirstElement();
+ System.out.println("viewer key/hash:" + node.getMessageKey() + "/" + node.hashCode());
+ editor.setSelectedKey(node.getMessageKey());
+ } else {
+ editor.setSelectedKey(null);
+ }
+ }
+ });
+ // changes in editor selected key updates the tree
+ editor.addChangeListener(new MessagesEditorChangeAdapter() {
+ public void selectedKeyChanged(String oldKey, String newKey) {
+ ITreeContentProvider provider =
+ (ITreeContentProvider) treeViewer.getContentProvider();
+ if (provider != null) { // alst workaround
+ KeyTreeNode node = findKeyTreeNode(
+ provider, provider.getElements(null), newKey);
+
+ // String[] test = newKey.split("\\.");
+ // treeViewer.setSelection(new StructuredSelection(test), true);
+
+
+ if (node != null) {
+ treeViewer.setSelection(new StructuredSelection(node),
+ true);
+ treeViewer.getTree().showSelection();
+ }
+ }
+ }
+ });
+ }
+
+
+
+ /**
+ * Contributes actions to the tree.
+ * @param treeViewer tree viewer
+ */
+ private void contributeActions(final TreeViewer treeViewer) {
+ Tree tree = treeViewer.getTree();
+
+ // Add menu
+ MenuManager menuManager = new MenuManager();
+ Menu menu = menuManager.createContextMenu(tree);
+
+ // Add
+ final IAction addAction = new AddKeyAction(editor, treeViewer);
+ menuManager.add(addAction);
+ // Delete
+ final IAction deleteAction = new DeleteKeyAction(editor, treeViewer);
+ menuManager.add(deleteAction);
+ // Rename
+ //final IAction renameAction = new RenameKeyAction(editor, treeViewer);
+ AbstractRenameKeyAction renameKeyAction = null;
+ try {
+ Class<?> clazz = Class
+ .forName(AbstractRenameKeyAction.INSTANCE_CLASS);
+ Constructor<?> cons = clazz.getConstructor(MessagesEditor.class, TreeViewer.class);
+ renameKeyAction = (AbstractRenameKeyAction) cons
+ .newInstance(editor, treeViewer);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ final IAction renameAction = renameKeyAction;
+ menuManager.add(renameAction);
+
+ menuManager.update(true);
+ tree.setMenu(menu);
+
+ // Bind actions to tree
+ tree.addKeyListener(new KeyAdapter() {
+ public void keyReleased(KeyEvent event) {
+ if (event.character == SWT.DEL) {
+ deleteAction.run();
+ } else if (event.keyCode == SWT.F2) {
+ renameAction.run();
+ }
+ }
+ });
+ }
+
+ private KeyTreeNode findKeyTreeNode(
+ ITreeContentProvider provider, Object[] nodes, String key) {
+ for (int i = 0; i < nodes.length; i++) {
+ KeyTreeNode node = (KeyTreeNode) nodes[i];
+ if (node.getMessageKey().equals(key)) {
+ return node;
+ }
+ node = findKeyTreeNode(provider, provider.getChildren(node), key);
+ if (node != null) {
+ return node;
+ }
+ }
+ return null;
+ }
+
+ public IKeyTreeNode getKeyTreeNode(String key) {
+ return getKeyTreeNode(key, null);
+ }
+
+ // TODO, think about a hashmap
+ private IKeyTreeNode getKeyTreeNode(String key, IKeyTreeNode node) {
+ if (node == null) {
+ for (IKeyTreeNode ktn : treeModel.getRootNodes()) {
+ String id = ktn.getMessageKey();
+ if (key.equals(id)) {
+ return ktn;
+ } else {
+ getKeyTreeNode(key, ktn);
+ }
+ }
+ } else {
+ for (IKeyTreeNode ktn : node.getChildren()) {
+ String id = ktn.getMessageKey();
+ if (key.equals(id)) {
+ return ktn;
+ } else {
+ getKeyTreeNode(key, ktn);
+ }
+ }
+ }
+ return null;
+ }
+
+ public IKeyTreeNode[] getRootKeyItems() {
+ return treeModel.getRootNodes();
+ }
+
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java
new file mode 100644
index 00000000..d6d67174
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java
@@ -0,0 +1,271 @@
+/*******************************************************************************
+ * Copyright (c) 2007 Pascal Essiembre.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Pascal Essiembre - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.editor.tree.internal;
+
+import java.util.Collection;
+
+import org.eclipse.babel.core.message.checks.IMessageCheck;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.internal.KeyTreeNode;
+import org.eclipse.babel.editor.internal.MessagesEditor;
+import org.eclipse.babel.editor.internal.MessagesEditorMarkers;
+import org.eclipse.babel.editor.util.OverlayImageIcon;
+import org.eclipse.babel.editor.util.UIUtils;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.DecorationOverlayIcon;
+import org.eclipse.jface.viewers.IColorProvider;
+import org.eclipse.jface.viewers.IDecoration;
+import org.eclipse.jface.viewers.IFontProvider;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Label provider for key tree viewer.
+ * @author Pascal Essiembre
+ */
+public class KeyTreeLabelProvider
+ extends ColumnLabelProvider implements IFontProvider, IColorProvider {
+
+ private static final int KEY_DEFAULT = 1 << 1;
+ private static final int KEY_COMMENTED = 1 << 2;
+ private static final int KEY_VIRTUAL = 1 << 3;
+ private static final int BADGE_WARNING = 1 << 4;
+ private static final int BADGE_WARNING_GREY = 1 << 5;
+
+ /** Registry instead of UIUtils one for image not keyed by file name. */
+ private static ImageRegistry imageRegistry = new ImageRegistry();
+
+
+ private MessagesEditor editor;
+ private MessagesBundleGroup messagesBundleGroup;
+
+ /**
+ * This label provider keeps a reference to the content provider.
+ * This is only because the way the nodes are labeled depends on whether
+ * the node is being displayed in a tree or a flat structure.
+ * <P>
+ * This label provider does not have to listen to changes in the tree/flat
+ * selection because such a change would cause the content provider to do
+ * a full refresh anyway.
+ */
+ private KeyTreeContentProvider contentProvider;
+
+ /**
+ *
+ */
+ public KeyTreeLabelProvider(
+ MessagesEditor editor,
+ AbstractKeyTreeModel treeModel,
+ KeyTreeContentProvider contentProvider) {
+ super();
+ this.editor = editor;
+ this.messagesBundleGroup = editor.getBundleGroup();
+ this.contentProvider = contentProvider;
+ }
+
+ /**
+ * @see ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ if (element instanceof KeyTreeNode) {
+ KeyTreeNode node = (KeyTreeNode)element;
+ Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(node.getMessageKey());
+ if (c == null || c.isEmpty()) {
+ // Return the default key image as no issue exists
+ return UIUtils.getKeyImage();
+ }
+ if (editor.getMarkers().isUnusedKey(node.getMessageKey(), false)) {
+ if (editor.getMarkers().isMissingKey(node.getMessageKey())){
+ return UIUtils.getMissingAndUnusedTranslationsImage();
+ } else if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
+ return UIUtils.getDuplicateEntryAndUnusedTranslationsImage();
+ }
+ return UIUtils.getUnusedTranslationsImage();
+ } else if (editor.getMarkers().isMissingKey(node.getMessageKey())){
+ return UIUtils.getMissingTranslationImage();
+ } else if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
+ return UIUtils.getDuplicateEntryImage();
+ }
+
+ // This shouldnt happen, but just in case a default key with a warning icon will be showed
+ Image someWarning = UIUtils.getKeyImage();
+ ImageDescriptor warning = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_WARNING));
+ someWarning = new DecorationOverlayIcon(someWarning, warning, IDecoration.BOTTOM_RIGHT).createImage();
+ return someWarning;
+ //return UIUtils.getImage(UIUtils.IMAGE_WARNED_TRANSLATION);
+ } else {
+/* // Figure out background icon
+ if (messagesBundleGroup.isMessageKey(key)) {
+ //TODO create check (or else)
+// if (!noInactiveKeyCheck.checkKey(messagesBundleGroup, node.getPath())) {
+// iconFlags += KEY_COMMENTED;
+// } else {
+ iconFlags += KEY_DEFAULT;
+
+// }
+ } else {
+ iconFlags += KEY_VIRTUAL;
+ }*/
+
+ return UIUtils.getKeyImage();
+
+ }
+ }
+
+
+ /**
+ * @see ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ /*
+ * We look to the content provider to see if the node is being
+ * displayed in flat or tree mode.
+ */
+ KeyTreeNode node = (KeyTreeNode) element;
+ switch (contentProvider.getTreeType()) {
+ case Tree:
+ return node.getName();
+ case Flat:
+ return node.getMessageKey();
+ default:
+ // Should not happen
+ return "error";
+ }
+ }
+
+ public String getToolTipText(Object element) {
+ if (element instanceof KeyTreeNode) {
+ KeyTreeNode node = (KeyTreeNode)element;
+ Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(node.getMessageKey());
+ if (c == null || c.isEmpty()) {
+ return null;
+ }
+ boolean isMissingOrUnused = editor.getMarkers().isMissingOrUnusedKey(node.getMessageKey());
+ if (isMissingOrUnused) {
+ if (editor.getMarkers().isUnusedKey(node.getMessageKey(), isMissingOrUnused)) {
+ return "This Locale is unused";
+ } else {
+ return "This Locale has missing translations";
+ }
+ }
+ if (editor.getMarkers().isDuplicateValue(node.getMessageKey())) {
+ return "This Locale has a duplicate value";
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+//TODO imageRegistry.dispose(); could do if version 3.1
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
+ */
+ public Font getFont(Object element) {
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
+ */
+ public Color getForeground(Object element) {
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
+ */
+ public Color getBackground(Object element) {
+ return null;
+ }
+
+ /**
+ * Generates an image based on icon flags.
+ * @param iconFlags
+ * @return generated image
+ */
+ private Image generateImage(int iconFlags) {
+ Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
+ if (image == null) {
+ // Figure background image
+ if ((iconFlags & KEY_COMMENTED) != 0) {
+ image = getRegistryImage("keyCommented.png"); //$NON-NLS-1$
+ } else if ((iconFlags & KEY_VIRTUAL) != 0) {
+ image = getRegistryImage("keyVirtual.png"); //$NON-NLS-1$
+ } else {
+ image = getRegistryImage("keyDefault.png"); //$NON-NLS-1$
+ }
+
+ // Add warning icon
+ if ((iconFlags & BADGE_WARNING) != 0) {
+ image = overlayImage(image, "warning.gif", //$NON-NLS-1$
+ OverlayImageIcon.BOTTOM_RIGHT, iconFlags);
+ } else if ((iconFlags & BADGE_WARNING_GREY) != 0) {
+ image = overlayImage(image, "warningGrey.gif", //$NON-NLS-1$
+ OverlayImageIcon.BOTTOM_RIGHT, iconFlags);
+ }
+ }
+ return image;
+ }
+
+ private Image overlayImage(
+ Image baseImage, String imageName, int location, int iconFlags) {
+ /* To obtain a unique key, we assume here that the baseImage and
+ * location are always the same for each imageName and keyFlags
+ * combination.
+ */
+ String imageKey = imageName + iconFlags;
+ Image image = imageRegistry.get(imageKey);
+ if (image == null) {
+ image = new OverlayImageIcon(baseImage, getRegistryImage(
+ imageName), location).createImage();
+ imageRegistry.put(imageKey, image);
+ }
+ return image;
+ }
+
+ private Image getRegistryImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = UIUtils.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
+
+ private boolean isOneChildrenMarked(IKeyTreeNode parentNode) {
+ MessagesEditorMarkers markers = editor.getMarkers();
+ IKeyTreeNode[] childNodes =
+ editor.getKeyTreeModel().getChildren(parentNode);
+ for (int i = 0; i < childNodes.length; i++) {
+ IKeyTreeNode node = childNodes[i];
+ if (markers.isMarked(node.getMessageKey())) {
+ return true;
+ }
+ if (isOneChildrenMarked(node)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java
index 7c8755a5..08e1b332 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java
@@ -27,16 +27,20 @@
import java.util.Locale;
import java.util.Set;
+import org.eclipse.babel.editor.compat.MySWT;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.jface.viewers.DecorationOverlayIcon;
+import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
@@ -100,22 +104,30 @@ public final class UIUtils {
public static final String IMAGE_EMPTY =
"empty.gif"; //$NON-NLS-1$
public static final String IMAGE_MISSING_TRANSLATION =
- "missing_translation.png"; //$NON-NLS-1$
+ "missing_translation.gif"; //$NON-NLS-1$
public static final String IMAGE_UNUSED_TRANSLATION =
"unused_translation.png"; //$NON-NLS-1$
public static final String IMAGE_UNUSED_AND_MISSING_TRANSLATIONS =
"unused_and_missing_translations.png"; //$NON-NLS-1$
public static final String IMAGE_WARNED_TRANSLATION =
"warned_translation.png"; //$NON-NLS-1$
+ public static final String IMAGE_DUPLICATE =
+ "duplicate.gif"; //$NON-NLS-1$
+
+ public static final String IMAGE_WARNING =
+ "warning.gif"; //$NON-NLS-1$
+ public static final String IMAGE_ERROR =
+ "error_co.gif"; //$NON-NLS-1$
+
/** Image registry. */
- private static final ImageRegistry imageRegistry =
+ private static ImageRegistry imageRegistry;
//TODO: REMOVE this comment eventually:
//necessary to specify the display otherwise Display.getCurrent()
//is called and will return null if this is not the UI-thread.
//this happens if the builder is called and initialize this class:
//the thread will not be the UI-thread.
- new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
+ //new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
public static final String PDE_NATURE = "org.eclipse.pde.PluginNature"; //$NON-NLS-1$
public static final String JDT_JAVA_NATURE = "org.eclipse.jdt.core.javanature"; //$NON-NLS-1$
@@ -417,7 +429,9 @@ public static ImageDescriptor getImageDescriptor(String name) {
* @return image
*/
public static Image getImage(String imageName) {
- Image image = imageRegistry.get(imageName);
+ if (imageRegistry == null)
+ imageRegistry = new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
+ Image image = imageRegistry.get(imageName);
if (image == null) {
image = getImageDescriptor(imageName).createImage();
imageRegistry.put(imageName, image);
@@ -425,6 +439,64 @@ public static Image getImage(String imageName) {
return image;
}
+ /**
+ * @return Image for the icon that indicates a key with no issues
+ */
+ public static Image getKeyImage() {
+ Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
+ return image;
+ }
+
+ /**
+ * @return Image for the icon which indicates a key that has missing translations
+ */
+ public static Image getMissingTranslationImage() {
+ Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_ERROR));
+ image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
+ }
+
+ /**
+ * @return Image for the icon which indicates a key that is unused
+ */
+ public static Image getUnusedTranslationsImage() {
+ Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
+ ImageDescriptor warning = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_WARNING));
+ image = new DecorationOverlayIcon(image, warning, IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
+ }
+
+ /**
+ * @return Image for the icon which indicates a key that has missing translations and is unused
+ */
+ public static Image getMissingAndUnusedTranslationsImage() {
+ Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_ERROR));
+ image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
+ }
+
+ /**
+ * @return Image for the icon which indicates a key that has duplicate entries
+ */
+ public static Image getDuplicateEntryImage() {
+ Image image = UIUtils.getImage(UIUtils.IMAGE_KEY);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_WARNING));
+ image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
+ }
+
+ /**
+ * @return Image for the icon which indicates a key that has duplicate entries and is unused
+ */
+ public static Image getDuplicateEntryAndUnusedTranslationsImage() {
+ Image image = UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
+ ImageDescriptor missing = ImageDescriptor.createFromImage(UIUtils.getImage(UIUtils.IMAGE_DUPLICATE));
+ image = new DecorationOverlayIcon(image, missing, IDecoration.BOTTOM_RIGHT).createImage();
+ return image;
+ }
+
/**
* Gets the orientation suited for a given locale.
* @param locale the locale
@@ -435,7 +507,7 @@ public static int getOrientation(Locale locale){
ComponentOrientation orientation =
ComponentOrientation.getOrientation(locale);
if(orientation==ComponentOrientation.RIGHT_TO_LEFT){
- return SWT.RIGHT_TO_LEFT;
+ return MySWT.RIGHT_TO_LEFT;
}
}
return SWT.LEFT_TO_RIGHT;
@@ -461,11 +533,11 @@ public static boolean hasNature(
if (!projDescr.exists()) {
return false;//a corrupted project
}
-
- //<classpathentry kind="src" path="src"/>
+ //<classpathentry kind="src" path="src"/>
InputStream in = null;
try {
- in = ((IFile)projDescr).getContents();
+ projDescr.refreshLocal(IResource.DEPTH_ZERO, null);
+ in = projDescr.getContents();
//supposedly in utf-8. should not really matter for us
Reader r = new InputStreamReader(in, "UTF-8");
LineNumberReader lnr = new LineNumberReader(r);
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java
index fc05be98..e81ab275 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java
@@ -12,12 +12,12 @@
-import org.eclipse.babel.editor.MessagesEditor;
-import org.eclipse.babel.editor.tree.KeyTreeContributor;
+import org.eclipse.babel.editor.internal.MessagesEditor;
import org.eclipse.babel.editor.tree.actions.CollapseAllAction;
import org.eclipse.babel.editor.tree.actions.ExpandAllAction;
import org.eclipse.babel.editor.tree.actions.FlatModelAction;
import org.eclipse.babel.editor.tree.actions.TreeModelAction;
+import org.eclipse.babel.editor.tree.internal.KeyTreeContributor;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.widgets.Composite;
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java
index 6f9f816d..2be5cce2 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java
@@ -10,6 +10,8 @@
******************************************************************************/
package org.eclipse.babel.editor.widgets;
+import java.util.Stack;
+
import org.eclipse.babel.editor.util.UIUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusListener;
@@ -60,6 +62,8 @@ public void keyReleased(KeyEvent e) {
public NullableText(Composite parent, int style) {
super(parent, SWT.NONE);
text = new Text(this, style);
+ text.setData("UNDO", new Stack<String>());
+ text.setData("REDO", new Stack<String>());
defaultColor = text.getBackground();
nullColor = UIUtils.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW);
@@ -88,6 +92,8 @@ public void setText(String text) {
this.text.setText(text);
renderNormal();
}
+ Stack<String> undoCache = (Stack<String>) this.text.getData("UNDO");
+ undoCache.push(this.text.getText());
}
public String getText() {
if (isnull) {
@@ -177,4 +183,23 @@ public void setEditable(boolean editable) {
text.setEditable(editable);
}
+// private class SaveListener implements IMessagesEditorListener {
+//
+// public void onSave() {
+// Stack<String> undoCache = (Stack<String>) text.getData("UNDO");
+// undoCache.clear();
+// }
+//
+// public void onModify() {
+// // TODO Auto-generated method stub
+//
+// }
+//
+// public void onResourceChanged(IMessagesBundle bundle) {
+// // TODO Auto-generated method stub
+//
+// }
+//
+// }
+
}
\ No newline at end of file
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
new file mode 100644
index 00000000..7d4b05a8
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.editor.wizards;
+
+public interface IResourceBundleWizard {
+
+ void setBundleId(String rbName);
+
+ void setDefaultPath(String pathName);
+
+}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/ResourceBundleNewWizardPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/ResourceBundleNewWizardPage.java
deleted file mode 100644
index 91974f20..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/ResourceBundleNewWizardPage.java
+++ /dev/null
@@ -1,416 +0,0 @@
-/*
- * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
- *
- * This file is part of Essiembre ResourceBundle Editor.
- *
- * Essiembre ResourceBundle Editor is free software; you can redistribute it
- * and/or modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * Essiembre ResourceBundle Editor is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Essiembre ResourceBundle Editor; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307 USA
- */
-package org.eclipse.babel.editor.wizards;
-
-import java.util.Locale;
-
-import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.babel.editor.widgets.LocaleSelector;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.IDialogPage;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.List;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.ContainerSelectionDialog;
-
-/**
- * The "New" wizard page allows setting the container for
- * 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 $
- */
-public class ResourceBundleNewWizardPage extends WizardPage {
-
- static final String DEFAULT_LOCALE = "[" //$NON-NLS-1$
- + MessagesEditorPlugin.getString("editor.default") //$NON-NLS-1$
- + "]"; //$NON-NLS-1$
-
- private Text containerText;
- private Text fileText;
- private ISelection selection;
-
- private Button addButton;
- private Button removeButton;
-
- private List bundleLocalesList;
-
- private LocaleSelector localeSelector;
-
- /**
- * Constructor for SampleNewWizardPage.
- * @param selection workbench selection
- */
- public ResourceBundleNewWizardPage(ISelection selection) {
- super("wizardPage"); //$NON-NLS-1$
- setTitle(MessagesEditorPlugin.getString("editor.wiz.title")); //$NON-NLS-1$
- setDescription(MessagesEditorPlugin.getString("editor.wiz.desc")); //$NON-NLS-1$
- this.selection = selection;
- }
-
- /**
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 1;
- layout.verticalSpacing = 20;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- // Bundle name + location
- createTopComposite(container);
-
- // Locales
- createBottomComposite(container);
-
-
- initialize();
- dialogChanged();
- setControl(container);
- }
-
-
- /**
- * Creates the bottom part of this wizard, which is the locales to add.
- * @param parent parent container
- */
- private void createBottomComposite(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- // Available locales
- createBottomAvailableLocalesComposite(container);
-
- // Buttons
- createBottomButtonsComposite(container);
-
- // Selected locales
- createBottomSelectedLocalesComposite(container);
- }
-
- /**
- * Creates the bottom part of this wizard where selected locales
- * are stored.
- * @param parent parent container
- */
- private void createBottomSelectedLocalesComposite(Composite parent) {
-
- // Selected locales Group
- Group selectedGroup = new Group(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- layout = new GridLayout();
- layout.numColumns = 1;
- selectedGroup.setLayout(layout);
- GridData gd = new GridData(GridData.FILL_BOTH);
- selectedGroup.setLayoutData(gd);
- selectedGroup.setText(MessagesEditorPlugin.getString(
- "editor.wiz.selected")); //$NON-NLS-1$
- bundleLocalesList =
- new List(selectedGroup, SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
- gd = new GridData(GridData.FILL_BOTH);
- bundleLocalesList.setLayoutData(gd);
- bundleLocalesList.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- removeButton.setEnabled(
- bundleLocalesList.getSelectionIndices().length != 0);
- setAddButtonState();
- }
- });
- // add a single Locale so that the bundleLocalesList isn't empty on startup
- bundleLocalesList.add(DEFAULT_LOCALE);
- }
-
- /**
- * Creates the bottom part of this wizard where buttons to add/remove
- * locales are located.
- * @param parent parent container
- */
- private void createBottomButtonsComposite(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 1;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- addButton = new Button(container, SWT.NULL);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- addButton.setLayoutData(gd);
- addButton.setText(MessagesEditorPlugin.getString(
- "editor.wiz.add")); //$NON-NLS-1$
- addButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- bundleLocalesList.add(getSelectedLocaleAsString());
- setAddButtonState();
- dialogChanged(); // for the locale-check
- }
- });
-
- removeButton = new Button(container, SWT.NULL);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- removeButton.setLayoutData(gd);
- removeButton.setText(MessagesEditorPlugin.getString(
- "editor.wiz.remove")); //$NON-NLS-1$
- removeButton.setEnabled(false);
- removeButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- bundleLocalesList.remove(
- bundleLocalesList.getSelectionIndices());
- removeButton.setEnabled(false);
- setAddButtonState();
- dialogChanged(); // for the locale-check
- }
- });
- }
-
- /**
- * Creates the bottom part of this wizard where locales can be chosen
- * or created
- * @param parent parent container
- */
- private void createBottomAvailableLocalesComposite(Composite parent) {
-
- localeSelector =
- new LocaleSelector(parent);
- localeSelector.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- setAddButtonState();
- }
- });
- }
-
- /**
- * Creates the top part of this wizard, which is the bundle name
- * and location.
- * @param parent parent container
- */
- private void createTopComposite(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- // Folder
- Label label = new Label(container, SWT.NULL);
- label.setText(MessagesEditorPlugin.getString(
- "editor.wiz.folder")); //$NON-NLS-1$
-
- containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- containerText.setLayoutData(gd);
- containerText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- Button button = new Button(container, SWT.PUSH);
- button.setText(MessagesEditorPlugin.getString(
- "editor.wiz.browse")); //$NON-NLS-1$
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleBrowse();
- }
- });
-
- // Bundle name
- label = new Label(container, SWT.NULL);
- label.setText(MessagesEditorPlugin.getString(
- "editor.wiz.bundleName")); //$NON-NLS-1$
-
- fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- fileText.setLayoutData(gd);
- fileText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- label = new Label(container, SWT.NULL);
- label.setText("[locale].properties"); //$NON-NLS-1$
- }
-
- /**
- * Tests if the current workbench selection is a suitable
- * container to use.
- */
- private void initialize() {
- if (selection!=null && selection.isEmpty()==false &&
- selection instanceof IStructuredSelection) {
- IStructuredSelection ssel = (IStructuredSelection)selection;
- if (ssel.size()>1) {
- return;
- }
- Object obj = ssel.getFirstElement();
- if (obj instanceof IAdaptable) {
- IResource resource = (IResource) ((IAdaptable) obj).
- getAdapter(IResource.class);
- // check if selection is a file
- if (resource.getType() == IResource.FILE) {
- resource = resource.getParent();
- }
- // fill filepath container
- containerText.setText(resource.getFullPath().
- toPortableString());
- } else if (obj instanceof IResource) {
- // this will most likely never happen (legacy code)
- IContainer container;
- if (obj instanceof IContainer) {
- container = (IContainer)obj;
- } else {
- container = ((IResource)obj).getParent();
- }
- containerText.setText(container.getFullPath().
- toPortableString());
- }
- }
- fileText.setText("ApplicationResources"); //$NON-NLS-1$
- }
-
- /**
- * Uses the standard container selection dialog to
- * choose the new value for the container field.
- */
-
- /*default*/ void handleBrowse() {
- ContainerSelectionDialog dialog =
- new ContainerSelectionDialog(
- getShell(),
- ResourcesPlugin.getWorkspace().getRoot(),
- false,
- MessagesEditorPlugin.getString(
- "editor.wiz.selectFolder")); //$NON-NLS-1$
- if (dialog.open() == Window.OK) {
- Object[] result = dialog.getResult();
- if (result.length == 1) {
- containerText.setText(((Path)result[0]).toOSString());
- }
- }
- }
-
- /**
- * Ensures that both text fields and the Locale field are set.
- */
- /*default*/ void dialogChanged() {
- String container = getContainerName();
- String fileName = getFileName();
-
- if (container.length() == 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.container")); //$NON-NLS-1$
- return;
- }
- if (fileName.length() == 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.bundleName")); //$NON-NLS-1$
- return;
- }
- int dotLoc = fileName.lastIndexOf('.');
- if (dotLoc != -1) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.extension")); //$NON-NLS-1$
- return;
- }
- // check if at least one Locale has been added to th list
- if (bundleLocalesList.getItemCount() <= 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.locale")); //$NON-NLS-1$
- return;
- }
- updateStatus(null);
- }
-
- private void updateStatus(String message) {
- setErrorMessage(message);
- setPageComplete(message == null);
- }
-
- /**
- * Gets the container name.
- * @return container name
- */
- public String getContainerName() {
- return containerText.getText();
- }
- /**
- * Gets the file name.
- * @return file name
- */
- public String getFileName() {
- return fileText.getText();
- }
-
- /**
- * Sets the "add" button state.
- */
- /*default*/ void setAddButtonState() {
- addButton.setEnabled(bundleLocalesList.indexOf(
- getSelectedLocaleAsString()) == -1);
- }
-
- /**
- * Gets the user selected locales.
- * @return locales
- */
- /*default*/ String[] getLocaleStrings() {
- return bundleLocalesList.getItems();
- }
-
- /**
- * Gets a string representation of selected locale.
- * @return string representation of selected locale
- */
- /*default*/ String getSelectedLocaleAsString() {
- Locale selectedLocale = localeSelector.getSelectedLocale();
- if (selectedLocale != null) {
- return selectedLocale.toString();
- }
- return DEFAULT_LOCALE;
- }
-}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/ResourceBundleWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/ResourceBundleWizard.java
deleted file mode 100644
index 44399aa9..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/ResourceBundleWizard.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.wizards;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWizard;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-/**
- * This is the main wizard class for creating a new set of ResourceBundle
- * properties files. If the container resource
- * (a folder or a project) is selected in the workspace
- * when the wizard is opened, it will accept it as the target
- * container. The wizard creates one or several files with the extension
- * "properties".
- * @author Pascal Essiembre ([email protected])
- */
-public class ResourceBundleWizard extends Wizard implements INewWizard {
- private ResourceBundleNewWizardPage page;
- private ISelection selection;
-
- /**
- * Constructor for ResourceBundleWizard.
- */
- public ResourceBundleWizard() {
- super();
- setNeedsProgressMonitor(true);
- }
-
- /**
- * Adding the page to the wizard.
- */
-
- public void addPages() {
- page = new ResourceBundleNewWizardPage(selection);
- addPage(page);
- }
-
- /**
- * This method is called when 'Finish' button is pressed in
- * the wizard. We will create an operation and run it
- * using wizard as execution context.
- */
- public boolean performFinish() {
- final String containerName = page.getContainerName();
- final String baseName = page.getFileName();
- final String[] locales = page.getLocaleStrings();
- IRunnableWithProgress op = new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- monitor.worked(1);
- monitor.setTaskName(MessagesEditorPlugin.getString(
- "editor.wiz.creating")); //$NON-NLS-1$
- IFile file = null;
- for (int i = 0; i < locales.length; i++) {
- String fileName = baseName;
- if (locales[i].equals(
- ResourceBundleNewWizardPage.DEFAULT_LOCALE)) {
- fileName += ".properties"; //$NON-NLS-1$
- } else {
- fileName += "_" + locales[i] //$NON-NLS-1$
- + ".properties"; //$NON-NLS-1$
- }
- file = createFile(containerName, fileName, monitor);
- }
- final IFile lastFile = file;
- getShell().getDisplay().asyncExec(new Runnable() {
- public void run() {
- IWorkbenchPage wbPage = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- try {
- IDE.openEditor(wbPage, lastFile, true);
- } catch (PartInitException e) {
- }
- }
- });
- monitor.worked(1);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- try {
- getContainer().run(true, false, op);
- } catch (InterruptedException e) {
- return false;
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- MessageDialog.openError(getShell(),
- "Error", realException.getMessage()); //$NON-NLS-1$
- return false;
- }
- return true;
- }
-
- /*
- * The worker method. It will find the container, create the
- * file if missing or just replace its contents, and open
- * the editor on the newly created file.
- */
- /*default*/ IFile createFile(
- String containerName,
- String fileName,
- IProgressMonitor monitor)
- throws CoreException {
-
- monitor.beginTask(MessagesEditorPlugin.getString(
- "editor.wiz.creating") + fileName, 2); //$NON-NLS-1$
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IResource resource = root.findMember(new Path(containerName));
- if (!resource.exists() || !(resource instanceof IContainer)) {
- throwCoreException("Container \"" + containerName //$NON-NLS-1$
- + "\" does not exist."); //$NON-NLS-1$
- }
- IContainer container = (IContainer) resource;
- final IFile file = container.getFile(new Path(fileName));
- try {
- InputStream stream = openContentStream();
- if (file.exists()) {
- file.setContents(stream, true, true, monitor);
- } else {
- file.create(stream, true, monitor);
- }
- stream.close();
- } catch (IOException e) {
- }
- return file;
- }
-
- /*
- * We will initialize file contents with a sample text.
- */
- private InputStream openContentStream() {
- String contents = ""; //$NON-NLS-1$
- if (MsgEditorPreferences.getInstance().getSerializerConfig().isShowSupportEnabled()) {
-// contents = PropertiesGenerator.GENERATED_BY;
- }
- return new ByteArrayInputStream(contents.getBytes());
- }
-
- private void throwCoreException(String message) throws CoreException {
- IStatus status = new Status(IStatus.ERROR,
- "org.eclipse.babel.editor", //$NON-NLS-1$
- IStatus.OK, message, null);
- throw new CoreException(status);
- }
-
- /**
- * We will accept the selection in the workbench to see if
- * we can initialize from it.
- * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
- */
- public void init(
- IWorkbench workbench, IStructuredSelection structSelection) {
- this.selection = structSelection;
- }
-}
\ No newline at end of file
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
new file mode 100644
index 00000000..12f7e427
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java
@@ -0,0 +1,483 @@
+/*
+ * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
+ *
+ * This file is part of Essiembre ResourceBundle Editor.
+ *
+ * Essiembre ResourceBundle Editor is free software; you can redistribute it
+ * and/or modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Essiembre ResourceBundle Editor is distributed in the hope that it will be
+ * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Essiembre ResourceBundle Editor; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307 USA
+ */
+package org.eclipse.babel.editor.wizards.internal;
+
+import java.util.Locale;
+
+import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
+import org.eclipse.babel.editor.widgets.LocaleSelector;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.dialogs.IDialogPage;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.window.Window;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.dialogs.ContainerSelectionDialog;
+
+/**
+ * The "New" wizard page allows setting the container for
+ * 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 $
+ */
+public class ResourceBundleNewWizardPage extends WizardPage {
+
+ static final String DEFAULT_LOCALE = "[" //$NON-NLS-1$
+ + MessagesEditorPlugin.getString("editor.default") //$NON-NLS-1$
+ + "]"; //$NON-NLS-1$
+
+ /**
+ * contains the path of the folder in which the resource file will be created
+ */
+ private Text containerText;
+ /**
+ * Contains the name of the resource file
+ */
+ private Text fileText;
+ private ISelection selection;
+
+ private Button addButton;
+ private Button removeButton;
+ /**
+ * Contains all added locales
+ */
+ private List bundleLocalesList;
+
+ private LocaleSelector localeSelector;
+
+ private String defaultPath = "";
+ private String defaultRBName = "ApplicationResources";
+
+ /**
+ * Constructor for SampleNewWizardPage.
+ * @param selection workbench selection
+ */
+ public ResourceBundleNewWizardPage(ISelection selection, String defaultPath, String defaultRBName) {
+ super("wizardPage"); //$NON-NLS-1$
+ setTitle(MessagesEditorPlugin.getString("editor.wiz.title")); //$NON-NLS-1$
+ setDescription(MessagesEditorPlugin.getString("editor.wiz.desc")); //$NON-NLS-1$
+ this.selection = selection;
+
+ if (! defaultPath.isEmpty())
+ this.defaultPath = defaultPath;
+ if (! defaultRBName.isEmpty())
+ this.defaultRBName = defaultRBName;
+ }
+
+ /**
+ * @see IDialogPage#createControl(Composite)
+ */
+ public void createControl(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 1;
+ layout.verticalSpacing = 20;
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ container.setLayoutData(gd);
+
+ // Bundle name + location
+ createTopComposite(container);
+
+ // Locales
+ createBottomComposite(container);
+
+
+ initialize();
+ dialogChanged();
+ setControl(container);
+ }
+
+
+ /**
+ * Creates the bottom part of this wizard, which is the locales to add.
+ * @param parent parent container
+ */
+ private void createBottomComposite(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 9;
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ container.setLayoutData(gd);
+
+ // Available locales
+ createBottomAvailableLocalesComposite(container);
+
+ // Buttons
+ createBottomButtonsComposite(container);
+
+ // Selected locales
+ createBottomSelectedLocalesComposite(container);
+ }
+
+ /**
+ * Creates the bottom part of this wizard where selected locales
+ * are stored.
+ * @param parent parent container
+ */
+ private void createBottomSelectedLocalesComposite(Composite parent) {
+
+ // Selected locales Group
+ Group selectedGroup = new Group(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ layout = new GridLayout();
+ layout.numColumns = 1;
+ selectedGroup.setLayout(layout);
+ GridData gd = new GridData(GridData.FILL_BOTH);
+ selectedGroup.setLayoutData(gd);
+ selectedGroup.setText(MessagesEditorPlugin.getString(
+ "editor.wiz.selected")); //$NON-NLS-1$
+ bundleLocalesList =
+ new List(selectedGroup, SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
+ gd = new GridData(GridData.FILL_BOTH);
+ bundleLocalesList.setLayoutData(gd);
+ bundleLocalesList.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ removeButton.setEnabled(
+ bundleLocalesList.getSelectionIndices().length != 0);
+ setAddButtonState();
+ }
+ });
+ // add a single Locale so that the bundleLocalesList isn't empty on startup
+ bundleLocalesList.add(DEFAULT_LOCALE);
+ }
+
+ /**
+ * Creates the bottom part of this wizard where buttons to add/remove
+ * locales are located.
+ * @param parent parent container
+ */
+ private void createBottomButtonsComposite(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 1;
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ container.setLayoutData(gd);
+
+ addButton = new Button(container, SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ addButton.setLayoutData(gd);
+ addButton.setText(MessagesEditorPlugin.getString(
+ "editor.wiz.add")); //$NON-NLS-1$
+ addButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ bundleLocalesList.add(getSelectedLocaleAsString());
+ setAddButtonState();
+ dialogChanged(); // for the locale-check
+ }
+ });
+
+ removeButton = new Button(container, SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ removeButton.setLayoutData(gd);
+ removeButton.setText(MessagesEditorPlugin.getString(
+ "editor.wiz.remove")); //$NON-NLS-1$
+ removeButton.setEnabled(false);
+ removeButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ bundleLocalesList.remove(
+ bundleLocalesList.getSelectionIndices());
+ removeButton.setEnabled(false);
+ setAddButtonState();
+ dialogChanged(); // for the locale-check
+ }
+ });
+ }
+
+ /**
+ * Creates the bottom part of this wizard where locales can be chosen
+ * or created
+ * @param parent parent container
+ */
+ private void createBottomAvailableLocalesComposite(Composite parent) {
+
+ localeSelector =
+ new LocaleSelector(parent);
+ localeSelector.addModifyListener(new ModifyListener(){
+ public void modifyText(ModifyEvent e) {
+ setAddButtonState();
+ }
+ });
+ }
+
+ /**
+ * Creates the top part of this wizard, which is the bundle name
+ * and location.
+ * @param parent parent container
+ */
+ private void createTopComposite(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 9;
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ container.setLayoutData(gd);
+
+ // Folder
+ Label label = new Label(container, SWT.NULL);
+ label.setText(MessagesEditorPlugin.getString(
+ "editor.wiz.folder")); //$NON-NLS-1$
+
+ containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ containerText.setLayoutData(gd);
+ containerText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ dialogChanged();
+ }
+ });
+ Button button = new Button(container, SWT.PUSH);
+ button.setText(MessagesEditorPlugin.getString(
+ "editor.wiz.browse")); //$NON-NLS-1$
+ button.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handleBrowse();
+ }
+ });
+
+ // Bundle name
+ label = new Label(container, SWT.NULL);
+ label.setText(MessagesEditorPlugin.getString(
+ "editor.wiz.bundleName")); //$NON-NLS-1$
+
+ fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ fileText.setLayoutData(gd);
+ fileText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ dialogChanged();
+ }
+ });
+ label = new Label(container, SWT.NULL);
+ label.setText("[locale].properties"); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests if the current workbench selection is a suitable
+ * container to use.
+ */
+ private void initialize() {
+ if (! defaultPath.isEmpty()) {
+ containerText.setText(defaultPath);
+
+ } else if (selection!=null && selection.isEmpty()==false &&
+ selection instanceof IStructuredSelection) {
+ IStructuredSelection ssel = (IStructuredSelection)selection;
+ if (ssel.size()>1) {
+ return;
+ }
+ Object obj = ssel.getFirstElement();
+ if (obj instanceof IAdaptable) {
+ IResource resource = (IResource) ((IAdaptable) obj).
+ getAdapter(IResource.class);
+ // check if selection is a file
+ if (resource.getType() == IResource.FILE) {
+ resource = resource.getParent();
+ }
+ // fill filepath container
+ containerText.setText(resource.getFullPath().
+ toPortableString());
+ } else if (obj instanceof IResource) {
+ // this will most likely never happen (legacy code)
+ IContainer container;
+ if (obj instanceof IContainer) {
+ container = (IContainer)obj;
+ } else {
+ container = ((IResource)obj).getParent();
+ }
+ containerText.setText(container.getFullPath().
+ toPortableString());
+ }
+ }
+
+ fileText.setText(defaultRBName);
+ }
+
+ /**
+ * Uses the standard container selection dialog to
+ * choose the new value for the container field.
+ */
+
+ /*default*/ void handleBrowse() {
+ ContainerSelectionDialog dialog =
+ new ContainerSelectionDialog(
+ getShell(),
+ ResourcesPlugin.getWorkspace().getRoot(),
+ false,
+ MessagesEditorPlugin.getString(
+ "editor.wiz.selectFolder")); //$NON-NLS-1$
+ if (dialog.open() == Window.OK) {
+ Object[] result = dialog.getResult();
+ if (result.length == 1) {
+ containerText.setText(((Path)result[0]).toOSString());
+ }
+ }
+ }
+
+ /**
+ * Ensures that both text fields and the Locale field are set.
+ */
+ /*default*/ void dialogChanged() {
+ String container = getContainerName();
+ String fileName = getFileName();
+
+ if (container.length() == 0) {
+ updateStatus(MessagesEditorPlugin.getString(
+ "editor.wiz.error.container")); //$NON-NLS-1$
+ return;
+ }
+ if (fileName.length() == 0) {
+ updateStatus(MessagesEditorPlugin.getString(
+ "editor.wiz.error.bundleName")); //$NON-NLS-1$
+ return;
+ }
+ int dotLoc = fileName.lastIndexOf('.');
+ if (dotLoc != -1) {
+ updateStatus(MessagesEditorPlugin.getString(
+ "editor.wiz.error.extension")); //$NON-NLS-1$
+ return;
+ }
+ // check if at least one Locale has been added to th list
+ if (bundleLocalesList.getItemCount() <= 0) {
+ updateStatus(MessagesEditorPlugin.getString(
+ "editor.wiz.error.locale")); //$NON-NLS-1$
+ return;
+ }
+ // check if the container field contains a valid path
+ // meaning: Project exists, at least one segment, valid path
+ Path pathContainer = new Path(container);
+ if (!pathContainer.isValidPath(container)) {
+ updateStatus(MessagesEditorPlugin.getString(
+ "editor.wiz.error.invalidpath")); //$NON-NLS-1$
+ return;
+ }
+
+ if (pathContainer.segmentCount() < 1) {
+ updateStatus(MessagesEditorPlugin.getString(
+ "editor.wiz.error.invalidpath")); //$NON-NLS-1$
+ return;
+ }
+
+ if (!projectExists(pathContainer.segment(0))) {
+ String errormessage = MessagesEditorPlugin.getString(
+ "editor.wiz.error.projectnotexist");
+ errormessage = String.format(errormessage, pathContainer.segment(0));
+ updateStatus(errormessage); //$NON-NLS-1$
+ return;
+ }
+
+ updateStatus(null);
+ }
+
+ private void updateStatus(String message) {
+ setErrorMessage(message);
+ setPageComplete(message == null);
+ }
+
+ /**
+ * Gets the container name.
+ * @return container name
+ */
+ public String getContainerName() {
+ return containerText.getText();
+ }
+ /**
+ * Gets the file name.
+ * @return file name
+ */
+ public String getFileName() {
+ return fileText.getText();
+ }
+
+ /**
+ * Sets the "add" button state.
+ */
+ /*default*/ void setAddButtonState() {
+ addButton.setEnabled(bundleLocalesList.indexOf(
+ getSelectedLocaleAsString()) == -1);
+ }
+
+ /**
+ * Gets the user selected locales.
+ * @return locales
+ */
+ /*default*/ String[] getLocaleStrings() {
+ return bundleLocalesList.getItems();
+ }
+
+ /**
+ * Gets a string representation of selected locale.
+ * @return string representation of selected locale
+ */
+ /*default*/ String getSelectedLocaleAsString() {
+ Locale selectedLocale = localeSelector.getSelectedLocale();
+ if (selectedLocale != null) {
+ return selectedLocale.toString();
+ }
+ return DEFAULT_LOCALE;
+ }
+
+ /**
+ * Checks if there is a Project with the given name in the Package Explorer
+ * @param projectName
+ * @return
+ */
+ /*default*/ boolean projectExists(String projectName) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ Path containerNamePath = new Path("/"+projectName);
+ IResource resource = root.findMember(containerNamePath);
+ if (resource == null) {
+ return false;
+ }
+ return resource.exists();
+ }
+
+ public void setDefaultRBName(String name) {
+ defaultRBName = name;
+ }
+
+ public void setDefaultPath(String path) {
+ defaultPath = path;
+ }
+}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java
new file mode 100644
index 00000000..b0710490
--- /dev/null
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java
@@ -0,0 +1,293 @@
+/*******************************************************************************
+ * 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
+ * Matthias Lettmayer - added setBundleId() + setDefaultPath() (fixed issue 60)
+ ******************************************************************************/
+package org.eclipse.babel.editor.wizards.internal;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+
+import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
+import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
+import org.eclipse.babel.editor.wizards.IResourceBundleWizard;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.ui.INewWizard;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWizard;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.ide.IDE;
+
+/**
+ * This is the main wizard class for creating a new set of ResourceBundle
+ * properties files. If the container resource
+ * (a folder or a project) is selected in the workspace
+ * when the wizard is opened, it will accept it as the target
+ * container. The wizard creates one or several files with the extension
+ * "properties".
+ * @author Pascal Essiembre ([email protected])
+ */
+public class ResourceBundleWizard extends Wizard implements INewWizard, IResourceBundleWizard {
+ private ResourceBundleNewWizardPage page;
+ private ISelection selection;
+
+ private String defaultRbName = "";
+ private String defaultPath = "";
+
+ /**
+ * Constructor for ResourceBundleWizard.
+ */
+ public ResourceBundleWizard() {
+ super();
+ setNeedsProgressMonitor(true);
+ }
+
+ /**
+ * Adding the page to the wizard.
+ */
+
+ public void addPages() {
+ page = new ResourceBundleNewWizardPage(selection, defaultPath, defaultRbName);
+ addPage(page);
+ }
+
+ /**
+ * This method is called when 'Finish' button is pressed in
+ * the wizard. We will create an operation and run it
+ * using wizard as execution context.
+ */
+ public boolean performFinish() {
+ final String containerName = page.getContainerName();
+ final String baseName = page.getFileName();
+ final String[] locales = page.getLocaleStrings();
+ if (!folderExists(containerName)) {
+ //show choosedialog
+ String message = MessagesEditorPlugin.getString(
+ "editor.wiz.createfolder");
+ message = String.format(message, containerName);
+ if(!MessageDialog.openConfirm(getShell(), "Create Folder", message)) { //$NON-NLS-1$
+ return false;
+ }
+
+ }
+ IRunnableWithProgress op = new IRunnableWithProgress() {
+ public void run(IProgressMonitor monitor) throws InvocationTargetException {
+ try {
+ monitor.worked(1);
+ monitor.setTaskName(MessagesEditorPlugin.getString(
+ "editor.wiz.creating")); //$NON-NLS-1$
+ IFile file = null;
+ for (int i = 0; i < locales.length; i++) {
+ String fileName = baseName;
+ if (locales[i].equals(
+ ResourceBundleNewWizardPage.DEFAULT_LOCALE)) {
+ fileName += ".properties"; //$NON-NLS-1$
+ } else {
+ fileName += "_" + locales[i] //$NON-NLS-1$
+ + ".properties"; //$NON-NLS-1$
+ }
+ file = createFile(containerName, fileName, monitor);
+ }
+ if (file == null) { // file creation failed
+ MessageDialog.openError(getShell(), "Error", "Error creating file"); //$NON-NLS-1$
+ throwCoreException("File \""+containerName+baseName+"\" could not be created"); //$NON-NLS-1$
+ }
+ final IFile lastFile = file;
+ getShell().getDisplay().asyncExec(new Runnable() {
+ public void run() {
+ IWorkbenchPage wbPage = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ try {
+ IDE.openEditor(wbPage, lastFile, true);
+ } catch (PartInitException e) {
+ }
+ }
+ });
+ monitor.worked(1);
+ } catch (CoreException e) {
+ throw new InvocationTargetException(e);
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+ try {
+ getContainer().run(true, false, op);
+ } catch (InterruptedException e) {
+ return false;
+ } catch (InvocationTargetException e) {
+ Throwable realException = e.getTargetException();
+ MessageDialog.openError(getShell(),
+ "Error", realException.getLocalizedMessage()); //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
+ /*
+ * Checks if the input folder existsS
+ */
+ /*default*/ boolean folderExists(String path) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IResource resource = root.findMember(new Path(path));
+ if (resource == null) {
+ return false;
+ } else {
+ return resource.exists();
+ }
+ }
+
+ /*
+ * The worker method. It will find the container, create the
+ * file if missing or just replace its contents, and open
+ * the editor on the newly created file. Will also create
+ * the parent folders of the file if they do not exist.
+ */
+ /*default*/ IFile createFile(
+ String containerName,
+ String fileName,
+ IProgressMonitor monitor)
+ throws CoreException {
+
+ monitor.beginTask(MessagesEditorPlugin.getString(
+ "editor.wiz.creating") + fileName, 2); //$NON-NLS-1$
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ Path containerNamePath = new Path(containerName);
+ IResource resource = root.findMember(containerNamePath);
+ if (resource == null) {
+ if (!createFolder(containerNamePath, root, monitor)) {
+ MessageDialog.openError(getShell(), "Error",
+ String.format(MessagesEditorPlugin.getString(
+ "editor.wiz.error.couldnotcreatefolder"),
+ containerName)); //$NON-NLS-1$
+ return null;
+ }
+ } else if (!resource.exists() || !(resource instanceof IContainer)) {
+ //throwCoreException("Container \"" + containerName //$NON-NLS-1$
+ // + "\" does not exist."); //$NON-NLS-1$
+ if (!createFolder(containerNamePath, root, monitor)) {
+ MessageDialog.openError(getShell(), "Error",
+ String.format(MessagesEditorPlugin.getString(
+ "editor.wiz.error.couldnotcreatefolder"),
+ containerName)); //$NON-NLS-1$
+ return null;
+ }
+ }
+
+ IContainer container = (IContainer) root.findMember(containerNamePath);
+ if (container == null) {
+ MessageDialog.openError(getShell(), "Error",
+ String.format(MessagesEditorPlugin.getString(
+ "editor.wiz.error.couldnotcreatefolder"),
+ containerName)); //$NON-NLS-1$
+ return null;
+ }
+ final IFile file = container.getFile(new Path(fileName));
+ try {
+ InputStream stream = openContentStream();
+ if (file.exists()) {
+ file.setContents(stream, true, true, monitor);
+ } else {
+ file.create(stream, true, monitor);
+ }
+ stream.close();
+ } catch (IOException e) {
+ }
+ return file;
+ }
+
+ /*
+ * Recursively creates all missing folders
+ */
+ /*default*/ boolean createFolder(Path folderPath, IWorkspaceRoot root, IProgressMonitor monitor) {
+ IResource baseResource = root.findMember(folderPath);
+ if (!(baseResource == null)) {
+ if (baseResource.exists()) {
+ return true;
+ }
+ } else { // if folder does not exist
+ if (folderPath.segmentCount() <= 1) {
+ return true;
+ }
+ Path oneSegmentLess = (Path)folderPath.removeLastSegments(1); // get parent
+ if (createFolder(oneSegmentLess, root, monitor)) { // create parent folder
+ IResource resource = root.findMember(oneSegmentLess);
+ if (resource == null) {
+ return false; // resource is null
+ } else if (!resource.exists() || !(resource instanceof IContainer)) {
+ return false; // resource does not exist
+ }
+ final IFolder folder = root.getFolder(folderPath);
+ try {
+ folder.create(true, true, monitor);
+ } catch (CoreException e) {
+ return false;
+ }
+ return true;
+ } else {
+ return false; // could not create parent folder of the input path
+ }
+ }
+ return true;
+ }
+
+ /*
+ * We will initialize file contents with a sample text.
+ */
+ private InputStream openContentStream() {
+ String contents = ""; //$NON-NLS-1$
+ if (MsgEditorPreferences.getInstance().getSerializerConfig().isShowSupportEnabled()) {
+// contents = PropertiesGenerator.GENERATED_BY;
+ }
+ return new ByteArrayInputStream(contents.getBytes());
+ }
+
+ private synchronized void throwCoreException(String message) throws CoreException {
+ IStatus status = new Status(IStatus.ERROR,
+ "org.eclipse.babel.editor", //$NON-NLS-1$
+ IStatus.OK, message, null);
+ throw new CoreException(status);
+ }
+
+ /**
+ * We will accept the selection in the workbench to see if
+ * we can initialize from it.
+ * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
+ */
+ public void init(
+ IWorkbench workbench, IStructuredSelection structSelection) {
+ this.selection = structSelection;
+ }
+
+ public void setBundleId(String rbName) {
+ defaultRbName = rbName;
+ }
+
+ public void setDefaultPath(String pathName) {
+ defaultPath = pathName;
+ }
+}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
index 3a56a8c8..46f1a2b1 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
@@ -13,9 +13,10 @@
import java.util.ArrayList;
import java.util.Locale;
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesIFileResource;
+import org.eclipse.babel.core.message.internal.Message;
+import org.eclipse.babel.core.message.internal.MessagesBundle;
+import org.eclipse.babel.core.message.resource.IMessagesResource;
+import org.eclipse.babel.core.message.resource.internal.PropertiesIFileResource;
import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
@@ -48,7 +49,6 @@
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
public class EditResourceBundleEntriesDialog extends Dialog {
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
index f0f98c83..b5cd32f4 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java
@@ -1,12 +1,12 @@
/*******************************************************************************
- * Copyright (c) 2008 Stefan Mücke and others.
+ * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan Mücke - initial API and implementation
+ * Stefan M�cke - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.nls.internal.ui.editor;
@@ -22,6 +22,7 @@
import java.util.List;
import java.util.Locale;
+import org.eclipse.babel.editor.compat.MyFormToolkit;
import org.eclipse.babel.editor.plugin.MessagesEditorPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -113,10 +114,12 @@ public LocalizationLabelProvider(Object columnConfig) {
this.columnConfig = columnConfig;
}
+ @Override
public String getText(Object element) {
ResourceBundleKey key = (ResourceBundleKey) element;
- if (columnConfig == KEY)
+ if (columnConfig == KEY) {
return key.getName();
+ }
Locale locale = (Locale) columnConfig;
String value;
try {
@@ -125,8 +128,9 @@ public String getText(Object element) {
value = null;
MessagesEditorPlugin.log(e);
}
- if (value == null)
+ if (value == null) {
value = "";
+ }
return value;
}
}
@@ -139,6 +143,7 @@ public EditEntryAction() {
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
ResourceBundleKey key = getSelectedEntry();
if (key == null) {
@@ -146,7 +151,8 @@ public void run() {
}
Shell shell = Display.getCurrent().getActiveShell();
Locale[] locales = getLocales();
- EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(shell, locales);
+ EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(
+ shell, locales);
dialog.setResourceBundleKey(key);
if (dialog.open() == Window.OK) {
updateLabels();
@@ -156,24 +162,28 @@ public void run() {
private class ConfigureColumnsAction extends Action {
public ConfigureColumnsAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/conf_columns.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/conf_columns.gif"));
setToolTipText("Configure Columns");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
Shell shell = Display.getCurrent().getActiveShell();
String[] values = new String[columnConfigs.length];
for (int i = 0; i < columnConfigs.length; i++) {
String config = columnConfigs[i].toString();
- if (config.equals("")) //$NON-NLS-1$
+ if (config.equals("")) {
config = "default"; //$NON-NLS-1$
+ }
values[i] = config;
}
- ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell, values);
+ ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell,
+ values);
if (dialog.open() == Window.OK) {
String[] result = dialog.getResult();
Object[] newConfigs = new Object[result.length];
@@ -193,14 +203,16 @@ public void run() {
private class EditFilterOptionsAction extends Action {
public EditFilterOptionsAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/filter_obj.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/filter_obj.gif"));
setToolTipText("Edit Filter Options");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
Shell shell = Display.getCurrent().getActiveShell();
FilterOptionsDialog dialog = new FilterOptionsDialog(shell);
@@ -215,14 +227,16 @@ public void run() {
private class RefreshAction extends Action {
public RefreshAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/refresh.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/refresh.gif"));
setToolTipText("Refresh");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
MessagesEditorPlugin.disposeModel();
entryList = new ResourceBundleKeyList(new ResourceBundleKey[0]);
@@ -232,11 +246,14 @@ public void run() {
}
}
- private class BundleStringComparator implements Comparator<ResourceBundleKey> {
+ private class BundleStringComparator implements
+ Comparator<ResourceBundleKey> {
private final Locale locale;
+
public BundleStringComparator(Locale locale) {
this.locale = locale;
}
+
public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
String value1 = null;
String value2 = null;
@@ -250,53 +267,59 @@ public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
} catch (CoreException e) {
MessagesEditorPlugin.log(e);
}
- if (value1 == null)
+ if (value1 == null) {
value1 = ""; //$NON-NLS-1$
- if (value2 == null)
+ }
+ if (value2 == null) {
value2 = ""; //$NON-NLS-1$
+ }
return value1.compareToIgnoreCase(value2);
}
}
private class ExportAction extends Action {
public ExportAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/export.gif"));
+ super(null, IAction.AS_PUSH_BUTTON);
+ setImageDescriptor(MessagesEditorPlugin
+ .getImageDescriptor("elcl16/export.gif"));
setToolTipText("Export Current View to CSV or HTML File");
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
+ @Override
public void run() {
Shell shell = Display.getCurrent().getActiveShell();
FileDialog dialog = new FileDialog(shell);
dialog.setText("Export File");
- dialog.setFilterExtensions(new String[] {"*.*", "*.htm; *.html", "*.txt; *.csv"});
- dialog.setFilterNames(new String[] {"All Files (*.*)", "HTML File (*.htm; *.html)",
- "Tabulator Separated File (*.txt; *.csv)"});
+ dialog.setFilterExtensions(new String[] { "*.*", "*.htm; *.html",
+ "*.txt; *.csv" });
+ dialog.setFilterNames(new String[] { "All Files (*.*)",
+ "HTML File (*.htm; *.html)",
+ "Tabulator Separated File (*.txt; *.csv)" });
final String filename = dialog.open();
if (filename != null) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
File file = new File(filename);
try {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(file),
- "UTF8")); //$NON-NLS-1$
+ BufferedWriter writer = new BufferedWriter(
+ new OutputStreamWriter(
+ new FileOutputStream(file), "UTF8")); //$NON-NLS-1$
boolean isHtml = filename.endsWith(".htm") || filename.endsWith(".html"); //$NON-NLS-1$ //$NON-NLS-2$
if (isHtml) {
writer.write("" //$NON-NLS-1$
- + "<html>\r\n" //$NON-NLS-1$
- + "<head>\r\n" //$NON-NLS-1$
- + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
- + "<style>\r\n" //$NON-NLS-1$
- + "table {width:100%;}\r\n" //$NON-NLS-1$
- + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
- + "</style>\r\n" //$NON-NLS-1$
- + "</head>\r\n" //$NON-NLS-1$
- + "<body>\r\n" //$NON-NLS-1$
- + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
+ + "<html>\r\n" //$NON-NLS-1$
+ + "<head>\r\n" //$NON-NLS-1$
+ + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
+ + "<style>\r\n" //$NON-NLS-1$
+ + "table {width:100%;}\r\n" //$NON-NLS-1$
+ + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
+ + "</style>\r\n" //$NON-NLS-1$
+ + "</head>\r\n" //$NON-NLS-1$
+ + "<body>\r\n" //$NON-NLS-1$
+ + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
}
int size = entryList.getSize();
@@ -313,8 +336,9 @@ public void run() {
writer.write("<tr><td>"); //$NON-NLS-1$
}
Object config = configs[j];
- if (!isHtml && j > 0)
+ if (!isHtml && j > 0) {
writer.write("\t"); //$NON-NLS-1$
+ }
if (config == KEY) {
writer.write(key.getName());
} else {
@@ -332,7 +356,8 @@ public void run() {
} else {
valueCount++;
}
- writer.write(EditResourceBundleEntriesDialog.escape(value));
+ writer.write(EditResourceBundleEntriesDialog
+ .escape(value));
}
if (isHtml) {
writer.write("</td></tr>\r\n"); //$NON-NLS-1$
@@ -350,23 +375,21 @@ public void run() {
}
writer.close();
Shell shell = Display.getCurrent().getActiveShell();
- MessageDialog.openInformation(
- shell,
- "Finished",
- "File written successfully.\n\nNumber of entries written: "
- + entryList.getSize()
- + "\nNumber of translations: "
- + valueCount
- + " ("
- + missingCount
- + " missing)");
+ MessageDialog.openInformation(shell, "Finished",
+ "File written successfully.\n\nNumber of entries written: "
+ + entryList.getSize()
+ + "\nNumber of translations: "
+ + valueCount + " (" + missingCount
+ + " missing)");
} catch (IOException e) {
Shell shell = Display.getCurrent().getActiveShell();
- ErrorDialog.openError(shell, "Error", "Error saving file.", new Status(
- IStatus.ERROR,
- MessagesEditorPlugin.PLUGIN_ID,
- e.getMessage(),
- e));
+ ErrorDialog.openError(
+ shell,
+ "Error",
+ "Error saving file.",
+ new Status(IStatus.ERROR,
+ MessagesEditorPlugin.PLUGIN_ID, e
+ .getMessage(), e));
}
}
});
@@ -376,7 +399,8 @@ public void run() {
public static final String ID = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
- protected static final Object KEY = "key"; // used to indicate the key column
+ protected static final Object KEY = "key"; // used to indicate the key
+ // column
private static final String PREF_SECTION_NAME = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
private static final String PREF_SORT_ORDER = "sortOrder"; //$NON-NLS-1$
@@ -392,7 +416,7 @@ public void run() {
private ExportAction exportAction;
// Form
- protected FormToolkit toolkit = new FormToolkit(Display.getCurrent());
+ protected MyFormToolkit toolkit = new MyFormToolkit(Display.getCurrent());
private Form form;
private Image formImage;
@@ -400,7 +424,7 @@ public void run() {
protected Composite queryComposite;
protected Text queryText;
- // Results
+ // Results
private Section resultsSection;
private Composite tableComposite;
protected TableViewer tableViewer;
@@ -413,7 +437,8 @@ public void run() {
protected FilterOptions filterOptions;
/**
- * Column configuration. Values may be either <code>KEY</code> or a {@link Locale}.
+ * Column configuration. Values may be either <code>KEY</code> or a
+ * {@link Locale}.
*/
protected Object[] columnConfigs;
/**
@@ -428,6 +453,7 @@ public void run() {
public boolean contains(ISchedulingRule rule) {
return rule == this;
}
+
public boolean isConflicting(ISchedulingRule rule) {
return rule == this;
}
@@ -439,7 +465,8 @@ public LocalizationEditor() {
}
public ResourceBundleKey getSelectedEntry() {
- IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
+ IStructuredSelection selection = (IStructuredSelection) tableViewer
+ .getSelection();
if (selection.size() == 1) {
return (ResourceBundleKey) selection.getFirstElement();
}
@@ -459,7 +486,8 @@ public void createPartControl(Composite parent) {
form.setSeparatorVisible(true);
form.setText("Localization");
- form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor("obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
+ form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor(
+ "obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
toolkit.adapt(form);
toolkit.paintBordersFor(form);
final Composite body = form.getBody();
@@ -492,8 +520,10 @@ public void createPartControl(Composite parent) {
toolkit.createLabel(queryComposite, "Search:");
// Query text
- queryText = toolkit.createText(queryComposite, "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
+ queryText = toolkit.createText(queryComposite,
+ "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
queryText.addKeyListener(new KeyAdapter() {
+ @Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN) {
table.setFocus();
@@ -523,13 +553,16 @@ public void modifyText(ModifyEvent e) {
toolkit.adapt(control);
// Results section
- resultsSection = toolkit.createSection(body, ExpandableComposite.TITLE_BAR
- | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
- resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
+ resultsSection = toolkit.createSection(body,
+ ExpandableComposite.TITLE_BAR
+ | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
+ resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true, 2, 1));
resultsSection.setText("Localization Strings");
toolkit.adapt(resultsSection);
- final Composite resultsComposite = toolkit.createComposite(resultsSection, SWT.NONE);
+ final Composite resultsComposite = toolkit.createComposite(
+ resultsSection, SWT.NONE);
toolkit.adapt(resultsComposite);
final GridLayout gridLayout2 = new GridLayout();
gridLayout2.marginTop = 1;
@@ -539,8 +572,10 @@ public void modifyText(ModifyEvent e) {
resultsComposite.setLayout(gridLayout2);
filteredLabel = new Label(resultsSection, SWT.NONE);
- filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- filteredLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
+ filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER,
+ false, false));
+ filteredLabel.setForeground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_RED));
filteredLabel.setText(""); //$NON-NLS-1$
toolkit.paintBordersFor(resultsComposite);
@@ -548,9 +583,11 @@ public void modifyText(ModifyEvent e) {
resultsSection.setTextClient(filteredLabel);
tableComposite = toolkit.createComposite(resultsComposite, SWT.NONE);
- tableComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
+ tableComposite.setData(FormToolkit.KEY_DRAW_BORDER,
+ FormToolkit.TREE_BORDER);
toolkit.adapt(tableComposite);
- tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
// Table
createTableViewer();
@@ -563,7 +600,7 @@ public void modifyText(ModifyEvent e) {
filterOptions.pluginPatterns = new String[0];
filterOptions.keysWithMissingEntriesOnly = false;
sortOrder = KEY;
- columnConfigs = new Object[] {KEY, new Locale(""), new Locale("de")}; //$NON-NLS-1$ //$NON-NLS-2$
+ columnConfigs = new Object[] { KEY, new Locale(""), new Locale("de") }; //$NON-NLS-1$ //$NON-NLS-2$
// Load configuration
try {
@@ -578,7 +615,8 @@ public void modifyText(ModifyEvent e) {
}
protected void updateFilterLabel() {
- if (filterOptions.filterPlugins || filterOptions.keysWithMissingEntriesOnly) {
+ if (filterOptions.filterPlugins
+ || filterOptions.keysWithMissingEntriesOnly) {
filteredLabel.setText("(filtered)");
} else {
filteredLabel.setText(""); //$NON-NLS-1$
@@ -588,10 +626,12 @@ protected void updateFilterLabel() {
private void loadSettings() {
// TODO Move this to the preferences?
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault().getDialogSettings();
+ IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
- if (section == null)
+ if (section == null) {
return;
+ }
// Sort order
String sortOrderString = section.get(PREF_SORT_ORDER);
@@ -610,7 +650,8 @@ private void loadSettings() {
// Columns
String columns = section.get(PREF_COLUMNS);
if (columns != null) {
- String[] cols = columns.substring(1, columns.length() - 1).split(","); //$NON-NLS-1$
+ String[] cols = columns.substring(1, columns.length() - 1).split(
+ ","); //$NON-NLS-1$
columnConfigs = new Object[cols.length];
for (int i = 0; i < cols.length; i++) {
String value = cols[i].trim();
@@ -633,7 +674,8 @@ private void loadSettings() {
this.filterOptions.filterPlugins = "true".equals(filterOptions); //$NON-NLS-1$
String patterns = section.get(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS);
if (patterns != null) {
- String[] split = patterns.substring(1, patterns.length() - 1).split(","); //$NON-NLS-1$
+ String[] split = patterns.substring(1, patterns.length() - 1)
+ .split(","); //$NON-NLS-1$
for (int i = 0; i < split.length; i++) {
split[i] = split[i].trim();
}
@@ -641,11 +683,12 @@ private void loadSettings() {
}
this.filterOptions.keysWithMissingEntriesOnly = "true".equals(section.get(PREF_FILTER_OPTIONS_MISSING_ONLY)); //$NON-NLS-1$
- // TODO Save column widths
+ // TODO Save column widths
}
private void saveSettings() {
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault().getDialogSettings();
+ IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault()
+ .getDialogSettings();
IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
if (section == null) {
section = dialogSettings.addNewSection(PREF_SECTION_NAME);
@@ -657,13 +700,17 @@ private void saveSettings() {
section.put(PREF_COLUMNS, Arrays.toString(columnConfigs));
// Filter options
- section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS, filterOptions.filterPlugins);
- section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS, Arrays.toString(filterOptions.pluginPatterns));
- section.put(PREF_FILTER_OPTIONS_MISSING_ONLY, filterOptions.keysWithMissingEntriesOnly);
+ section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS,
+ filterOptions.filterPlugins);
+ section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS,
+ Arrays.toString(filterOptions.pluginPatterns));
+ section.put(PREF_FILTER_OPTIONS_MISSING_ONLY,
+ filterOptions.keysWithMissingEntriesOnly);
}
private void createTableViewer() {
- table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION | SWT.MULTI);
+ table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION
+ | SWT.MULTI);
tableViewer = new TableViewer(table);
table.setHeaderVisible(true);
toolkit.adapt(table);
@@ -674,9 +721,12 @@ private void createTableViewer() {
public void updateElement(int index) {
tableViewer.replace(entryList.getKey(index), index);
}
+
public void dispose() {
}
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {
}
});
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
@@ -696,7 +746,8 @@ public void menuAboutToShow(IMenuManager menu) {
});
Menu contextMenu = menuManager.createContextMenu(table);
table.setMenu(contextMenu);
- getSite().registerContextMenu(menuManager, getSite().getSelectionProvider());
+ getSite().registerContextMenu(menuManager,
+ getSite().getSelectionProvider());
}
protected void fillContextMenu(IMenuManager menu) {
@@ -706,8 +757,10 @@ protected void fillContextMenu(IMenuManager menu) {
menu.add(new Separator());
}
MenuManager showInSubMenu = new MenuManager("&Show In");
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN.create(window);
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN
+ .create(window);
showInSubMenu.add(item);
menu.add(showInSubMenu);
}
@@ -726,7 +779,8 @@ public void doSaveAs() {
}
@Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
setSite(site);
setInput(input);
this.input = (LocalizationEditorInput) input;
@@ -784,14 +838,15 @@ public void run() {
strPattern = "*".concat(strPattern); //$NON-NLS-1$
}
- ResourceBundleModel model = MessagesEditorPlugin.getModel(new NullProgressMonitor());
+ ResourceBundleModel model = MessagesEditorPlugin
+ .getModel(new NullProgressMonitor());
Locale[] locales = getLocales();
// Collect keys
ResourceBundleKey[] keys;
if (!filterOptions.filterPlugins
- || filterOptions.pluginPatterns == null
- || filterOptions.pluginPatterns.length == 0) {
+ || filterOptions.pluginPatterns == null
+ || filterOptions.pluginPatterns.length == 0) {
// Ensure the bundles are loaded
for (Locale locale : locales) {
@@ -812,7 +867,8 @@ public void run() {
String[] patterns = filterOptions.pluginPatterns;
StringMatcher[] matchers = new StringMatcher[patterns.length];
for (int i = 0; i < matchers.length; i++) {
- matchers[i] = new StringMatcher(patterns[i], true, false);
+ matchers[i] = new StringMatcher(patterns[i], true,
+ false);
}
int size = 0;
@@ -833,14 +889,17 @@ public void run() {
size += family.getKeyCount();
}
- ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(size);
+ ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(
+ size);
for (ResourceBundleFamily family : families) {
// Ensure the bundles are loaded
for (Locale locale : locales) {
try {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
+ ResourceBundle bundle = family
+ .getBundle(locale);
+ if (bundle != null) {
bundle.load();
+ }
} catch (CoreException e) {
MessagesEditorPlugin.log(e);
}
@@ -851,25 +910,30 @@ public void run() {
filteredKeys.add(key);
}
}
- keys = filteredKeys.toArray(new ResourceBundleKey[filteredKeys.size()]);
+ keys = filteredKeys
+ .toArray(new ResourceBundleKey[filteredKeys.size()]);
}
// Filter keys
ArrayList<ResourceBundleKey> filtered = new ArrayList<ResourceBundleKey>();
- StringMatcher keyMatcher = new StringMatcher(keyPattern, true, false);
- StringMatcher strMatcher = new StringMatcher(strPattern, true, false);
+ StringMatcher keyMatcher = new StringMatcher(keyPattern, true,
+ false);
+ StringMatcher strMatcher = new StringMatcher(strPattern, true,
+ false);
for (ResourceBundleKey key : keys) {
- if (monitor.isCanceled())
+ if (monitor.isCanceled()) {
return Status.OK_STATUS;
+ }
// Missing entries
if (filterOptions.keysWithMissingEntriesOnly) {
boolean hasMissingEntry = false;
// Check all columns for missing values
for (Object config : columnConfigs) {
- if (config == KEY)
+ if (config == KEY) {
continue;
+ }
Locale locale = (Locale) config;
String value = null;
try {
@@ -882,8 +946,9 @@ public void run() {
break;
}
}
- if (!hasMissingEntry)
+ if (!hasMissingEntry) {
continue;
+ }
}
// Match key
@@ -894,8 +959,9 @@ public void run() {
// Match entries
for (Object config : columnConfigs) {
- if (config == KEY)
+ if (config == KEY) {
continue;
+ }
Locale locale = (Locale) config;
String value = null;
try {
@@ -910,11 +976,14 @@ public void run() {
}
}
- ResourceBundleKey[] array = filtered.toArray(new ResourceBundleKey[filtered.size()]);
+ ResourceBundleKey[] array = filtered
+ .toArray(new ResourceBundleKey[filtered.size()]);
if (sortOrder == KEY) {
Arrays.sort(array, new Comparator<ResourceBundleKey>() {
- public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
- return o1.getName().compareToIgnoreCase(o2.getName());
+ public int compare(ResourceBundleKey o1,
+ ResourceBundleKey o2) {
+ return o1.getName().compareToIgnoreCase(
+ o2.getName());
}
});
} else {
@@ -923,8 +992,9 @@ public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
}
entryList = new ResourceBundleKeyList(array);
- if (monitor.isCanceled())
+ if (monitor.isCanceled()) {
return Status.OK_STATUS;
+ }
final ResourceBundleKeyList entryList2 = entryList;
Display.getDefault().syncExec(new Runnable() {
@@ -968,7 +1038,8 @@ public void updateLabels() {
}
/**
- * @param columnConfigs an array containing <code>KEY</code> and {@link Locale} values
+ * @param columnConfigs
+ * an array containing <code>KEY</code> and {@link Locale} values
*/
public void setColumns(Object[] columnConfigs) {
this.columnConfigs = columnConfigs;
@@ -992,10 +1063,12 @@ public void updateColumns() {
// Create columns
for (Object config : columnConfigs) {
- if (config == null)
+ if (config == null) {
continue;
+ }
- final TableViewerColumn viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
+ final TableViewerColumn viewerColumn = new TableViewerColumn(
+ tableViewer, SWT.NONE);
TableColumn column = viewerColumn.getColumn();
if (config == KEY) {
column.setText("Key");
@@ -1005,14 +1078,16 @@ public void updateColumns() {
column.setText("Default Bundle");
} else {
String displayName = locale.getDisplayName();
- if (displayName.equals("")) //$NON-NLS-1$
+ if (displayName.equals("")) {
displayName = locale.toString();
+ }
column.setText(displayName);
localesToUnload.remove(locale);
}
}
- viewerColumn.setLabelProvider(new LocalizationLabelProvider(config));
+ viewerColumn
+ .setLabelProvider(new LocalizationLabelProvider(config));
tableColumnLayout.setColumnData(column, new ColumnWeightData(33));
columns.add(column);
column.addSelectionListener(new SelectionAdapter() {
@@ -1040,8 +1115,9 @@ public void widgetSelected(SelectionEvent e) {
sortOrder = KEY; // fall back to default sort order
}
int index = configs.indexOf(sortOrder);
- if (index != -1)
+ if (index != -1) {
table.setSortColumn(columns.get(index));
+ }
refresh();
}
@@ -1051,18 +1127,22 @@ public void widgetSelected(SelectionEvent e) {
*/
@SuppressWarnings("unchecked")
@Override
- public Object getAdapter(Class adapter) {
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
if (IShowInSource.class == adapter) {
return new IShowInSource() {
public ShowInContext getShowInContext() {
ResourceBundleKey entry = getSelectedEntry();
- if (entry == null)
+ if (entry == null) {
return null;
- ResourceBundle bundle = entry.getParent().getBundle(new Locale(""));
- if (bundle == null)
+ }
+ ResourceBundle bundle = entry.getParent().getBundle(
+ new Locale(""));
+ if (bundle == null) {
return null;
+ }
Object resource = bundle.getUnderlyingResource();
- return new ShowInContext(resource, new StructuredSelection(resource));
+ return new ShowInContext(resource, new StructuredSelection(
+ resource));
}
};
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java
index f0bf4d97..e6addce3 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java
@@ -1,12 +1,12 @@
/*******************************************************************************
- * Copyright (c) 2008 Stefan Mücke and others.
+ * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan Mücke - initial API and implementation
+ * Stefan M�cke - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.nls.internal.ui.model;
@@ -32,489 +32,541 @@
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.pde.core.plugin.IFragmentModel;
-import org.eclipse.pde.core.plugin.IPluginModelBase;
-import org.eclipse.pde.core.plugin.PluginRegistry;
+import org.eclipse.osgi.service.resolver.BundleDescription;
/**
- * A <code>ResourceBundleModel</code> is the host for all {@link ResourceBundleFamily} elements.
+ * A <code>ResourceBundleModel</code> is the host for all
+ * {@link ResourceBundleFamily} elements.
*/
public class ResourceBundleModel extends ResourceBundleElement {
- private static final String PROPERTIES_SUFFIX = ".properties"; //$NON-NLS-1$
+ private static final String PROPERTIES_SUFFIX = ".properties"; //$NON-NLS-1$
- private static final String JAVA_NATURE = "org.eclipse.jdt.core.javanature"; //$NON-NLS-1$
+ private static final String JAVA_NATURE = "org.eclipse.jdt.core.javanature"; //$NON-NLS-1$
- private ArrayList<ResourceBundleFamily> bundleFamilies = new ArrayList<ResourceBundleFamily>();
+ private ArrayList<ResourceBundleFamily> bundleFamilies = new ArrayList<ResourceBundleFamily>();
- /**
- * The locales for which all bundles have been loaded.
- */
- // TODO Perhaps we should add reference counting to prevent unexpected unloading of bundles
- private HashSet<Locale> loadedLocales = new HashSet<Locale>();
+ /**
+ * The locales for which all bundles have been loaded.
+ */
+ // TODO Perhaps we should add reference counting to prevent unexpected
+ // unloading of bundles
+ private HashSet<Locale> loadedLocales = new HashSet<Locale>();
- public ResourceBundleModel(IProgressMonitor monitor) {
- super(null);
- try {
- populateFromWorkspace(monitor);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
+ public ResourceBundleModel(IProgressMonitor monitor) {
+ super(null);
+ try {
+ populateFromWorkspace(monitor);
+ } catch (CoreException e) {
+ MessagesEditorPlugin.log(e);
}
-
- /**
- * Returns all resource bundle families contained in this model.
- *
- * @return all resource bundle families contained in this model
- */
- public ResourceBundleFamily[] getFamilies() {
- return bundleFamilies.toArray(new ResourceBundleFamily[bundleFamilies.size()]);
+ }
+
+ /**
+ * Returns all resource bundle families contained in this model.
+ *
+ * @return all resource bundle families contained in this model
+ */
+ public ResourceBundleFamily[] getFamilies() {
+ return bundleFamilies.toArray(new ResourceBundleFamily[bundleFamilies
+ .size()]);
+ }
+
+ public ResourceBundleFamily[] getFamiliesForPluginId(String pluginId) {
+ ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
+ for (ResourceBundleFamily family : bundleFamilies) {
+ if (family.getPluginId().equals(pluginId)) {
+ found.add(family);
+ }
}
-
- public ResourceBundleFamily[] getFamiliesForPluginId(String pluginId) {
- ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
- for (ResourceBundleFamily family : bundleFamilies) {
- if (family.getPluginId().equals(pluginId)) {
- found.add(family);
- }
- }
- return found.toArray(new ResourceBundleFamily[found.size()]);
+ return found.toArray(new ResourceBundleFamily[found.size()]);
+ }
+
+ public ResourceBundleFamily[] getFamiliesForProjectName(String projectName) {
+ ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
+ for (ResourceBundleFamily family : bundleFamilies) {
+ if (family.getProjectName().equals(projectName)) {
+ found.add(family);
+ }
}
-
- public ResourceBundleFamily[] getFamiliesForProjectName(String projectName) {
- ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
- for (ResourceBundleFamily family : bundleFamilies) {
- if (family.getProjectName().equals(projectName)) {
- found.add(family);
- }
- }
- return found.toArray(new ResourceBundleFamily[found.size()]);
+ return found.toArray(new ResourceBundleFamily[found.size()]);
+ }
+
+ public ResourceBundleFamily[] getFamiliesForProject(IProject project) {
+ return getFamiliesForProjectName(project.getName());
+ }
+
+ /**
+ * Returns an array of all currently known bundle keys. This always includes
+ * the keys from the default bundles and may include some additional keys
+ * from bundles that have been loaded sometime and that contain keys not
+ * found in a bundle's default bundle. When a bundle is unloaded, these
+ * additional keys will not be removed from the model.
+ *
+ * @return the array of bundles keys
+ * @throws CoreException
+ */
+ public ResourceBundleKey[] getAllKeys() throws CoreException {
+ Locale root = new Locale("", "", "");
+
+ // Ensure default bundle is loaded and count keys
+ int size = 0;
+ for (ResourceBundleFamily family : bundleFamilies) {
+ ResourceBundle bundle = family.getBundle(root);
+ if (bundle != null)
+ bundle.load();
+ size += family.getKeyCount();
}
- public ResourceBundleFamily[] getFamiliesForProject(IProject project) {
- return getFamiliesForProjectName(project.getName());
+ ArrayList<ResourceBundleKey> allKeys = new ArrayList<ResourceBundleKey>(
+ size);
+ for (ResourceBundleFamily family : bundleFamilies) {
+ ResourceBundleKey[] keys = family.getKeys();
+ for (ResourceBundleKey key : keys) {
+ allKeys.add(key);
+ }
}
- /**
- * Returns an array of all currently known bundle keys. This always includes
- * the keys from the default bundles and may include some additional keys
- * from bundles that have been loaded sometime and that contain keys not found in
- * a bundle's default bundle. When a bundle is unloaded, these additional keys
- * will not be removed from the model.
- *
- * @return the array of bundles keys
- * @throws CoreException
- */
- public ResourceBundleKey[] getAllKeys() throws CoreException {
- Locale root = new Locale("", "", "");
-
- // Ensure default bundle is loaded and count keys
- int size = 0;
- for (ResourceBundleFamily family : bundleFamilies) {
- ResourceBundle bundle = family.getBundle(root);
- if (bundle != null)
- bundle.load();
- size += family.getKeyCount();
- }
-
- ArrayList<ResourceBundleKey> allKeys = new ArrayList<ResourceBundleKey>(size);
- for (ResourceBundleFamily family : bundleFamilies) {
- ResourceBundleKey[] keys = family.getKeys();
- for (ResourceBundleKey key : keys) {
- allKeys.add(key);
- }
- }
-
- return allKeys.toArray(new ResourceBundleKey[allKeys.size()]);
+ return allKeys.toArray(new ResourceBundleKey[allKeys.size()]);
+ }
+
+ /**
+ * Loads all the bundles for the given locale into memory.
+ *
+ * @param locale
+ * the locale of the bundles to load
+ * @throws CoreException
+ */
+ public void loadBundles(Locale locale) throws CoreException {
+ ResourceBundleFamily[] families = getFamilies();
+ for (ResourceBundleFamily family : families) {
+ ResourceBundle bundle = family.getBundle(locale);
+ if (bundle != null)
+ bundle.load();
}
-
- /**
- * Loads all the bundles for the given locale into memory.
- *
- * @param locale the locale of the bundles to load
- * @throws CoreException
- */
- public void loadBundles(Locale locale) throws CoreException {
- ResourceBundleFamily[] families = getFamilies();
- for (ResourceBundleFamily family : families) {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.load();
- }
- loadedLocales.add(locale);
+ loadedLocales.add(locale);
+ }
+
+ /**
+ * Unloads all the bundles for the given locale from this model. The default
+ * bundle cannot be unloaded. Such a request will be ignored.
+ *
+ * @param locale
+ * the locale of the bundles to unload
+ */
+ public void unloadBundles(Locale locale) {
+ if ("".equals(locale.getLanguage()))
+ return; // never unload the default bundles
+
+ ResourceBundleFamily[] families = getFamilies();
+ for (ResourceBundleFamily family : families) {
+ ResourceBundle bundle = family.getBundle(locale);
+ if (bundle != null)
+ bundle.unload();
}
+ loadedLocales.remove(locale);
+ }
+
+ /**
+ * @param monitor
+ * @throws CoreException
+ */
+ private void populateFromWorkspace(IProgressMonitor monitor)
+ throws CoreException {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceRoot root = workspace.getRoot();
+ IProject[] projects = root.getProjects();
+ for (IProject project : projects) {
+ try {
+ if (!project.isOpen())
+ continue;
+
+ IJavaProject javaProject = (IJavaProject) project
+ .getNature(JAVA_NATURE);
+ String pluginId = null;
- /**
- * Unloads all the bundles for the given locale from this model. The default
- * bundle cannot be unloaded. Such a request will be ignored.
- *
- * @param locale the locale of the bundles to unload
- */
- public void unloadBundles(Locale locale) {
- if ("".equals(locale.getLanguage()))
- return; // never unload the default bundles
-
- ResourceBundleFamily[] families = getFamilies();
- for (ResourceBundleFamily family : families) {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.unload();
- }
- loadedLocales.remove(locale);
- }
+ try {
+ Class IFragmentModel = Class
+ .forName("org.eclipse.pde.core.plugin.IFragmentModel");
+ Class IPluginModelBase = Class
+ .forName("org.eclipse.pde.core.plugin.IPluginModelBase");
+ Class PluginRegistry = Class
+ .forName("org.eclipse.pde.core.plugin.PluginRegistry");
+ Class IPluginBase = Class
+ .forName("org.eclipse.pde.core.plugin.IPluginBase");
+ Class PluginFragmentModel = Class
+ .forName("org.eclipse.core.runtime.model.PluginFragmentModel");
+
+ // Plugin and fragment projects
+ Class pluginModel = (Class) PluginRegistry.getMethod(
+ "findModel", IProject.class).invoke(null, project);
+ if (pluginModel != null) {
+ // Get plugin id
+ BundleDescription bd = (BundleDescription) IPluginModelBase
+ .getMethod("getBundleDescription").invoke(
+ pluginModel);
+ pluginId = bd.getName();
+ // OSGi bundle name
+ if (pluginId == null) {
+ Object pluginBase = IPluginModelBase.getMethod(
+ "getPluginBase").invoke(pluginModel);
+ pluginId = (String) IPluginBase.getMethod("getId")
+ .invoke(pluginBase); // non-OSGi
+ // plug-in id
+ }
- private void populateFromWorkspace(IProgressMonitor monitor) throws CoreException {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IProject[] projects = root.getProjects();
- for (IProject project : projects) {
- try {
- if (!project.isOpen())
- continue;
-
- IJavaProject javaProject = (IJavaProject) project.getNature(JAVA_NATURE);
-
- // Plugin and fragment projects
- IPluginModelBase pluginModel = PluginRegistry.findModel(project);
- String pluginId = null;
- if (pluginModel != null) {
- // Get plugin id
- pluginId = pluginModel.getBundleDescription().getName(); // OSGi bundle name
- if (pluginId == null) {
- pluginId = pluginModel.getPluginBase().getId(); // non-OSGi plug-in id
- }
- boolean isFragment = pluginModel instanceof IFragmentModel;
- if (isFragment) {
- IFragmentModel fragmentModel = (IFragmentModel) pluginModel;
- pluginId = fragmentModel.getFragment().getPluginId();
- }
+ boolean isFragment = IFragmentModel
+ .isInstance(pluginModel);
+ if (isFragment) {
+ Object pfm = IFragmentModel
+ .getMethod("getFragment");
+ pluginId = (String) PluginFragmentModel.getMethod(
+ "getPluginId").invoke(pfm);
+ }
- // Look for additional 'nl' resources
- IFolder nl = project.getFolder("nl"); //$NON-NLS-1$
- if (isFragment && nl.exists()) {
- IResource[] members = nl.members();
- for (IResource member : members) {
- if (member instanceof IFolder) {
- IFolder langFolder = (IFolder) member;
- String language = langFolder.getName();
-
- // Collect property files
- IFile[] propertyFiles = collectPropertyFiles(langFolder);
- for (IFile file : propertyFiles) {
- // Compute path name
- IPath path = file.getProjectRelativePath();
- String country = ""; //$NON-NLS-1$
- String packageName = null;
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
-
- // Segment 0: 'nl'
- // Segment 1: language code
- // Segment 2: (country code)
- int begin = 2;
- if (segmentCount > 2 && isCountry(path.segment(2))) {
- begin = 3;
- country = path.segment(2);
- }
-
- for (int i = begin; i < segmentCount - 1; i++) {
- if (i > begin)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
-
- String baseName = getBaseName(file.getName());
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
- }
- }
- }
+ // Look for additional 'nl' resources
+ IFolder nl = project.getFolder("nl"); //$NON-NLS-1$
+ if (isFragment && nl.exists()) {
+ IResource[] members = nl.members();
+ for (IResource member : members) {
+ if (member instanceof IFolder) {
+ IFolder langFolder = (IFolder) member;
+ String language = langFolder.getName();
+
+ // Collect property files
+ IFile[] propertyFiles = collectPropertyFiles(langFolder);
+ for (IFile file : propertyFiles) {
+ // Compute path name
+ IPath path = file
+ .getProjectRelativePath();
+ String country = ""; //$NON-NLS-1$
+ String packageName = null;
+ int segmentCount = path.segmentCount();
+ if (segmentCount > 1) {
+ StringBuilder builder = new StringBuilder();
+
+ // Segment 0: 'nl'
+ // Segment 1: language code
+ // Segment 2: (country code)
+ int begin = 2;
+ if (segmentCount > 2
+ && isCountry(path
+ .segment(2))) {
+ begin = 3;
+ country = path.segment(2);
+ }
+
+ for (int i = begin; i < segmentCount - 1; i++) {
+ if (i > begin)
+ builder.append('.');
+ builder.append(path.segment(i));
+ }
+ packageName = builder.toString();
}
- // Collect property files
- if (isFragment || javaProject == null) {
- IFile[] propertyFiles = collectPropertyFiles(project);
- for (IFile file : propertyFiles) {
- IPath path = file.getProjectRelativePath();
- int segmentCount = path.segmentCount();
-
- if (segmentCount > 0 && path.segment(0).equals("nl")) //$NON-NLS-1$
- continue; // 'nl' resource have been processed above
-
- // Guess package name
- String packageName = null;
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < segmentCount - 1; i++) {
- if (i > 0)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
-
- String baseName = getBaseName(file.getName());
- String language = getLanguage(file.getName());
- String country = getCountry(file.getName());
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
- }
- }
+ String baseName = getBaseName(file
+ .getName());
+
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId,
+ packageName, baseName);
+ addBundle(family,
+ getLocale(language, country),
+ file);
+ }
+ }
+ }
+ }
+ // Collect property files
+ if (isFragment || javaProject == null) {
+ IFile[] propertyFiles = collectPropertyFiles(project);
+ for (IFile file : propertyFiles) {
+ IPath path = file.getProjectRelativePath();
+ int segmentCount = path.segmentCount();
+
+ if (segmentCount > 0
+ && path.segment(0).equals("nl")) //$NON-NLS-1$
+ continue; // 'nl' resource have been
+ // processed
+ // above
+
+ // Guess package name
+ String packageName = null;
+ if (segmentCount > 1) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < segmentCount - 1; i++) {
+ if (i > 0)
+ builder.append('.');
+ builder.append(path.segment(i));
+ }
+ packageName = builder.toString();
}
- // Look for resource bundles in Java packages (output folders, e.g. 'bin', will be ignored)
- if (javaProject != null) {
- IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
- for (IClasspathEntry entry : classpathEntries) {
- if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- IPath path = entry.getPath();
- IFolder folder = workspace.getRoot().getFolder(path);
- IFile[] propertyFiles = collectPropertyFiles(folder);
-
- for (IFile file : propertyFiles) {
- String name = file.getName();
- String baseName = getBaseName(name);
- String language = getLanguage(name);
- String country = getCountry(name);
- IPackageFragment pf = javaProject.findPackageFragment(file.getParent()
- .getFullPath());
- String packageName = pf.getElementName();
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
-
- addBundle(family, getLocale(language, country), file);
- }
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- IPackageFragmentRoot[] findPackageFragmentRoots = javaProject.findPackageFragmentRoots(entry);
- for (IPackageFragmentRoot packageFragmentRoot : findPackageFragmentRoots) {
- IJavaElement[] children = packageFragmentRoot.getChildren();
- for (IJavaElement child : children) {
- IPackageFragment pf = (IPackageFragment) child;
- Object[] nonJavaResources = pf.getNonJavaResources();
-
- for (Object resource : nonJavaResources) {
- if (resource instanceof IJarEntryResource) {
- IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
- String name = jarEntryResource.getName();
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- String baseName = getBaseName(name);
- String language = getLanguage(name);
- String country = getCountry(name);
- String packageName = pf.getElementName();
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
-
- addBundle(
- family,
- getLocale(language, country),
- jarEntryResource);
- }
- }
- }
- }
- }
- }
- }
+ String baseName = getBaseName(file.getName());
+ String language = getLanguage(file.getName());
+ String country = getCountry(file.getName());
- // Collect non-Java resources
- Object[] nonJavaResources = javaProject.getNonJavaResources();
- ArrayList<IFile> files = new ArrayList<IFile>();
- for (Object resource : nonJavaResources) {
- if (resource instanceof IContainer) {
- IContainer container = (IContainer) resource;
- collectPropertyFiles(container, files);
- } else if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- String name = file.getName();
- if (isIgnoredFilename(name))
- continue;
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- files.add(file);
- }
- }
- }
- for (IFile file : files) {
-
- // Convert path to package name format
- IPath path = file.getProjectRelativePath();
- String packageName = null;
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < segmentCount - 1; i++) {
- if (i > 0)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
-
- String baseName = getBaseName(file.getName());
- String language = getLanguage(file.getName());
- String country = getCountry(file.getName());
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId,
+ packageName, baseName);
+ addBundle(family, getLocale(language, country),
+ file);
+ }
+ }
+
+ }
+ } catch (Throwable e) {
+ // MessagesEditorPlugin.log(e);
+ }
+
+ // Look for resource bundles in Java packages (output folders,
+ // e.g. 'bin', will be ignored)
+ if (javaProject != null) {
+ IClasspathEntry[] classpathEntries = javaProject
+ .getResolvedClasspath(true);
+ for (IClasspathEntry entry : classpathEntries) {
+ if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
+ IPath path = entry.getPath();
+ IFolder folder = workspace.getRoot()
+ .getFolder(path);
+ IFile[] propertyFiles = collectPropertyFiles(folder);
+
+ for (IFile file : propertyFiles) {
+ String name = file.getName();
+ String baseName = getBaseName(name);
+ String language = getLanguage(name);
+ String country = getCountry(name);
+ IPackageFragment pf = javaProject
+ .findPackageFragment(file.getParent()
+ .getFullPath());
+ String packageName = pf.getElementName();
+
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId,
+ packageName, baseName);
+
+ addBundle(family, getLocale(language, country),
+ file);
+ }
+ } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
+ IPackageFragmentRoot[] findPackageFragmentRoots = javaProject
+ .findPackageFragmentRoots(entry);
+ for (IPackageFragmentRoot packageFragmentRoot : findPackageFragmentRoots) {
+ IJavaElement[] children = packageFragmentRoot
+ .getChildren();
+ for (IJavaElement child : children) {
+ IPackageFragment pf = (IPackageFragment) child;
+ Object[] nonJavaResources = pf
+ .getNonJavaResources();
+
+ for (Object resource : nonJavaResources) {
+ if (resource instanceof IJarEntryResource) {
+ IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
+ String name = jarEntryResource
+ .getName();
+ if (name.endsWith(PROPERTIES_SUFFIX)) {
+ String baseName = getBaseName(name);
+ String language = getLanguage(name);
+ String country = getCountry(name);
+ String packageName = pf
+ .getElementName();
ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
+ project.getName(),
+ pluginId, packageName,
+ baseName);
+
+ addBundle(
+ family,
+ getLocale(language,
+ country),
+ jarEntryResource);
+ }
}
-
+ }
}
- } catch (Exception e) {
- MessagesEditorPlugin.log(e);
+ }
}
- }
- }
+ }
- private IFile[] collectPropertyFiles(IContainer container) throws CoreException {
- ArrayList<IFile> files = new ArrayList<IFile>();
- collectPropertyFiles(container, files);
- return files.toArray(new IFile[files.size()]);
- }
-
- private void collectPropertyFiles(IContainer container, ArrayList<IFile> files) throws CoreException {
- IResource[] members = container.members();
- for (IResource resource : members) {
- if (!resource.exists())
- continue;
+ // Collect non-Java resources
+ Object[] nonJavaResources = javaProject
+ .getNonJavaResources();
+ ArrayList<IFile> files = new ArrayList<IFile>();
+ for (Object resource : nonJavaResources) {
if (resource instanceof IContainer) {
- IContainer childContainer = (IContainer) resource;
- collectPropertyFiles(childContainer, files);
+ IContainer container = (IContainer) resource;
+ collectPropertyFiles(container, files);
} else if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- String name = file.getName();
- if (file.getProjectRelativePath().segmentCount() == 0 && isIgnoredFilename(name))
- continue;
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- files.add(file);
- }
+ IFile file = (IFile) resource;
+ String name = file.getName();
+ if (isIgnoredFilename(name))
+ continue;
+ if (name.endsWith(PROPERTIES_SUFFIX)) {
+ files.add(file);
+ }
+ }
+ }
+ for (IFile file : files) {
+
+ // Convert path to package name format
+ IPath path = file.getProjectRelativePath();
+ String packageName = null;
+ int segmentCount = path.segmentCount();
+ if (segmentCount > 1) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < segmentCount - 1; i++) {
+ if (i > 0)
+ builder.append('.');
+ builder.append(path.segment(i));
+ }
+ packageName = builder.toString();
}
- }
- }
-
- private boolean isCountry(String name) {
- if (name == null || name.length() != 2)
- return false;
- char c1 = name.charAt(0);
- char c2 = name.charAt(1);
- return 'A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z';
- }
- private Locale getLocale(String language, String country) {
- if (language == null)
- language = ""; //$NON-NLS-1$
- if (country == null)
- country = ""; //$NON-NLS-1$
- return new Locale(language, country);
- }
+ String baseName = getBaseName(file.getName());
+ String language = getLanguage(file.getName());
+ String country = getCountry(file.getName());
- private void addBundle(ResourceBundleFamily family, Locale locale, Object resource) throws CoreException {
- ResourceBundle bundle = new ResourceBundle(family, resource, locale);
- if ("".equals(locale.getLanguage()))
- bundle.load();
- family.addBundle(bundle);
- }
+ ResourceBundleFamily family = getOrCreateFamily(
+ project.getName(), pluginId, packageName,
+ baseName);
+ addBundle(family, getLocale(language, country), file);
+ }
- private String getBaseName(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(0, len - 6);
- } else {
- return name.substring(0, len - 3);
- }
}
- return name;
+ } catch (Exception e) {
+ MessagesEditorPlugin.log(e);
+ }
}
-
- private String getLanguage(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(len - 5, len - 3);
- } else {
- return name.substring(len - 2);
- }
+ }
+
+ private IFile[] collectPropertyFiles(IContainer container)
+ throws CoreException {
+ ArrayList<IFile> files = new ArrayList<IFile>();
+ collectPropertyFiles(container, files);
+ return files.toArray(new IFile[files.size()]);
+ }
+
+ private void collectPropertyFiles(IContainer container,
+ ArrayList<IFile> files) throws CoreException {
+ IResource[] members = container.members();
+ for (IResource resource : members) {
+ if (!resource.exists())
+ continue;
+ if (resource instanceof IContainer) {
+ IContainer childContainer = (IContainer) resource;
+ collectPropertyFiles(childContainer, files);
+ } else if (resource instanceof IFile) {
+ IFile file = (IFile) resource;
+ String name = file.getName();
+ if (file.getProjectRelativePath().segmentCount() == 0
+ && isIgnoredFilename(name))
+ continue;
+ if (name.endsWith(PROPERTIES_SUFFIX)) {
+ files.add(file);
}
- return ""; //$NON-NLS-1$
+ }
}
-
- private String getCountry(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(len - 2);
- } else {
- return ""; //$NON-NLS-1$
- }
- }
+ }
+
+ private boolean isCountry(String name) {
+ if (name == null || name.length() != 2)
+ return false;
+ char c1 = name.charAt(0);
+ char c2 = name.charAt(1);
+ return 'A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z';
+ }
+
+ private Locale getLocale(String language, String country) {
+ if (language == null)
+ language = ""; //$NON-NLS-1$
+ if (country == null)
+ country = ""; //$NON-NLS-1$
+ return new Locale(language, country);
+ }
+
+ private void addBundle(ResourceBundleFamily family, Locale locale,
+ Object resource) throws CoreException {
+ ResourceBundle bundle = new ResourceBundle(family, resource, locale);
+ if ("".equals(locale.getLanguage()))
+ bundle.load();
+ family.addBundle(bundle);
+ }
+
+ private String getBaseName(String filename) {
+ if (!filename.endsWith(PROPERTIES_SUFFIX))
+ throw new IllegalArgumentException();
+ String name = filename.substring(0, filename.length() - 11);
+ int len = name.length();
+ if (len > 3 && name.charAt(len - 3) == '_') {
+ if (len > 6 && name.charAt(len - 6) == '_') {
+ return name.substring(0, len - 6);
+ } else {
+ return name.substring(0, len - 3);
+ }
+ }
+ return name;
+ }
+
+ private String getLanguage(String filename) {
+ if (!filename.endsWith(PROPERTIES_SUFFIX))
+ throw new IllegalArgumentException();
+ String name = filename.substring(0, filename.length() - 11);
+ int len = name.length();
+ if (len > 3 && name.charAt(len - 3) == '_') {
+ if (len > 6 && name.charAt(len - 6) == '_') {
+ return name.substring(len - 5, len - 3);
+ } else {
+ return name.substring(len - 2);
+ }
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ private String getCountry(String filename) {
+ if (!filename.endsWith(PROPERTIES_SUFFIX))
+ throw new IllegalArgumentException();
+ String name = filename.substring(0, filename.length() - 11);
+ int len = name.length();
+ if (len > 3 && name.charAt(len - 3) == '_') {
+ if (len > 6 && name.charAt(len - 6) == '_') {
+ return name.substring(len - 2);
+ } else {
return ""; //$NON-NLS-1$
+ }
}
+ return ""; //$NON-NLS-1$
+ }
- private ResourceBundleFamily getOrCreateFamily(String projectName, String pluginId, String packageName,
- String baseName) {
+ private ResourceBundleFamily getOrCreateFamily(String projectName,
+ String pluginId, String packageName, String baseName) {
- // Ignore project name
- if (pluginId != null)
- projectName = null;
+ // Ignore project name
+ if (pluginId != null)
+ projectName = null;
- for (ResourceBundleFamily family : bundleFamilies) {
- if (areEqual(family.getProjectName(), projectName)
- && areEqual(family.getPluginId(), pluginId)
- && areEqual(family.getPackageName(), packageName)
- && areEqual(family.getBaseName(), baseName)) {
- return family;
- }
- }
- ResourceBundleFamily family = new ResourceBundleFamily(
- this,
- projectName,
- pluginId,
- packageName,
- baseName);
- bundleFamilies.add(family);
+ for (ResourceBundleFamily family : bundleFamilies) {
+ if (areEqual(family.getProjectName(), projectName)
+ && areEqual(family.getPluginId(), pluginId)
+ && areEqual(family.getPackageName(), packageName)
+ && areEqual(family.getBaseName(), baseName)) {
return family;
+ }
}
-
- private boolean isIgnoredFilename(String filename) {
- return filename.equals("build.properties") || filename.equals("logging.properties"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private boolean areEqual(String str1, String str2) {
- return str1 == null && str2 == null || str1 != null && str1.equals(str2);
- }
+ ResourceBundleFamily family = new ResourceBundleFamily(this,
+ projectName, pluginId, packageName, baseName);
+ bundleFamilies.add(family);
+ return family;
+ }
+
+ private boolean isIgnoredFilename(String filename) {
+ return filename.equals("build.properties") || filename.equals("logging.properties"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ private boolean areEqual(String str1, String str2) {
+ return str1 == null && str2 == null || str1 != null
+ && str1.equals(str2);
+ }
}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/.classpath b/org.eclipse.babel.tapiji.tools.core.ui/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/.classpath
rename to org.eclipse.babel.tapiji.tools.core.ui/.classpath
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/.project b/org.eclipse.babel.tapiji.tools.core.ui/.project
new file mode 100644
index 00000000..8dce816c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.tapiji.tools.core.ui</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.core.ui/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..8f5d6954
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/META-INF/MANIFEST.MF
@@ -0,0 +1,42 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: TapiJI Tools Core UI
+Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.core.ui;singleton:=true
+Bundle-Version: 0.0.2.qualifier
+Bundle-Activator: org.eclipse.babel.tapiji.tools.core.ui.Activator
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.eclipse.jdt.ui;bundle-version="3.6.2",
+ org.eclipse.babel.tapiji.tools.core;bundle-version="0.0.2";visibility:=reexport,
+ org.eclipse.ui.ide;bundle-version="3.6.2",
+ org.eclipse.jface.text;bundle-version="3.6.1",
+ org.eclipse.jdt.core;bundle-version="3.6.2",
+ org.eclipse.core.resources;bundle-version="3.6.1",
+ org.eclipse.ui.editors,
+ org.eclipse.babel.editor;bundle-version="0.8.0";visibility:=reexport
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.babel.tapiji.tools.core.ui,
+ org.eclipse.babel.tapiji.tools.core.ui.analyzer,
+ org.eclipse.babel.tapiji.tools.core.ui.builder,
+ org.eclipse.babel.tapiji.tools.core.ui.decorators,
+ org.eclipse.babel.tapiji.tools.core.ui.dialogs,
+ org.eclipse.babel.tapiji.tools.core.ui.extensions,
+ org.eclipse.babel.tapiji.tools.core.ui.filters,
+ org.eclipse.babel.tapiji.tools.core.ui.markers,
+ org.eclipse.babel.tapiji.tools.core.ui.memento,
+ org.eclipse.babel.tapiji.tools.core.ui.menus,
+ org.eclipse.babel.tapiji.tools.core.ui.preferences,
+ org.eclipse.babel.tapiji.tools.core.ui.quickfix,
+ org.eclipse.babel.tapiji.tools.core.ui.utils,
+ org.eclipse.babel.tapiji.tools.core.ui.views.messagesview,
+ org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd,
+ org.eclipse.babel.tapiji.tools.core.ui.widgets,
+ org.eclipse.babel.tapiji.tools.core.ui.widgets.event,
+ org.eclipse.babel.tapiji.tools.core.ui.widgets.filter,
+ org.eclipse.babel.tapiji.tools.core.ui.widgets.listener,
+ org.eclipse.babel.tapiji.tools.core.ui.widgets.provider,
+ org.eclipse.babel.tapiji.tools.core.ui.widgets.sorter
+Import-Package: org.eclipse.core.filebuffers,
+ org.eclipse.ui.texteditor
+Bundle-Vendor: Vienna University of Technology
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/build.properties b/org.eclipse.babel.tapiji.tools.core.ui/build.properties
new file mode 100644
index 00000000..285b8bf4
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/build.properties
@@ -0,0 +1,6 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml,\
+ icons/
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html
new file mode 100644
index 00000000..84ec2511
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html
@@ -0,0 +1,261 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
+<title>Eclipse Public License - Version 1.0</title>
+<style type="text/css">
+ body {
+ size: 8.5in 11.0in;
+ margin: 0.25in 0.5in 0.25in 0.5in;
+ tab-interval: 0.5in;
+ }
+ p {
+ margin-left: auto;
+ margin-top: 0.5em;
+ margin-bottom: 0.5em;
+ }
+ p.list {
+ margin-left: 0.5in;
+ margin-top: 0.05em;
+ margin-bottom: 0.05em;
+ }
+ </style>
+
+</head>
+
+<body lang="EN-US">
+
+<p align=center><b>Eclipse Public License - v 1.0</b></p>
+
+<p>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
+PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
+DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
+AGREEMENT.</p>
+
+<p><b>1. DEFINITIONS</b></p>
+
+<p>"Contribution" means:</p>
+
+<p class="list">a) in the case of the initial Contributor, the initial
+code and documentation distributed under this Agreement, and</p>
+<p class="list">b) in the case of each subsequent Contributor:</p>
+<p class="list">i) changes to the Program, and</p>
+<p class="list">ii) additions to the Program;</p>
+<p class="list">where such changes and/or additions to the Program
+originate from and are distributed by that particular Contributor. A
+Contribution 'originates' from a Contributor if it was added to the
+Program by such Contributor itself or anyone acting on such
+Contributor's behalf. Contributions do not include additions to the
+Program which: (i) are separate modules of software distributed in
+conjunction with the Program under their own license agreement, and (ii)
+are not derivative works of the Program.</p>
+
+<p>"Contributor" means any person or entity that distributes
+the Program.</p>
+
+<p>"Licensed Patents" mean patent claims licensable by a
+Contributor which are necessarily infringed by the use or sale of its
+Contribution alone or when combined with the Program.</p>
+
+<p>"Program" means the Contributions distributed in accordance
+with this Agreement.</p>
+
+<p>"Recipient" means anyone who receives the Program under
+this Agreement, including all Contributors.</p>
+
+<p><b>2. GRANT OF RIGHTS</b></p>
+
+<p class="list">a) Subject to the terms of this Agreement, each
+Contributor hereby grants Recipient a non-exclusive, worldwide,
+royalty-free copyright license to reproduce, prepare derivative works
+of, publicly display, publicly perform, distribute and sublicense the
+Contribution of such Contributor, if any, and such derivative works, in
+source code and object code form.</p>
+
+<p class="list">b) Subject to the terms of this Agreement, each
+Contributor hereby grants Recipient a non-exclusive, worldwide,
+royalty-free patent license under Licensed Patents to make, use, sell,
+offer to sell, import and otherwise transfer the Contribution of such
+Contributor, if any, in source code and object code form. This patent
+license shall apply to the combination of the Contribution and the
+Program if, at the time the Contribution is added by the Contributor,
+such addition of the Contribution causes such combination to be covered
+by the Licensed Patents. The patent license shall not apply to any other
+combinations which include the Contribution. No hardware per se is
+licensed hereunder.</p>
+
+<p class="list">c) Recipient understands that although each Contributor
+grants the licenses to its Contributions set forth herein, no assurances
+are provided by any Contributor that the Program does not infringe the
+patent or other intellectual property rights of any other entity. Each
+Contributor disclaims any liability to Recipient for claims brought by
+any other entity based on infringement of intellectual property rights
+or otherwise. As a condition to exercising the rights and licenses
+granted hereunder, each Recipient hereby assumes sole responsibility to
+secure any other intellectual property rights needed, if any. For
+example, if a third party patent license is required to allow Recipient
+to distribute the Program, it is Recipient's responsibility to acquire
+that license before distributing the Program.</p>
+
+<p class="list">d) Each Contributor represents that to its knowledge it
+has sufficient copyright rights in its Contribution, if any, to grant
+the copyright license set forth in this Agreement.</p>
+
+<p><b>3. REQUIREMENTS</b></p>
+
+<p>A Contributor may choose to distribute the Program in object code
+form under its own license agreement, provided that:</p>
+
+<p class="list">a) it complies with the terms and conditions of this
+Agreement; and</p>
+
+<p class="list">b) its license agreement:</p>
+
+<p class="list">i) effectively disclaims on behalf of all Contributors
+all warranties and conditions, express and implied, including warranties
+or conditions of title and non-infringement, and implied warranties or
+conditions of merchantability and fitness for a particular purpose;</p>
+
+<p class="list">ii) effectively excludes on behalf of all Contributors
+all liability for damages, including direct, indirect, special,
+incidental and consequential damages, such as lost profits;</p>
+
+<p class="list">iii) states that any provisions which differ from this
+Agreement are offered by that Contributor alone and not by any other
+party; and</p>
+
+<p class="list">iv) states that source code for the Program is available
+from such Contributor, and informs licensees how to obtain it in a
+reasonable manner on or through a medium customarily used for software
+exchange.</p>
+
+<p>When the Program is made available in source code form:</p>
+
+<p class="list">a) it must be made available under this Agreement; and</p>
+
+<p class="list">b) a copy of this Agreement must be included with each
+copy of the Program.</p>
+
+<p>Contributors may not remove or alter any copyright notices contained
+within the Program.</p>
+
+<p>Each Contributor must identify itself as the originator of its
+Contribution, if any, in a manner that reasonably allows subsequent
+Recipients to identify the originator of the Contribution.</p>
+
+<p><b>4. COMMERCIAL DISTRIBUTION</b></p>
+
+<p>Commercial distributors of software may accept certain
+responsibilities with respect to end users, business partners and the
+like. While this license is intended to facilitate the commercial use of
+the Program, the Contributor who includes the Program in a commercial
+product offering should do so in a manner which does not create
+potential liability for other Contributors. Therefore, if a Contributor
+includes the Program in a commercial product offering, such Contributor
+("Commercial Contributor") hereby agrees to defend and
+indemnify every other Contributor ("Indemnified Contributor")
+against any losses, damages and costs (collectively "Losses")
+arising from claims, lawsuits and other legal actions brought by a third
+party against the Indemnified Contributor to the extent caused by the
+acts or omissions of such Commercial Contributor in connection with its
+distribution of the Program in a commercial product offering. The
+obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In
+order to qualify, an Indemnified Contributor must: a) promptly notify
+the Commercial Contributor in writing of such claim, and b) allow the
+Commercial Contributor to control, and cooperate with the Commercial
+Contributor in, the defense and any related settlement negotiations. The
+Indemnified Contributor may participate in any such claim at its own
+expense.</p>
+
+<p>For example, a Contributor might include the Program in a commercial
+product offering, Product X. That Contributor is then a Commercial
+Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance
+claims and warranties are such Commercial Contributor's responsibility
+alone. Under this section, the Commercial Contributor would have to
+defend claims against the other Contributors related to those
+performance claims and warranties, and if a court requires any other
+Contributor to pay any damages as a result, the Commercial Contributor
+must pay those damages.</p>
+
+<p><b>5. NO WARRANTY</b></p>
+
+<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
+PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
+ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
+OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and
+distributing the Program and assumes all risks associated with its
+exercise of rights under this Agreement , including but not limited to
+the risks and costs of program errors, compliance with applicable laws,
+damage to or loss of data, programs or equipment, and unavailability or
+interruption of operations.</p>
+
+<p><b>6. DISCLAIMER OF LIABILITY</b></p>
+
+<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
+NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
+WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
+DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
+HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p>
+
+<p><b>7. GENERAL</b></p>
+
+<p>If any provision of this Agreement is invalid or unenforceable under
+applicable law, it shall not affect the validity or enforceability of
+the remainder of the terms of this Agreement, and without further action
+by the parties hereto, such provision shall be reformed to the minimum
+extent necessary to make such provision valid and enforceable.</p>
+
+<p>If Recipient institutes patent litigation against any entity
+(including a cross-claim or counterclaim in a lawsuit) alleging that the
+Program itself (excluding combinations of the Program with other
+software or hardware) infringes such Recipient's patent(s), then such
+Recipient's rights granted under Section 2(b) shall terminate as of the
+date such litigation is filed.</p>
+
+<p>All Recipient's rights under this Agreement shall terminate if it
+fails to comply with any of the material terms or conditions of this
+Agreement and does not cure such failure in a reasonable period of time
+after becoming aware of such noncompliance. If all Recipient's rights
+under this Agreement terminate, Recipient agrees to cease use and
+distribution of the Program as soon as reasonably practicable. However,
+Recipient's obligations under this Agreement and any licenses granted by
+Recipient relating to the Program shall continue and survive.</p>
+
+<p>Everyone is permitted to copy and distribute copies of this
+Agreement, but in order to avoid inconsistency the Agreement is
+copyrighted and may only be modified in the following manner. The
+Agreement Steward reserves the right to publish new versions (including
+revisions) of this Agreement from time to time. No one other than the
+Agreement Steward has the right to modify this Agreement. The Eclipse
+Foundation is the initial Agreement Steward. The Eclipse Foundation may
+assign the responsibility to serve as the Agreement Steward to a
+suitable separate entity. Each new version of the Agreement will be
+given a distinguishing version number. The Program (including
+Contributions) may always be distributed subject to the version of the
+Agreement under which it was received. In addition, after a new version
+of the Agreement is published, Contributor may elect to distribute the
+Program (including its Contributions) under the new version. Except as
+expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
+rights or licenses to the intellectual property of any Contributor under
+this Agreement, whether expressly, by implication, estoppel or
+otherwise. All rights in the Program not expressly granted under this
+Agreement are reserved.</p>
+
+<p>This Agreement is governed by the laws of the State of New York and
+the intellectual property laws of the United States of America. No party
+to this Agreement will bring a legal action under this Agreement more
+than one year after the cause of action arose. Each party waives its
+rights to a jury trial in any resulting litigation.</p>
+
+</body>
+
+</html>
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/Folder.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Folder.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/Folder.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/Folder.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/Glossary.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/Glossary.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/Glossary.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/Glossary.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/NewGlossary.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/NewGlossary.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/NewGlossary.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/NewGlossary.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary2.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary2.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary2.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary2.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary3.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary3.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary3.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary3.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary4.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary4.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary4.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary4.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary5.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary5.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/OpenGlossary5.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary5.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/Resource16.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/Resource16.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/Resource16_small.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_small.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/Resource16_small.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_small.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/Resource16_warning_small.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_warning_small.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/Resource16_warning_small.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_warning_small.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_128.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_128.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_128.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_128.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_16.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_16.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_16.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_16.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_32.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_32.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_32.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_32.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_48.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_48.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_48.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_48.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_64.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_64.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/TapiJI_64.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_64.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/.cvsignore b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/.cvsignore
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/.cvsignore
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/.cvsignore
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/__.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/__.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/__.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/__.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/_f.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/_f.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/_f.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/_f.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ad.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ad.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ad.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ad.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ae.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ae.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ae.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ae.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/af.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/af.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/af.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/af.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ag.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ag.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ag.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/al.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/al.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/al.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/al.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/am.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/am.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/am.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/am.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ao.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ao.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ao.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ao.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/aq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/aq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/aq.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/aq.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ar.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ar.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ar.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/at.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/at.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/at.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/at.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/au.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/au.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/au.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/au.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/az.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/az.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/az.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/az.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ba.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ba.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ba.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ba.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/be.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/be.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/be.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/be.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bf.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bf.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bi.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bi.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/blank.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/blank.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/blank.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/blank.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bo.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bo.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/br.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/br.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/br.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/br.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bs.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bs.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/by.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/by.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/by.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/by.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/bz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/bz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ca.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ca.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ca.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ca.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cf.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cf.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ch.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ch.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ch.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ch.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ci.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ci.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ci.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ci.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/co.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/co.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/co.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/co.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cs.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cs.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/cz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/cz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/dd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/dd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/de.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/de.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/de.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/de.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/dj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/dj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/dk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/dk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/dm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/dm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/do.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/do.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/do.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/do.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/dz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/dz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ec.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ec.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ec.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ec.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ee.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ee.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ee.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ee.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/eg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/eg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/eh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/eh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/er.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/er.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/er.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/er.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/es.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/es.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/es.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/es.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/et.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/et.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/et.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/et.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/eu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/eu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/fi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/fi.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fi.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/fj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/fj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/fm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/fm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/fr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/fr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ga.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ga.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ga.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ga.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ge.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ge.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ge.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ge.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gq.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gq.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/gy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/gy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/hk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/hk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/hn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/hn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/hr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/hr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ht.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ht.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ht.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ht.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/hu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/hu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/id.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/id.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/id.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/id.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ie.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ie.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ie.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ie.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/il.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/il.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/il.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/il.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/in.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/in.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/in.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/in.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/iq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/iq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/iq.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/iq.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ir.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ir.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ir.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ir.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/is.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/is.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/is.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/is.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/it.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/it.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/it.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/it.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/jm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/jm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/jo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/jo.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jo.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/jp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/jp.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jp.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ke.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ke.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ke.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ke.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ki.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ki.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ki.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ki.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/km.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/km.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/km.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/km.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kp.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kp.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/kz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/kz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/la.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/la.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/la.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/la.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/li.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/li.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/li.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/li.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ls.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ls.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ls.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ls.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/lv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/lv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ly.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ly.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ly.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ly.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ma.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ma.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ma.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ma.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/md.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/md.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/md.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/md.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ml.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ml.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ml.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ml.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mx.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mx.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mx.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mx.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/my.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/my.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/my.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/my.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/mz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/mz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/na.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/na.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/na.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/na.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ne.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ne.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ne.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ne.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ng.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ng.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ng.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ng.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ni.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ni.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ni.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ni.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/nl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/nl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/no.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/no.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/no.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/no.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/np.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/np.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/np.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/np.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/nr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/nr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/nu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/nu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/nz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/nz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/om.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/om.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/om.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/om.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pa.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pa.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pe.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pe.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pe.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pe.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ph.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ph.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ph.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ph.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ps.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ps.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ps.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ps.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/pw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/pw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/py.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/py.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/py.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/py.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/qa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/qa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/qa.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/qa.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ro.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ro.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ro.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ro.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ru.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ru.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ru.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ru.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/rw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/rw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/rw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/rw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sa.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sa.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/se.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/se.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/se.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/se.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/si.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/si.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/si.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/si.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/__.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/__.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/__.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/__.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/_f.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/_f.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/_f.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/_f.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ad.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ad.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ad.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ad.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ae.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ae.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ae.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ae.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/af.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/af.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/af.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/af.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ag.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ag.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ag.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/al.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/al.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/al.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/al.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/am.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/am.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/am.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/am.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ao.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ao.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ao.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ao.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/aq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/aq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/aq.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/aq.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ar.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ar.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ar.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/at.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/at.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/at.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/at.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/au.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/au.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/au.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/au.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/az.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/az.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/az.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/az.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ba.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ba.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ba.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ba.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/be.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/be.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/be.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/be.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bf.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bf.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bi.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bi.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/blank.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/blank.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/blank.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/blank.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bo.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bo.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/br.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/br.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/br.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/br.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bs.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bs.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/by.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/by.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/by.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/by.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/bz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ca.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ca.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ca.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ca.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cf.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cf.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ch.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ch.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ch.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ch.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ci.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ci.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ci.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ci.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/co.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/co.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/co.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/co.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cs.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cs.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/cz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/de.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/de.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/de.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/de.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/do.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/do.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/do.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/do.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/dz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ec.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ec.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ec.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ec.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ee.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ee.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ee.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ee.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/eg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/eg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/eh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/eh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/er.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/er.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/er.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/er.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/es.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/es.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/es.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/es.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/et.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/et.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/et.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/et.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/eu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/eu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fi.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fi.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/fr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ga.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ga.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ga.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ga.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ge.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ge.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ge.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ge.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gq.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gq.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/gy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ht.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ht.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ht.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ht.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/hu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/id.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/id.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/id.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/id.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ie.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ie.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ie.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ie.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/il.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/il.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/il.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/il.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/in.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/in.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/in.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/in.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/iq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/iq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/iq.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/iq.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ir.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ir.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ir.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ir.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/is.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/is.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/is.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/is.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/it.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/it.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/it.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/it.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/jm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/jm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/jo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/jo.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jo.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/jp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/jp.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jp.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ke.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ke.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ke.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ke.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ki.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ki.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ki.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ki.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/km.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/km.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/km.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/km.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kp.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kp.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/kz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/la.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/la.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/la.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/la.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/li.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/li.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/li.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/li.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ls.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ls.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ls.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ls.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/lv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ly.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ly.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ly.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ly.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ma.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ma.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ma.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ma.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/md.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/md.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/md.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/md.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mh.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mh.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ml.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ml.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ml.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ml.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mx.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mx.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mx.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mx.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/my.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/my.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/my.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/my.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/mz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/na.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/na.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/na.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/na.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ne.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ne.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ne.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ne.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ng.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ng.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ng.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ng.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ni.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ni.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ni.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ni.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/no.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/no.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/no.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/no.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/np.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/np.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/np.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/np.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/nz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/om.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/om.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/om.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/om.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pa.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pa.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pe.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pe.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pe.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pe.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ph.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ph.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ph.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ph.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ps.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ps.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ps.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ps.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/pw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/py.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/py.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/py.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/py.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/qa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/qa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/qa.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/qa.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ro.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ro.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ro.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ro.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ru.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ru.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ru.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ru.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/rw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/rw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/rw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/rw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sa.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sa.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sb.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sb.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sd.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sd.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/se.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/se.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/se.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/se.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/si.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/si.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/si.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/si.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sk.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sk.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sl.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sl.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/so.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/so.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/so.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/so.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/st.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/st.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/st.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/st.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/su.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/su.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/su.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/su.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/sz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/td.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/td.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/td.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/td.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/th.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/th.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/th.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/th.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/to.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/to.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/to.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/to.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tp.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tp.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/tz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ua.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ua.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ua.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ua.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ug.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ug.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ug.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ug.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/un.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/un.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/un.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/un.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/us.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/us.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/us.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/us.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/uy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/uy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/uz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/uz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/va.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/va.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/va.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/va.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/vc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/vc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ve.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ve.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ve.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ve.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/vn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/vn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/vu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/vu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ws.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ws.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ws.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ws.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ya.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ya.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ya.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ya.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ye.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ye.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ye0.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye0.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/ye0.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye0.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/yu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/yu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/yu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/yu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/za.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/za.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/za.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/za.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/zm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/zm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/zw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/small/zw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/so.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/so.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/so.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/so.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/st.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/st.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/st.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/st.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/su.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/su.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/su.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/su.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/sz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/sz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/td.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/td.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/td.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/td.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tg.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tg.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/th.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/th.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/th.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/th.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/to.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/to.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/to.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/to.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tp.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tp.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tr.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tr.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tt.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tt.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tv.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tv.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/tz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/tz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ua.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ua.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ua.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ua.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ug.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ug.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ug.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ug.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/un.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/un.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/un.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/un.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/us.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/us.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/us.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/us.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/uy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/uy.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uy.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/uz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/uz.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uz.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/va.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/va.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/va.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/va.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/vc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/vc.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vc.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ve.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ve.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ve.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ve.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/vn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/vn.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vn.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/vu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/vu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ws.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ws.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ws.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ws.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ya.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ya.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ya.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ya.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ye.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ye.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/ye0.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye0.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/ye0.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye0.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/yu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/yu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/yu.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/yu.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/za.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/za.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/za.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/za.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/zm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/zm.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zm.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/countries/zw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/countries/zw.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zw.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/duplicate.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/duplicate.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/duplicate.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/duplicate.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/entry.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/entry.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/entry.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/entry.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/exclude.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/exclude.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/exclude.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/exclude.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/file_obj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/file_obj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/file_obj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/file_obj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/flatLayout.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/flatLayout.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/flatLayout.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/flatLayout.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/fldr_obj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/fldr_obj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/fldr_obj.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/fldr_obj.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/hierarchicalLayout.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/hierarchicalLayout.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/hierarchicalLayout.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/hierarchicalLayout.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/icon_new_memory_view.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/icon_new_memory_view.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/icon_new_memory_view.png
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/icon_new_memory_view.png
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/incomplete.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/incomplete.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/incomplete.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/incomplete.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/int.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/int.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/int.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/int.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/key.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/key.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/key.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/key.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/keyCommented.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/keyCommented.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/keyCommented.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/keyCommented.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/keyNone.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/keyNone.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/keyNone.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/keyNone.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/newpropertiesfile.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/newpropertiesfile.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/newpropertiesfile.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/newpropertiesfile.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/no_int1.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int1.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/no_int1.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/no_int1.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/no_int2.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int2.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/no_int2.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/no_int2.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/original/entry.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/original/entry.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/original/entry.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/original/entry.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/IconResource.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/IconResource.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/IconResource.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/IconResource.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/NewGlossary.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/NewGlossary.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/NewGlossary.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/NewGlossary.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/OpenGlossary.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/OpenGlossary.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/OpenGlossary.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/OpenGlossary.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Resource16.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Resource16.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Resource16.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Resource16.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Resource16_small.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Resource16_small.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Resource16_small.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Resource16_small.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Resource16_warning_small.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Resource16_warning_small.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Resource16_warning_small.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Resource16_warning_small.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Splash.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Splash.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/Splash.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/Splash.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/TJ.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/TJ.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/TJ.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/TJ.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/TapiJI.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/TapiJI.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/TapiJI.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/TapiJI.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/exclude.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/exclude.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/exclude.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/exclude.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/exclude2.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/exclude2.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/photoshop/exclude2.psd
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/photoshop/exclude2.psd
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/propertiesfile.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/propertiesfile.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/propertiesfile.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/propertiesfile.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/read_only.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/read_only.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/read_only.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/read_only.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/resourcebundle.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/resourcebundle.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/resourcebundle.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/resourcebundle.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/sample.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/sample.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/sample.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/sample.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/similar.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/similar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/similar.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/similar.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/toc_open.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/toc_open.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/toc_open.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/toc_open.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/warning.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/warning.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/warning.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/warning.gif
diff --git a/org.eclipselabs.tapiji.tools.core.ui/icons/warningGrey.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/warningGrey.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core.ui/icons/warningGrey.gif
rename to org.eclipse.babel.tapiji.tools.core.ui/icons/warningGrey.gif
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/plugin.xml b/org.eclipse.babel.tapiji.tools.core.ui/plugin.xml
new file mode 100644
index 00000000..ab2227c9
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/plugin.xml
@@ -0,0 +1,243 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+ <extension
+ id="I18NBuilder"
+ point="org.eclipse.core.resources.builders">
+ <builder hasNature="true">
+ <run class="org.eclipse.babel.tapiji.tools.core.ui.builder.I18nBuilder" />
+ </builder>
+ </extension>
+
+ <extension
+ id="org.eclipse.babel.tapiji.tools.core.ui.nature"
+ name="Internationalization Nature"
+ point="org.eclipse.core.resources.natures">
+ <runtime>
+ <run class="org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature" />
+ </runtime>
+ <builder id="org.eclipse.babel.tapiji.tools.core.ui.I18NBuilder" />
+<!-- <requires-nature id="org.eclipse.jdt.core.javanature"/> -->
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.views">
+ <category
+ id="org.eclipse.babel.tapiji"
+ name="Internationalization">
+ </category>
+ <view
+ category="org.eclipse.babel.tapiji"
+ class="org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.MessagesView"
+ icon="icons/resourcebundle.gif"
+ id="org.eclipse.babel.tapiji.tools.core.views.MessagesView"
+ name="Resource-Bundle">
+ </view>
+ </extension>
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.eclipse.jdt.ui.JavaPerspective">
+ <view
+ id="org.eclipse.babel.tapiji.tools.core.views.MessagesView"
+ ratio="0.5"
+ relationship="right"
+ relative="org.eclipse.ui.views.TaskList">
+ </view>
+ </perspectiveExtension>
+ </extension>
+ <extension
+ point="org.eclipse.ui.menus">
+ <menuContribution
+ locationURI="popup:org.eclipse.ui.popup.any?before=additions">
+ <menu
+ id="org.eclipse.babel.tapiji.tools.core.ui.menus.Internationalization"
+ label="Internationalization"
+ tooltip="Java Internationalization assistance">
+ </menu>
+ </menuContribution>
+ <menuContribution
+ locationURI="popup:org.eclipse.babel.tapiji.tools.core.ui.menus.Internationalization?after=additions">
+ <dynamic
+ class="org.eclipse.babel.tapiji.tools.core.ui.menus.InternationalizationMenu"
+ id="org.eclipse.babel.tapiji.tools.core.ui.menus.ExcludeResource">
+ </dynamic>
+ </menuContribution>
+ </extension>
+ <extension
+ point="org.eclipse.ui.ide.markerResolution">
+ <markerResolutionGenerator
+ class="org.eclipse.babel.tapiji.tools.core.ui.builder.ViolationResolutionGenerator"
+ markerType="org.eclipse.babel.tapiji.tools.core.ui.StringLiteralAuditMarker">
+ </markerResolutionGenerator>
+ <markerResolutionGenerator
+ class="org.eclipse.babel.tapiji.tools.core.ui.builder.ViolationResolutionGenerator"
+ markerType="org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleAuditMarker">
+ </markerResolutionGenerator>
+ </extension>
+ <extension
+ point="org.eclipse.jdt.ui.javaElementFilters">
+ <filter
+ class="org.eclipse.babel.tapiji.tools.core.ui.filters.PropertiesFileFilter"
+ description="Filters only resource bundles"
+ enabled="false"
+ id="ResourceBundleFilter"
+ name="ResourceBundleFilter">
+ </filter>
+ </extension>
+ <extension
+ point="org.eclipse.ui.decorators">
+ <decorator
+ adaptable="true"
+ class="org.eclipse.babel.tapiji.tools.core.ui.decorators.ExcludedResource"
+ id="org.eclipse.babel.tapiji.tools.core.decorators.ExcludedResource"
+ label="Resource is excluded from Internationalization"
+ lightweight="false"
+ state="true">
+ <enablement>
+ <and>
+ <objectClass
+ name="org.eclipse.core.resources.IResource">
+ </objectClass>
+ <or>
+ <objectClass
+ name="org.eclipse.core.resources.IFolder">
+ </objectClass>
+ <objectClass
+ name="org.eclipse.core.resources.IFile">
+ </objectClass>
+ </or>
+ </and>
+ </enablement>
+ </decorator>
+ </extension>
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ class="org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiHomePreferencePage"
+ id="org.eclipse.babel.tapiji.tools.core.TapiJIGeneralPrefPage"
+ name="TapiJI">
+ </page>
+ <page
+ category="org.eclipse.babel.tapiji.tools.core.TapiJIGeneralPrefPage"
+ class="org.eclipse.babel.tapiji.tools.core.ui.preferences.FilePreferencePage"
+ id="org.eclipse.babel.tapiji.tools.core.FilePrefPage"
+ name="File Settings">
+ </page>
+ <page
+ category="org.eclipse.babel.tapiji.tools.core.TapiJIGeneralPrefPage"
+ class="org.eclipse.babel.tapiji.tools.core.ui.preferences.BuilderPreferencePage"
+ id="org.eclipse.babel.tapiji.tools.core.BuilderPrefPage"
+ name="Builder Settings">
+ </page>
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.editors.markerUpdaters">
+ <updater
+ class="org.eclipse.babel.tapiji.tools.core.ui.markers.MarkerUpdater"
+ id="org.eclipse.babel.tapiji.tools.core.ui.MarkerUpdater"
+ markerType="org.eclipse.core.resources.problemmarker">
+ </updater>
+ </extension>
+ <extension
+ point="org.eclipse.babel.tapiji.tools.core.stateLoader">
+ <IStateLoader
+ class="org.eclipse.babel.tapiji.tools.core.ui.memento.ResourceBundleManagerStateLoader">
+ </IStateLoader>
+ </extension>
+ <extension
+ id="StringLiteralAuditMarker"
+ name="String Literal Audit Marker"
+ point="org.eclipse.core.resources.markers">
+ <super
+ type="org.eclipse.core.resources.problemmarker">
+ </super>
+ <super
+ type="org.eclipse.core.resources.textmarker">
+ </super>
+ <persistent
+ value="true">
+ </persistent>
+ <attribute
+ name="stringLiteral">
+ </attribute>
+ <attribute
+ name="violation">
+ </attribute>
+ <attribute
+ name="context">
+ </attribute>
+ <attribute
+ name="cause">
+ </attribute>
+ <attribute
+ name="key">
+ </attribute>
+ <attribute
+ name="location">
+ </attribute>
+ <attribute
+ name="bundleName">
+ </attribute>
+ <attribute
+ name="bundleStart">
+ </attribute>
+ <attribute
+ name="bundleEnd">
+ </attribute>
+ </extension>
+ <extension
+ id="ResourceBundleAuditMarker"
+ name="Resource-Bundle Audit Marker"
+ point="org.eclipse.core.resources.markers">
+ <super
+ type="org.eclipse.core.resources.problemmarker">
+ </super>
+ <super
+ type="org.eclipse.core.resources.textmarker">
+ </super>
+ <persistent
+ value="true">
+ </persistent>
+ <attribute
+ name="stringLiteral">
+ </attribute>
+ <attribute
+ name="violation">
+ </attribute>
+ <attribute
+ name="context">
+ </attribute>
+ <attribute
+ name="cause">
+ </attribute>
+ <attribute
+ name="key">
+ </attribute>
+ <attribute
+ name="location">
+ </attribute>
+ <attribute
+ name="language">
+ </attribute>
+ <attribute
+ name="bundleLine">
+ </attribute>
+ <attribute
+ name="problemPartner">
+ </attribute>
+ </extension>
+ <extension
+ point="org.eclipse.core.runtime.preferences">
+ <initializer
+ class="org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiJIPreferenceInitializer">
+ </initializer>
+ </extension>
+ <extension
+ point="org.eclipse.babel.core.babelConfiguration">
+ <IConfiguration
+ class="org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiJIPreferences">
+ </IConfiguration>
+ </extension>
+</plugin>
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
new file mode 100644
index 00000000..746db867
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
@@ -0,0 +1,88 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core.ui"; //$NON-NLS-1$
+
+ // 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;
+ }
+
+ return imageDescriptorFromPlugin(PLUGIN_ID, 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;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ // save state of ResourceBundleManager
+ ResourceBundleManager.saveManagerState();
+
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+}
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
new file mode 100644
index 00000000..234af8e9
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
@@ -0,0 +1,817 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - moved object management to RBManager, Babel integration
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.factory.MessageFactory;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.IResourceDeltaListener;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.core.util.FileUtils;
+import org.eclipse.babel.core.util.NameUtils;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceDescriptor;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceExclusionListener;
+import org.eclipse.babel.tapiji.tools.core.model.ResourceDescriptor;
+import org.eclipse.babel.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipse.babel.tapiji.tools.core.model.manager.IStateLoader;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.analyzer.ResourceBundleDetectionVisitor;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.JavaCore;
+
+public class ResourceBundleManager {
+
+ public static String defaultLocaleTag = "[default]"; // TODO externalize
+
+ /*** CONFIG SECTION ***/
+ private static boolean checkResourceExclusionRoot = false;
+
+ /*** MEMBER SECTION ***/
+ private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>();
+
+ public static final String RESOURCE_BUNDLE_EXTENSION = ".properties";
+
+ // project-specific
+ private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>();
+
+ private Map<String, String> bundleNames = new HashMap<String, String>();
+
+ private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>();
+
+ private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>();
+
+ // global
+ private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>();
+
+ private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>();
+
+ // private static IResourceChangeListener changelistener; //
+ // RBChangeListener -> see stateLoader!
+
+ public static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
+
+ public static final String BUILDER_ID = Activator.PLUGIN_ID
+ + ".I18NBuilder";
+
+ /* Host project */
+ private IProject project = null;
+
+ /** State-Serialization Information **/
+ private static boolean state_loaded = false;
+
+ 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);
+ }
+ });
+ }
+
+ 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();
+ }
+
+ // 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);
+
+ Set<Locale> locales = new HashSet<Locale>();
+ IMessagesBundleGroup group = instance
+ .getMessagesBundleGroup(bundleName);
+ if (group == null) {
+ return locales;
+ }
+
+ for (IMessagesBundle bundle : group.getMessagesBundles()) {
+ locales.add(bundle.getLocale());
+ }
+ return locales;
+ }
+
+ public static String getResourceBundleName(IResource res) {
+ String name = res.getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + res.getFileExtension() + ")$"; //$NON-NLS-1$
+ return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
+ }
+
+ protected boolean isResourceBundleLoaded(String bundleName) {
+ return RBManager.getInstance(project).containsMessagesBundleGroup(
+ bundleName);
+ }
+
+ protected void unloadResource(String bundleName, IResource resource) {
+ // TODO implement more efficient
+ unloadResourceBundle(bundleName);
+ // loadResourceBundle(bundleName);
+ }
+
+ public static String getResourceBundleId(IResource resource) {
+ String packageFragment = "";
+
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment) {
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
+ }
+
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
+ }
+
+ public void addBundleResource(IResource resource) {
+ if (resource.isDerived()) {
+ return;
+ }
+
+ String bundleName = getResourceBundleId(resource);
+ Set<IResource> res;
+
+ if (!resources.containsKey(bundleName)) {
+ res = new HashSet<IResource>();
+ } else {
+ res = resources.get(bundleName);
+ }
+
+ res.add(resource);
+ resources.put(bundleName, res);
+ allBundles.put(bundleName, new HashSet<IResource>(res));
+ bundleNames.put(bundleName, getResourceBundleName(resource));
+
+ // Fire resource changed event
+ ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.ADDED, bundleName,
+ resource.getProject());
+ this.fireResourceBundleChangedEvent(bundleName, event);
+ }
+
+ protected void removeAllBundleResources(String bundleName) {
+ unloadResourceBundle(bundleName);
+ resources.remove(bundleName);
+ // allBundles.remove(bundleName);
+ listeners.remove(bundleName);
+ }
+
+ public void unloadResourceBundle(String name) {
+ RBManager instance = RBManager.getInstance(project);
+ instance.deleteMessagesBundleGroup(name);
+ }
+
+ public IMessagesBundleGroup getResourceBundle(String name) {
+ RBManager instance = RBManager.getInstance(project);
+ return instance.getMessagesBundleGroup(name);
+ }
+
+ public Collection<IResource> getResourceBundles(String bundleName) {
+ return resources.get(bundleName);
+ }
+
+ public List<String> getResourceBundleNames() {
+ List<String> returnList = new ArrayList<String>();
+
+ Iterator<String> it = resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
+ return returnList;
+ }
+
+ public IResource getResourceFile(String file) {
+ String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
+ String bundleName = file.replaceFirst(regex, "$1");
+ IResource resource = null;
+
+ for (IResource res : resources.get(bundleName)) {
+ if (res.getName().equalsIgnoreCase(file)) {
+ resource = res;
+ break;
+ }
+ }
+
+ return resource;
+ }
+
+ public void fireResourceBundleChangedEvent(String bundleName,
+ ResourceBundleChangedEvent event) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+
+ if (l == null) {
+ return;
+ }
+
+ for (IResourceBundleChangedListener listener : l) {
+ listener.resourceBundleChanged(event);
+ }
+ }
+
+ public void registerResourceBundleChangeListener(String bundleName,
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null) {
+ l = new ArrayList<IResourceBundleChangedListener>();
+ }
+ l.add(listener);
+ listeners.put(bundleName, l);
+ }
+
+ public void unregisterResourceBundleChangeListener(String bundleName,
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null) {
+ return;
+ }
+ l.remove(listener);
+ listeners.put(bundleName, l);
+ }
+
+ protected void detectResourceBundles() {
+ try {
+ project.accept(new ResourceBundleDetectionVisitor(getProject()));
+
+ IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
+ if (fragments != null) {
+ for (IProject p : fragments) {
+ p.accept(new ResourceBundleDetectionVisitor(getProject()));
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+
+ public IProject getProject() {
+ return project;
+ }
+
+ public List<String> getResourceBundleIdentifiers() {
+ List<String> returnList = new ArrayList<String>();
+
+ // TODO check other resource bundles that are available on the curren
+ // class path
+ Iterator<String> it = this.resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
+
+ return returnList;
+ }
+
+ public static List<String> getAllResourceBundleNames() {
+ List<String> returnList = new ArrayList<String>();
+
+ for (IProject p : getAllSupportedProjects()) {
+ if (!FragmentProjectUtils.isFragment(p)) {
+ Iterator<String> it = getManager(p).resources.keySet()
+ .iterator();
+ while (it.hasNext()) {
+ returnList.add(p.getName() + "/" + it.next());
+ }
+ }
+ }
+ return returnList;
+ }
+
+ public static Set<IProject> getAllSupportedProjects() {
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ Set<IProject> projs = new HashSet<IProject>();
+
+ for (IProject p : projects) {
+ try {
+ if (p.isOpen() && p.hasNature(NATURE_ID)) {
+ projs.add(p);
+ }
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ return projs;
+ }
+
+ public String getKeyHoverString(String rbName, String key) {
+ try {
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(rbName);
+ if (!bundleGroup.containsKey(key)) {
+ return null;
+ }
+
+ String hoverText = "<html><head></head><body>";
+
+ for (IMessage message : bundleGroup.getMessages(key)) {
+ String displayName = message.getLocale() == null ? "Default"
+ : message.getLocale().getDisplayName();
+ String value = message.getValue();
+ hoverText += "<b><i>" + displayName + "</i></b><br/>"
+ + value.replace("\n", "<br/>") + "<br/><br/>";
+ }
+ return hoverText + "</body></html>";
+ } catch (Exception e) {
+ // silent catch
+ return "";
+ }
+ }
+
+ public boolean isKeyBroken(String rbName, String key) {
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ project).getMessagesBundleGroup(rbName);
+ if (messagesBundleGroup == null) {
+ return true;
+ } else {
+ return !messagesBundleGroup.containsKey(key);
+ }
+
+ // if (!resourceBundles.containsKey(rbName))
+ // return true;
+ // return !this.isResourceExisting(rbName, key);
+ }
+
+ protected void excludeSingleResource(IResource res) {
+ IResourceDescriptor rd = new ResourceDescriptor(res);
+ 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 {
+ resource = resource.getParent();
+ }
+ }
+ }
+
+ try {
+ res.accept(new IResourceVisitor() {
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ changedResources.add(resource);
+ return true;
+ }
+ });
+
+ monitor.beginTask("Add resources to Internationalization context",
+ changedResources.size());
+ try {
+ for (Object r : changedResources) {
+ excludedResources.remove(new ResourceDescriptor(
+ (IResource) r));
+ monitor.worked(1);
+ }
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+
+ try {
+ res.touch(null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+
+ // 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));
+ }
+
+ protected void fireResourceExclusionEvent(ResourceExclusionEvent event) {
+ for (IResourceExclusionListener listener : exclusionListeners) {
+ listener.exclusionChanged(event);
+ }
+ }
+
+ public static boolean isResourceExcluded(IResource res) {
+ IResource resource = res;
+
+ if (!state_loaded) {
+ stateLoader.loadState();
+ }
+
+ 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();
+ }
+ 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);
+
+ 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);
+ }
+
+ public void registerResourceExclusionListener(
+ IResourceExclusionListener listener) {
+ exclusionListeners.add(listener);
+ }
+
+ public void unregisterResourceExclusionListener(
+ IResourceExclusionListener listener) {
+ exclusionListeners.remove(listener);
+ }
+
+ public boolean isResourceExclusionListenerRegistered(
+ IResourceExclusionListener listener) {
+ return exclusionListeners.contains(listener);
+ }
+
+ public static void unregisterResourceExclusionListenerFromAllManagers(
+ IResourceExclusionListener excludedResource) {
+ for (ResourceBundleManager mgr : rbmanager.values()) {
+ mgr.unregisterResourceExclusionListener(excludedResource);
+ }
+ }
+
+ public void addResourceBundleEntry(String resourceBundleId, String key,
+ Locale locale, String message) throws ResourceBundleException {
+
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+ IMessage entry = bundleGroup.getMessage(key, locale);
+
+ if (entry == null) {
+ DirtyHack.setFireEnabled(false);
+
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(locale);
+ IMessage m = MessageFactory.createMessage(key, locale);
+ m.setText(message);
+ messagesBundle.addMessage(m);
+
+ FileUtils.writeToFile(messagesBundle);
+ instance.fireResourceChanged(messagesBundle);
+
+ DirtyHack.setFireEnabled(true);
+
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
+ }
+
+ public void saveResourceBundle(String resourceBundleId,
+ IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
+
+ // RBManager.getInstance().
+ }
+
+ public void removeResourceBundleEntry(String resourceBundleId,
+ List<String> keys) throws ResourceBundleException {
+
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup messagesBundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+
+ DirtyHack.setFireEnabled(false);
+
+ for (String key : keys) {
+ messagesBundleGroup.removeMessages(key);
+ }
+
+ instance.writeToFile(messagesBundleGroup);
+
+ DirtyHack.setFireEnabled(true);
+
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
+
+ public boolean isResourceExisting(String bundleId, String key) {
+ boolean keyExists = false;
+ IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
+
+ if (bGroup != null) {
+ keyExists = bGroup.isKey(key);
+ }
+
+ return keyExists;
+ }
+
+ public static void rebuildProject(IResource resource) {
+ try {
+ resource.touch(null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public Set<Locale> getProjectProvidedLocales() {
+ Set<Locale> locales = new HashSet<Locale>();
+
+ for (String bundleId : getResourceBundleNames()) {
+ Set<Locale> rb_l = getProvidedLocales(bundleId);
+ if (!rb_l.isEmpty()) {
+ Object[] bundlelocales = rb_l.toArray();
+ for (Object l : bundlelocales) {
+ /* TODO check if useful to add the default */
+ if (!locales.contains(l)) {
+ locales.add((Locale) l);
+ }
+ }
+ }
+ }
+ return locales;
+ }
+
+ private static IStateLoader getStateLoader() {
+
+ 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;
+ }
+
+ 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
new file mode 100644
index 00000000..bf244de6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.analyzer;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+public class RBAuditor extends I18nResourceAuditor {
+
+ @Override
+ public void audit(IResource resource) {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ ResourceBundleManager.getManager(resource.getProject())
+ .addBundleResource(resource);
+ }
+ }
+
+ @Override
+ public String[] getFileEndings() {
+ return new String[] { "properties" };
+ }
+
+ @Override
+ public List<ILocation> getConstantStringLiterals() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenResourceReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenBundleReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public String getContextId() {
+ return "resource_bundle";
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..4e36b65d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.analyzer;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+
+public class ResourceBundleDetectionVisitor implements IResourceVisitor,
+ IResourceDeltaVisitor {
+
+ private IProject project = null;
+
+ public ResourceBundleDetectionVisitor(IProject project) {
+ this.project = project;
+ }
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ try {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ Logger.logInfo("Loading Resource-Bundle file '"
+ + resource.getName() + "'");
+ if (!ResourceBundleManager.isResourceExcluded(resource)) {
+ ResourceBundleManager.getManager(project)
+ .addBundleResource(resource);
+ }
+ return false;
+ } else {
+ return true;
+ }
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ IResource resource = delta.getResource();
+
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ return false;
+ }
+
+ return true;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..49a5f92b
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java
@@ -0,0 +1,56 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.analyzer;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.I18nBuilder;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+
+public class ResourceFinder implements IResourceVisitor, IResourceDeltaVisitor {
+
+ List<IResource> javaResources = null;
+ Set<String> supportedExtensions = null;
+
+ public ResourceFinder(Set<String> ext) {
+ javaResources = new ArrayList<IResource>();
+ supportedExtensions = ext;
+ }
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) {
+ Logger.logInfo("Audit necessary for resource '"
+ + resource.getFullPath().toOSString() + "'");
+ javaResources.add(resource);
+ return false;
+ } else
+ return true;
+ }
+
+ public List<IResource> getResources() {
+ return javaResources;
+ }
+
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ visit(delta.getResource());
+ return true;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..75da3d54
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java
@@ -0,0 +1,134 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.builder;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiJIPreferences;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.swt.widgets.Display;
+
+public class BuilderPropertyChangeListener implements IPropertyChangeListener {
+
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getNewValue().equals(true) && isTapiJIPropertyp(event))
+ rebuild();
+
+ if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN))
+ rebuild();
+
+ if (event.getNewValue().equals(false)) {
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) {
+ deleteMarkersByCause(EditorUtils.MARKER_ID, -1);
+ }
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1);
+ }
+ if (event.getProperty().equals(
+ TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_UNSPEZIFIED_KEY);
+ }
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_SAME_VALUE);
+ }
+ if (event.getProperty().equals(
+ TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_MISSING_LANGUAGE);
+ }
+ }
+
+ }
+
+ private boolean isTapiJIPropertyp(PropertyChangeEvent event) {
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)
+ || event.getProperty().equals(TapiJIPreferences.AUDIT_RB)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_SAME_VALUE)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_MISSING_LANGUAGE))
+ return true;
+ else
+ return false;
+ }
+
+ /*
+ * cause == -1 ignores the attribute 'case'
+ */
+ private void deleteMarkersByCause(final String markertype, final int cause) {
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ IMarker[] marker;
+ try {
+ marker = workspace.getRoot().findMarkers(markertype, true,
+ IResource.DEPTH_INFINITE);
+
+ for (IMarker m : marker) {
+ if (m.exists()) {
+ if (m.getAttribute("cause", -1) == cause)
+ m.delete();
+ if (cause == -1)
+ m.getResource().deleteMarkers(markertype, true,
+ IResource.DEPTH_INFINITE);
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+ });
+ }
+
+ private void rebuild() {
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+
+ new Job("Audit source files") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ for (IResource res : workspace.getRoot().members()) {
+ final IProject p = (IProject) res;
+ try {
+ p.build(I18nBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, monitor);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ return Status.OK_STATUS;
+ }
+
+ }.schedule();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..8d9a8ab4
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java
@@ -0,0 +1,80 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.builder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.analyzer.RBAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiJIPreferences;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.util.IPropertyChangeListener;
+
+public class ExtensionManager {
+
+ // list of registered extension plug-ins
+ private static List<I18nAuditor> extensions = 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>();
+
+ public static List<I18nAuditor> getRegisteredI18nAuditors() {
+ if (extensions == null) {
+ extensions = new ArrayList<I18nAuditor>();
+
+ // init default auditors
+ extensions.add(new RBAuditor());
+
+ // 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);
+ }
+ }
+
+ // init builder property change listener
+ if (propertyChangeListener == null) {
+ propertyChangeListener = new BuilderPropertyChangeListener();
+ TapiJIPreferences.addPropertyChangeListener(propertyChangeListener);
+ }
+
+ 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
new file mode 100644
index 00000000..a1adbea7
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java
@@ -0,0 +1,469 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.builder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.babel.core.configuration.ConfigurationManager;
+import org.eclipse.babel.core.configuration.IConfiguration;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.analyzer.ResourceFinder;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nRBAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils;
+import org.eclipse.core.resources.ICommand;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IWorkspaceRunnable;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+
+public class I18nBuilder extends IncrementalProjectBuilder {
+
+ public static final String BUILDER_ID = 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 boolean isResourceAuditable(IResource resource,
+ Set<String> supportedExtensions) {
+ for (String ext : supportedExtensions) {
+ if (resource.getType() == IResource.FILE && !resource.isDerived()
+ && resource.getFileExtension() != null
+ && (resource.getFileExtension().equalsIgnoreCase(ext))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected IProject[] build(final int kind, Map args,
+ IProgressMonitor monitor) throws CoreException {
+
+ ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
+ @Override
+ public void run(IProgressMonitor monitor) throws CoreException {
+ if (kind == FULL_BUILD) {
+ fullBuild(monitor);
+ } else {
+ // only perform audit if the resource delta is not empty
+ IResourceDelta resDelta = getDelta(getProject());
+
+ if (resDelta == null) {
+ return;
+ }
+
+ if (resDelta.getAffectedChildren() == null) {
+ return;
+ }
+
+ incrementalBuild(monitor, resDelta);
+ }
+ }
+ }, monitor);
+
+ return null;
+ }
+
+ private void incrementalBuild(IProgressMonitor monitor,
+ IResourceDelta resDelta) throws CoreException {
+ try {
+ // inspect resource delta
+ ResourceFinder csrav = new ResourceFinder(
+ ExtensionManager.getSupportedFileEndings());
+ resDelta.accept(csrav);
+ auditResources(csrav.getResources(), monitor, getProject());
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public void buildResource(IResource resource, IProgressMonitor monitor) {
+ if (isResourceAuditable(resource,
+ ExtensionManager.getSupportedFileEndings())) {
+ List<IResource> resources = new ArrayList<IResource>();
+ resources.add(resource);
+ // TODO: create instance of progressmonitor and hand it over to
+ // auditResources
+ try {
+ auditResources(resources, monitor, resource.getProject());
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+ }
+
+ public void buildProject(IProgressMonitor monitor, IProject proj) {
+ try {
+ ResourceFinder csrav = new ResourceFinder(
+ ExtensionManager.getSupportedFileEndings());
+ proj.accept(csrav);
+ auditResources(csrav.getResources(), monitor, proj);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ private void fullBuild(IProgressMonitor monitor) {
+ buildProject(monitor, getProject());
+ }
+
+ private void auditResources(List<IResource> resources,
+ IProgressMonitor monitor, IProject project) {
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+
+ int work = resources.size();
+ int actWork = 0;
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
+
+ monitor.beginTask(
+ "Audit resource file for Internationalization problems", work);
+
+ for (IResource resource : resources) {
+ monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
+
+ if (!EditorUtils.deleteAuditMarkersForResource(resource)) {
+ continue;
+ }
+
+ if (ResourceBundleManager.isResourceExcluded(resource)) {
+ continue;
+ }
+
+ if (!resource.exists()) {
+ continue;
+ }
+
+ for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (ra instanceof I18nResourceAuditor
+ && !(configuration.getAuditResource())) {
+ continue;
+ }
+ if (ra instanceof I18nRBAuditor
+ && !(configuration.getAuditRb())) {
+ continue;
+ }
+
+ try {
+ if (monitor.isCanceled()) {
+ monitor.done();
+ break;
+ }
+
+ if (ra.isResourceOfType(resource)) {
+ ra.audit(resource);
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Error during auditing '" + resource.getFullPath()
+ + "'", e);
+ }
+ }
+
+ if (monitor != null) {
+ monitor.worked(1);
+ }
+ }
+
+ for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (a instanceof I18nResourceAuditor) {
+ handleI18NAuditorMarkers((I18nResourceAuditor) a);
+ }
+ if (a instanceof I18nRBAuditor) {
+ handleI18NAuditorMarkers((I18nRBAuditor) a);
+ ((I18nRBAuditor) a).resetProblems();
+ }
+ }
+
+ monitor.done();
+ }
+
+ private void handleI18NAuditorMarkers(I18nResourceAuditor ra) {
+ try {
+ for (ILocation problem : ra.getConstantStringLiterals()) {
+ EditorUtils
+ .reportToMarker(
+ 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());
+ }
+ }
+
+ // 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);
+
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
+
+ if (isInterrupted()) {
+ throw new InterruptedException();
+ }
+ }
+
+ @Override
+ protected void clean(IProgressMonitor monitor) throws CoreException {
+ // TODO Auto-generated method stub
+ super.clean(monitor);
+ }
+
+ public static void addBuilderToProject(IProject project) {
+ Logger.logInfo("Internationalization-Builder registered for '"
+ + project.getName() + "'");
+
+ // Only for open projects
+ if (!project.isOpen()) {
+ return;
+ }
+
+ IProjectDescription description = null;
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // Check if the builder is already associated to the specified project
+ ICommand[] commands = description.getBuildSpec();
+ for (ICommand command : commands) {
+ if (command.getBuilderName().equals(BUILDER_ID)) {
+ return;
+ }
+ }
+
+ // Associate the builder with the project
+ ICommand builderCmd = description.newCommand();
+ builderCmd.setBuilderName(BUILDER_ID);
+ List<ICommand> newCommands = new ArrayList<ICommand>();
+ newCommands.addAll(Arrays.asList(commands));
+ newCommands.add(builderCmd);
+ description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
+ .size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public static void removeBuilderFromProject(IProject project) {
+ // Only for open projects
+ if (!project.isOpen()) {
+ return;
+ }
+
+ try {
+ project.deleteMarkers(EditorUtils.MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ project.deleteMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ } catch (CoreException e1) {
+ Logger.logError(e1);
+ }
+
+ IProjectDescription description = null;
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // remove builder from project
+ int idx = -1;
+ ICommand[] commands = description.getBuildSpec();
+ for (int i = 0; i < commands.length; i++) {
+ if (commands[i].getBuilderName().equals(BUILDER_ID)) {
+ idx = i;
+ break;
+ }
+ }
+ if (idx == -1) {
+ return;
+ }
+
+ List<ICommand> newCommands = new ArrayList<ICommand>();
+ newCommands.addAll(Arrays.asList(commands));
+ newCommands.remove(idx);
+ description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
+ .size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..fa4ea483
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java
@@ -0,0 +1,142 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.builder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.resources.IProjectNature;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class InternationalizationNature implements IProjectNature {
+
+ private static final String NATURE_ID = 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;
+ }
+
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index != -1)
+ return;
+
+ // Add the nature
+ newIds.add(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public static boolean supportsNature(IProject project) {
+ return project.isOpen();
+ }
+
+ public static boolean hasNature(IProject project) {
+ try {
+ return project.isOpen() && project.hasNature(NATURE_ID);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
+ }
+
+ public static void removeNature(IProject project) {
+ if (!project.isOpen())
+ return;
+
+ IProjectDescription description = null;
+
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index == -1)
+ return;
+
+ // remove the nature
+ newIds.remove(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..472593e4
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java
@@ -0,0 +1,51 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.builder;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.ui.IMarkerResolution;
+import org.eclipse.ui.IMarkerResolutionGenerator2;
+
+public class ViolationResolutionGenerator implements
+ IMarkerResolutionGenerator2 {
+
+ @Override
+ public boolean hasResolutions(IMarker marker) {
+ return true;
+ }
+
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+
+ EditorUtils.updateMarker(marker);
+
+ String contextId = marker.getAttribute("context", "");
+
+ // find resolution generator for the given context
+ try {
+ I18nAuditor auditor = I18nBuilder
+ .getI18nAuditorByContext(contextId);
+ List<IMarkerResolution> resolutions = auditor
+ .getMarkerResolutions(marker);
+ return resolutions
+ .toArray(new IMarkerResolution[resolutions.size()]);
+ } catch (NoSuchResourceAuditorException e) {
+ }
+
+ return new IMarkerResolution[0];
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..57bfdfb7
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
@@ -0,0 +1,115 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.decorators;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceExclusionListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.viewers.DecorationOverlayIcon;
+import org.eclipse.jface.viewers.IDecoration;
+import org.eclipse.jface.viewers.ILabelDecorator;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.LabelProviderChangedEvent;
+import org.eclipse.swt.graphics.Image;
+
+public class ExcludedResource implements ILabelDecorator,
+ IResourceExclusionListener {
+
+ private static final String ENTRY_SUFFIX = "[no i18n]";
+ private static final Image OVERLAY_IMAGE_ON = ImageUtils
+ .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
+ private static final Image OVERLAY_IMAGE_OFF = ImageUtils
+ .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
+ private final List<ILabelProviderListener> label_provider_listener = new ArrayList<ILabelProviderListener>();
+
+ public boolean decorate(Object element) {
+ boolean needsDecoration = false;
+ if (element instanceof IFolder || element instanceof IFile) {
+ IResource resource = (IResource) element;
+ if (!InternationalizationNature.hasNature(resource.getProject()))
+ return false;
+ try {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(resource.getProject());
+ if (!manager.isResourceExclusionListenerRegistered(this))
+ manager.registerResourceExclusionListener(this);
+ if (ResourceBundleManager.isResourceExcluded(resource)) {
+ needsDecoration = true;
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+ return needsDecoration;
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ label_provider_listener.add(listener);
+ }
+
+ @Override
+ public void dispose() {
+ ResourceBundleManager
+ .unregisterResourceExclusionListenerFromAllManagers(this);
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ label_provider_listener.remove(listener);
+ }
+
+ @Override
+ public void exclusionChanged(ResourceExclusionEvent event) {
+ LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(
+ this, event.getChangedResources().toArray());
+ for (ILabelProviderListener l : label_provider_listener)
+ l.labelProviderChanged(labelEvent);
+ }
+
+ @Override
+ public Image decorateImage(Image image, Object element) {
+ if (decorate(element)) {
+ DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(
+ image,
+ Activator
+ .getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
+ IDecoration.TOP_RIGHT);
+ return overlayIcon.createImage();
+ } else {
+ return image;
+ }
+ }
+
+ @Override
+ public String decorateText(String text, Object element) {
+ if (decorate(element)) {
+ return text + " " + ENTRY_SUFFIX;
+ } else
+ return text;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
new file mode 100644
index 00000000..a61b3728
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
@@ -0,0 +1,168 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.dialogs;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.LocaleUtils;
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class AddLanguageDialoge extends Dialog {
+ private Locale locale;
+ private Shell shell;
+
+ private Text titelText;
+ private Text descriptionText;
+ private Combo cmbLanguage;
+ private Text language;
+ private Text country;
+ private Text variant;
+
+ public AddLanguageDialoge(Shell parentShell) {
+ super(parentShell);
+ shell = parentShell;
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND);
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ GridLayout layout = new GridLayout(1, true);
+ dialogArea.setLayout(layout);
+
+ initDescription(titelArea);
+ initCombo(dialogArea);
+ initTextArea(dialogArea);
+
+ titelArea.pack();
+ dialogArea.pack();
+ parent.pack();
+
+ return dialogArea;
+ }
+
+ private void initDescription(Composite titelArea) {
+ titelArea.setEnabled(false);
+ titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true,
+ 1, 1));
+ titelArea.setLayout(new GridLayout(1, true));
+ titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
+
+ titelText = new Text(titelArea, SWT.LEFT);
+ titelText.setFont(new Font(shell.getDisplay(), shell.getFont()
+ .getFontData()[0].getName(), 11, SWT.BOLD));
+ titelText.setText("Please, specify the desired language");
+
+ descriptionText = new Text(titelArea, SWT.WRAP);
+ descriptionText.setLayoutData(new GridData(450, 60)); // TODO improve
+ descriptionText
+ .setText("Note: "
+ + "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. "
+ + "If the locale is just provided of a ResourceBundle, no new file will be created.");
+ }
+
+ private void initCombo(Composite dialogArea) {
+ cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN);
+ cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
+ true, 1, 1));
+
+ final Locale[] locales = Locale.getAvailableLocales();
+ final Set<Locale> localeSet = new HashSet<Locale>();
+ List<String> localeNames = new LinkedList<String>();
+
+ for (Locale l : locales) {
+ localeNames.add(l.getDisplayName());
+ localeSet.add(l);
+ }
+
+ Collections.sort(localeNames);
+
+ String[] s = new String[localeNames.size()];
+ cmbLanguage.setItems(localeNames.toArray(s));
+ cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0);
+
+ cmbLanguage.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int selectIndex = ((Combo) e.getSource()).getSelectionIndex();
+ if (!cmbLanguage.getItem(selectIndex).equals(
+ ResourceBundleManager.defaultLocaleTag)) {
+ Locale l = LocaleUtils.getLocaleByDisplayName(localeSet,
+ cmbLanguage.getItem(selectIndex));
+
+ language.setText(l.getLanguage());
+ country.setText(l.getCountry());
+ variant.setText(l.getVariant());
+ } else {
+ language.setText("");
+ country.setText("");
+ variant.setText("");
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+ }
+
+ private void initTextArea(Composite dialogArea) {
+ final Group group = new Group(dialogArea, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1,
+ 1));
+ group.setLayout(new GridLayout(3, true));
+ group.setText("Locale");
+
+ Label languageLabel = new Label(group, SWT.SINGLE);
+ languageLabel.setText("Language");
+ Label countryLabel = new Label(group, SWT.SINGLE);
+ countryLabel.setText("Country");
+ Label variantLabel = new Label(group, SWT.SINGLE);
+ variantLabel.setText("Variant");
+
+ language = new Text(group, SWT.SINGLE);
+ country = new Text(group, SWT.SINGLE);
+ variant = new Text(group, SWT.SINGLE);
+ }
+
+ @Override
+ protected void okPressed() {
+ locale = new Locale(language.getText(), country.getText(),
+ variant.getText());
+
+ super.okPressed();
+ }
+
+ public Locale getSelectedLanguage() {
+ return locale;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
new file mode 100644
index 00000000..6d348525
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.dialogs;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class CreatePatternDialoge extends Dialog {
+ private String pattern;
+ private Text patternText;
+
+ public CreatePatternDialoge(Shell shell) {
+ this(shell, "");
+ }
+
+ public CreatePatternDialoge(Shell shell, String pattern) {
+ super(shell);
+ this.pattern = pattern;
+ // setShellStyle(SWT.RESIZE);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(1, true));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
+
+ Label descriptionLabel = new Label(composite, SWT.NONE);
+ descriptionLabel.setText("Enter a regular expression:");
+
+ patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
+ GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
+ gData.widthHint = 400;
+ gData.heightHint = 60;
+ patternText.setLayoutData(gData);
+ patternText.setText(pattern);
+
+ return composite;
+ }
+
+ @Override
+ protected void okPressed() {
+ pattern = patternText.getText();
+
+ super.okPressed();
+ }
+
+ public String getPattern() {
+ return pattern;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
new file mode 100644
index 00000000..fed59c04
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
@@ -0,0 +1,481 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Clemente Lodi-Fe - bug fix
+ * Alexej Strelzow - added DialogConfiguration
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.LocaleUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class CreateResourceBundleEntryDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+
+ private static final String DEFAULT_KEY = "defaultkey";
+
+ private String projectName;
+
+ private Text txtKey;
+ private Combo cmbRB;
+ private Text txtDefaultText;
+ private Combo cmbLanguage;
+
+ private Button okButton;
+ private Button cancelButton;
+
+ /*** Dialog Model ***/
+ String selectedRB = "";
+ String selectedLocale = "";
+ String selectedKey = "";
+ String selectedDefaultText = "";
+
+ /*** MODIFY LISTENER ***/
+ ModifyListener rbModifyListener;
+
+ public class DialogConfiguration {
+
+ String projectName;
+
+ String preselectedKey;
+ String preselectedMessage;
+ String preselectedBundle;
+ String preselectedLocale;
+
+ public String getProjectName() {
+ return projectName;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public String getPreselectedKey() {
+ return preselectedKey;
+ }
+
+ public void setPreselectedKey(String preselectedKey) {
+ this.preselectedKey = preselectedKey;
+ }
+
+ public String getPreselectedMessage() {
+ return preselectedMessage;
+ }
+
+ public void setPreselectedMessage(String preselectedMessage) {
+ this.preselectedMessage = preselectedMessage;
+ }
+
+ public String getPreselectedBundle() {
+ return preselectedBundle;
+ }
+
+ public void setPreselectedBundle(String preselectedBundle) {
+ this.preselectedBundle = preselectedBundle;
+ }
+
+ public String getPreselectedLocale() {
+ return preselectedLocale;
+ }
+
+ public void setPreselectedLocale(String preselectedLocale) {
+ this.preselectedLocale = preselectedLocale;
+ }
+
+ }
+
+ public CreateResourceBundleEntryDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ public void setDialogConfiguration(DialogConfiguration config) {
+ String preselectedKey = config.getPreselectedKey();
+ this.selectedKey = preselectedKey != null ? preselectedKey.trim()
+ : preselectedKey;
+ if ("".equals(this.selectedKey)) {
+ this.selectedKey = DEFAULT_KEY;
+ }
+
+ this.selectedDefaultText = config.getPreselectedMessage();
+ this.selectedRB = config.getPreselectedBundle();
+ this.selectedLocale = config.getPreselectedLocale();
+ this.projectName = config.getProjectName();
+ }
+
+ public String getSelectedResourceBundle() {
+ return selectedRB;
+ }
+
+ public String getSelectedKey() {
+ return selectedKey;
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructRBSection(dialogArea);
+ constructDefaultSection(dialogArea);
+ initContent();
+ return dialogArea;
+ }
+
+ protected void initContent() {
+ cmbRB.removeAll();
+ int iSel = -1;
+ int index = 0;
+
+ Collection<String> availableBundles = ResourceBundleManager.getManager(
+ projectName).getResourceBundleNames();
+
+ for (String bundle : availableBundles) {
+ cmbRB.add(bundle);
+ if (bundle.equals(selectedRB)) {
+ cmbRB.select(index);
+ iSel = index;
+ cmbRB.setEnabled(false);
+ }
+ index++;
+ }
+
+ if (availableBundles.size() > 0 && iSel < 0) {
+ cmbRB.select(0);
+ selectedRB = cmbRB.getText();
+ cmbRB.setEnabled(true);
+ }
+
+ rbModifyListener = new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ };
+ cmbRB.removeModifyListener(rbModifyListener);
+ cmbRB.addModifyListener(rbModifyListener);
+
+ cmbRB.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectedLocale = "";
+ updateAvailableLanguages();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ selectedLocale = "";
+ updateAvailableLanguages();
+ }
+ });
+ updateAvailableLanguages();
+ validate();
+ }
+
+ protected void updateAvailableLanguages() {
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
+
+ if ("".equals(selectedBundle.trim())) {
+ return;
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ int index = 0;
+ int iSel = -1;
+ for (Locale l : manager.getProvidedLocales(selectedBundle)) {
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (displayName.equals(selectedLocale))
+ iSel = index;
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ if (index == iSel)
+ cmbLanguage.select(iSel);
+ index++;
+ }
+
+ if (locales.size() > 0) {
+ cmbLanguage.select(0);
+ selectedLocale = cmbLanguage.getText();
+ }
+
+ cmbLanguage.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedLocale = cmbLanguage.getText();
+ validate();
+ }
+ });
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructRBSection(Composite parent) {
+ final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource Bundle");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
+ GridData.CENTER, false, false, 1, 1));
+ infoLabel
+ .setText("Specify the key of the new resource as well as the Resource-Bundle in\n"
+ + "which the resource" + "should be added.\n");
+
+ // Schl�ssel
+ final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblKey.setLayoutData(lblKeyGrid);
+ lblKey.setText("Key:");
+ txtKey = new Text(group, SWT.BORDER);
+ txtKey.setText(selectedKey);
+ // grey ouut textfield if there already is a preset key
+ txtKey.setEditable(selectedKey.trim().length() == 0
+ || selectedKey.indexOf("[Platzhalter]") >= 0
+ || selectedKey.equals(DEFAULT_KEY));
+ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ txtKey.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedKey = txtKey.getText();
+ validate();
+ }
+ });
+
+ // Resource-Bundle
+ final Label lblRB = new Label(group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
+
+ cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ }
+
+ protected void constructDefaultSection(Composite parent) {
+ final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ true, 1, 1));
+ group.setText("Default-Text");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
+ GridData.CENTER, false, false, 1, 1));
+ infoLabel
+ .setText("Define a default text for the specified resource. Moreover, you need to\n"
+ + "select the locale for which the default text should be defined.");
+
+ // Text
+ final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblTextGrid.heightHint = 80;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Text:");
+
+ txtDefaultText = new Text(group, SWT.MULTI | SWT.BORDER);
+ txtDefaultText.setText(selectedDefaultText);
+ txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1));
+ txtDefaultText.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedDefaultText = txtDefaultText.getText();
+ validate();
+ }
+ });
+
+ // Sprache
+ final Label lblLanguage = new Label(group, SWT.NONE);
+ lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1));
+ lblLanguage.setText("Language (Country):");
+
+ cmbLanguage = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ true, false, 1, 1));
+ }
+
+ @Override
+ protected void okPressed() {
+ super.okPressed();
+ // TODO debug
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ // Insert new Resource-Bundle reference
+ Locale locale = LocaleUtils.getLocaleByDisplayName(
+ manager.getProvidedLocales(selectedRB), selectedLocale); // new
+ // Locale("");
+ // //
+ // retrieve
+ // locale
+
+ try {
+ manager.addResourceBundleEntry(selectedRB, selectedKey, locale,
+ selectedDefaultText);
+ } catch (ResourceBundleException e) {
+ Logger.logError(e);
+ }
+ }
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Create Resource-Bundle entry");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("New Resource-Bundle entry");
+ this.setMessage("Please, specify details about the new Resource-Bundle entry");
+ }
+
+ /**
+ * Validates all inputs of the CreateResourceBundleEntryDialog
+ */
+ protected void validate() {
+ // Check Resource-Bundle ids
+ boolean keyValid = false;
+ boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey);
+ boolean rbValid = false;
+ boolean textValid = false;
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ boolean localeValid = LocaleUtils.containsLocaleByDisplayName(
+ manager.getProvidedLocales(selectedRB), selectedLocale);
+
+ for (String rbId : manager.getResourceBundleNames()) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
+
+ if (!manager.isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
+
+ if (selectedDefaultText.trim().length() > 0)
+ textValid = true;
+
+ // print Validation summary
+ String errorMessage = null;
+ if (selectedKey.trim().length() == 0)
+ errorMessage = "No resource key specified.";
+ else if (!keyValidChar)
+ errorMessage = "The specified resource key contains invalid characters.";
+ else if (!keyValid)
+ errorMessage = "The specified resource key is already existing.";
+ else if (!rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist.";
+ else if (!localeValid)
+ errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
+ else if (!textValid)
+ errorMessage = "No default translation specified.";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
+
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ okButton = createButton(parent, OK, "Ok", true);
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
+
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode(CANCEL);
+ close();
+ }
+ });
+
+ okButton.setEnabled(true);
+ cancelButton.setEnabled(true);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
new file mode 100644
index 00000000..6a503f64
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
@@ -0,0 +1,124 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.ListDialog;
+
+public class FragmentProjectSelectionDialog extends ListDialog {
+ private IProject hostproject;
+ private List<IProject> allProjects;
+
+ public FragmentProjectSelectionDialog(Shell parent, IProject hostproject,
+ List<IProject> fragmentprojects) {
+ super(parent);
+ this.hostproject = hostproject;
+ this.allProjects = new ArrayList<IProject>(fragmentprojects);
+ allProjects.add(0, hostproject);
+
+ init();
+ }
+
+ private void init() {
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following plug-ins:");
+ this.setTitle("Project Selector");
+ this.setContentProvider(new IProjectContentProvider());
+ this.setLabelProvider(new IProjectLabelProvider());
+
+ this.setInput(allProjects);
+ }
+
+ public IProject getSelectedProject() {
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (IProject) selection[0];
+ return null;
+ }
+
+ // private classes--------------------------------------------------------
+ class IProjectContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ List<IProject> resources = (List<IProject>) inputElement;
+ return resources.toArray();
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+ }
+
+ }
+
+ class IProjectLabelProvider implements ILabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_PROJECT);
+ }
+
+ @Override
+ public String getText(Object element) {
+ IProject p = ((IProject) element);
+ String text = p.getName();
+ if (p.equals(hostproject))
+ text += " [host project]";
+ else
+ text += " [fragment project]";
+ return text;
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
new file mode 100644
index 00000000..841c7290
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
@@ -0,0 +1,146 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.dialogs;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class GenerateBundleAccessorDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+
+ private Text bundleAccessor;
+ private Text packageName;
+
+ public GenerateBundleAccessorDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructBASection(dialogArea);
+ // constructDefaultSection (dialogArea);
+ initContent();
+ return dialogArea;
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructBASection(Composite parent) {
+ final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource Bundle");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING,
+ GridData.CENTER, false, false, 1, 1));
+ infoLabel
+ .setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
+
+ // Schl�ssel
+ final Label lblBA = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1);
+ lblBAGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblBA.setLayoutData(lblBAGrid);
+ lblBA.setText("Class-Name:");
+
+ bundleAccessor = new Text(group, SWT.BORDER);
+ bundleAccessor.setLayoutData(new GridData(GridData.FILL,
+ GridData.CENTER, true, false, 1, 1));
+
+ // Resource-Bundle
+ final Label lblPkg = new Label(group, SWT.NONE);
+ lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblPkg.setText("Package:");
+
+ packageName = new Text(group, SWT.BORDER);
+ packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ true, false, 1, 1));
+ }
+
+ protected void initContent() {
+ bundleAccessor.setText("BundleAccessor");
+ packageName.setText("a.b");
+ }
+
+ /*
+ * protected void constructDefaultSection(Composite parent) { final Group
+ * group = new Group (parent, SWT.SHADOW_ETCHED_IN); group.setLayoutData(new
+ * GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1));
+ * group.setText("Basis-Text");
+ *
+ * // define grid data for this group GridData gridData = new GridData();
+ * gridData.horizontalAlignment = SWT.FILL;
+ * gridData.grabExcessHorizontalSpace = true; group.setLayoutData(gridData);
+ * group.setLayout(new GridLayout(2, false));
+ *
+ * final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ * spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ * false, false, 1, 1));
+ *
+ * final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ * infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ * false, false, 1, 1)); infoLabel.setText(
+ * "Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar."
+ * );
+ *
+ * // Text final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
+ * GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false,
+ * false, 1, 1); lblTextGrid.heightHint = 80; lblTextGrid.widthHint = 100;
+ * lblText.setLayoutData(lblTextGrid); lblText.setText("Text:");
+ *
+ * txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER);
+ * txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
+ * true, true, 1, 1));
+ *
+ * // Sprache final Label lblLanguage = new Label (group, SWT.NONE);
+ * lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ * false, false, 1, 1)); lblLanguage.setText("Sprache (Land):");
+ *
+ * cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ * cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ * true, false, 1, 1)); }
+ */
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Create Resource-Bundle Accessor");
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
new file mode 100644
index 00000000..9c17b28c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
@@ -0,0 +1,462 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.dialogs;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.ResourceSelector;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class QueryResourceBundleEntryDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+ private static int SEARCH_FULLTEXT = 0;
+ private static int SEARCH_KEY = 1;
+
+ private ResourceBundleManager manager;
+ private Collection<String> availableBundles;
+ private int searchOption = SEARCH_FULLTEXT;
+ private String resourceBundle = "";
+
+ private Combo cmbRB;
+
+ private Text txtKey;
+ private Button btSearchText;
+ private Button btSearchKey;
+ private Combo cmbLanguage;
+ private ResourceSelector resourceSelector;
+ private Text txtPreviewText;
+
+ private Button okButton;
+ private Button cancelButton;
+
+ /*** DIALOG MODEL ***/
+ private String selectedRB = "";
+ private String preselectedRB = "";
+ private Locale selectedLocale = null;
+ private String selectedKey = "";
+
+ public QueryResourceBundleEntryDialog(Shell parentShell,
+ ResourceBundleManager manager, String bundleName) {
+ super(parentShell);
+ this.manager = manager;
+ // init available resource bundles
+ this.availableBundles = manager.getResourceBundleNames();
+ this.preselectedRB = bundleName;
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructSearchSection(dialogArea);
+ initContent();
+ return dialogArea;
+ }
+
+ protected void initContent() {
+ // init available resource bundles
+ cmbRB.removeAll();
+ int i = 0;
+ for (String bundle : availableBundles) {
+ cmbRB.add(bundle);
+ if (bundle.equals(preselectedRB)) {
+ cmbRB.select(i);
+ cmbRB.setEnabled(false);
+ }
+ i++;
+ }
+
+ if (availableBundles.size() > 0) {
+ if (preselectedRB.trim().length() == 0) {
+ cmbRB.select(0);
+ cmbRB.setEnabled(true);
+ }
+ }
+
+ cmbRB.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
+ });
+
+ // init available translations
+ // updateAvailableLanguages();
+
+ // init resource selector
+ updateResourceSelector();
+
+ // update search options
+ updateSearchOptions();
+ }
+
+ protected void updateResourceSelector() {
+ resourceBundle = cmbRB.getText();
+ resourceSelector.setResourceBundle(resourceBundle);
+ }
+
+ protected void updateSearchOptions() {
+ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY
+ : SEARCH_FULLTEXT);
+ // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
+ // lblLanguage.setEnabled(cmbLanguage.getEnabled());
+
+ // update ResourceSelector
+ resourceSelector
+ .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
+ : ResourceSelector.DISPLAY_KEYS);
+ }
+
+ protected void updateAvailableLanguages() {
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ for (Locale l : locales) {
+ String displayName = l.getDisplayName();
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ }
+
+ // if (locales.size() > 0) {
+ // cmbLanguage.select(0);
+ updateSelectedLocale();
+ // }
+ }
+
+ protected void updateSelectedLocale() {
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ Iterator<Locale> it = locales.iterator();
+ String selectedLocale = cmbLanguage.getText();
+ while (it.hasNext()) {
+ Locale l = it.next();
+ if (l.getDisplayName().equals(selectedLocale)) {
+ resourceSelector.setDisplayLocale(l);
+ break;
+ }
+ }
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructSearchSection(Composite parent) {
+ final Group group = new Group(parent, SWT.NONE);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource selection");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+ // TODO export as help text
+
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ GridData infoGrid = new GridData(GridData.BEGINNING,
+ GridData.BEGINNING, false, false, 1, 1);
+ infoGrid.heightHint = 70;
+ infoLabel.setLayoutData(infoGrid);
+ infoLabel
+ .setText("Select the resource that needs to be refrenced. This is achieved in two\n"
+ + "steps. First select the Resource-Bundle in which the resource is located. \n"
+ + "In a last step you need to choose the required resource.");
+
+ // Resource-Bundle
+ final Label lblRB = new Label(group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
+
+ cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ cmbRB.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ });
+
+ // Search-Options
+ final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ Composite searchOptions = new Composite(group, SWT.NONE);
+ searchOptions.setLayout(new GridLayout(2, true));
+
+ btSearchText = new Button(searchOptions, SWT.RADIO);
+ btSearchText.setText("Full-text");
+ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
+ btSearchText.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ btSearchKey = new Button(searchOptions, SWT.RADIO);
+ btSearchKey.setText("Key");
+ btSearchKey.setSelection(searchOption == SEARCH_KEY);
+ btSearchKey.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ // Sprache
+ // lblLanguage = new Label (group, SWT.NONE);
+ // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ // false, false, 1, 1));
+ // lblLanguage.setText("Language (Country):");
+ //
+ // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ // cmbLanguage.setLayoutData(new GridData(GridData.FILL,
+ // GridData.CENTER, true, false, 1, 1));
+ // cmbLanguage.addSelectionListener(new SelectionListener () {
+ //
+ // @Override
+ // public void widgetDefaultSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // @Override
+ // public void widgetSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // });
+ // cmbLanguage.addModifyListener(new ModifyListener() {
+ // @Override
+ // public void modifyText(ModifyEvent e) {
+ // selectedLocale =
+ // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB),
+ // cmbLanguage.getText());
+ // validate();
+ // }
+ // });
+
+ // Filter
+ final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblKey.setLayoutData(lblKeyGrid);
+ lblKey.setText("Filter:");
+
+ txtKey = new Text(group, SWT.BORDER);
+ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+
+ // Add selector for property keys
+ final Label lblKeys = new Label(group, SWT.NONE);
+ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING,
+ false, false, 1, 1));
+ lblKeys.setText("Resource:");
+
+ resourceSelector = new ResourceSelector(group, SWT.NONE);
+
+ resourceSelector.setProjectName(manager.getProject().getName());
+ resourceSelector.setResourceBundle(cmbRB.getText());
+ resourceSelector.setDisplayMode(searchOption);
+
+ GridData resourceSelectionData = new GridData(GridData.FILL,
+ GridData.CENTER, true, false, 1, 1);
+ resourceSelectionData.heightHint = 150;
+ resourceSelectionData.widthHint = 400;
+ resourceSelector.setLayoutData(resourceSelectionData);
+ resourceSelector
+ .addSelectionChangedListener(new IResourceSelectionListener() {
+
+ @Override
+ public void selectionChanged(ResourceSelectionEvent e) {
+ selectedKey = e.getSelectedKey();
+ updatePreviewLabel(e.getSelectionSummary());
+ validate();
+ }
+ });
+
+ // final Label spacer = new Label (group, SWT.SEPARATOR |
+ // SWT.HORIZONTAL);
+ // spacer.setLayoutData(new GridData(GridData.BEGINNING,
+ // GridData.CENTER, true, false, 2, 1));
+
+ // Preview
+ final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblTextGrid.heightHint = 120;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Preview:");
+
+ txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
+ txtPreviewText.setEditable(false);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1);
+ txtPreviewText.setLayoutData(lblTextGrid2);
+ }
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Insert Resource-Bundle-Reference");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("Reference a Resource");
+ this.setMessage("Please, specify details about the required Resource-Bundle reference");
+ }
+
+ protected void updatePreviewLabel(String previewText) {
+ txtPreviewText.setText(previewText);
+ }
+
+ protected void validate() {
+ // Check Resource-Bundle ids
+ boolean rbValid = false;
+ boolean localeValid = false;
+ boolean keyValid = false;
+
+ for (String rbId : this.availableBundles) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
+
+ if (selectedLocale != null)
+ localeValid = true;
+
+ if (manager.isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
+
+ // print Validation summary
+ String errorMessage = null;
+ if (!rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist";
+ // else if (! localeValid)
+ // errorMessage =
+ // "The specified Locale does not exist for the selecte Resource-Bundle";
+ else if (!keyValid)
+ errorMessage = "No resource selected";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
+
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ okButton = createButton(parent, OK, "Ok", true);
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
+
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode(CANCEL);
+ close();
+ }
+ });
+
+ okButton.setEnabled(false);
+ cancelButton.setEnabled(true);
+ }
+
+ public String getSelectedResourceBundle() {
+ return selectedRB;
+ }
+
+ public String getSelectedResource() {
+ return selectedKey;
+ }
+
+ public Locale getSelectedLocale() {
+ return selectedLocale;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
new file mode 100644
index 00000000..17b8721c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
@@ -0,0 +1,123 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.dialogs;
+
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.dialogs.ListDialog;
+
+public class RemoveLanguageDialoge extends ListDialog {
+ private IProject project;
+
+ public RemoveLanguageDialoge(IProject project, Shell shell) {
+ super(shell);
+ this.project = project;
+
+ initDialog();
+ }
+
+ protected void initDialog() {
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following languages to delete:");
+ this.setTitle("Language Selector");
+ this.setContentProvider(new RBContentProvider());
+ this.setLabelProvider(new RBLabelProvider());
+
+ this.setInput(ResourceBundleManager.getManager(project)
+ .getProjectProvidedLocales());
+ }
+
+ public Locale getSelectedLanguage() {
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (Locale) selection[0];
+ return null;
+ }
+
+ // private
+ // classes-------------------------------------------------------------------------------------
+ class RBContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ Set<Locale> resources = (Set<Locale>) inputElement;
+ return resources.toArray();
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ class RBLabelProvider implements ILabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ }
+
+ @Override
+ public String getText(Object element) {
+ Locale l = ((Locale) element);
+ String text = l.getDisplayName();
+ if (text == null || text.equals(""))
+ text = "default";
+ else
+ text += " - " + l.getLanguage() + " " + l.getCountry() + " "
+ + l.getVariant();
+ return text;
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
new file mode 100644
index 00000000..d204f767
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
@@ -0,0 +1,474 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.dialogs;
+
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.ResourceSelector;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+ private static int SEARCH_FULLTEXT = 0;
+ private static int SEARCH_KEY = 1;
+
+ private String projectName;
+ private String bundleName;
+
+ private int searchOption = SEARCH_FULLTEXT;
+ private String resourceBundle = "";
+
+ private Combo cmbRB;
+
+ private Button btSearchText;
+ private Button btSearchKey;
+ private Combo cmbLanguage;
+ private ResourceSelector resourceSelector;
+ private Text txtPreviewText;
+
+ private Button okButton;
+ private Button cancelButton;
+
+ /*** DIALOG MODEL ***/
+ private String selectedRB = "";
+ private String preselectedRB = "";
+ private Locale selectedLocale = null;
+ private String selectedKey = "";
+
+ public ResourceBundleEntrySelectionDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout(dialogArea);
+ constructSearchSection(dialogArea);
+ initContent();
+ return dialogArea;
+ }
+
+ protected void initContent() {
+ // init available resource bundles
+ cmbRB.removeAll();
+ int i = 0;
+ for (String bundle : ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames()) {
+ cmbRB.add(bundle);
+ if (bundle.equals(preselectedRB)) {
+ cmbRB.select(i);
+ cmbRB.setEnabled(false);
+ }
+ i++;
+ }
+
+ if (ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames().size() > 0) {
+ if (preselectedRB.trim().length() == 0) {
+ cmbRB.select(0);
+ cmbRB.setEnabled(true);
+ }
+ }
+
+ cmbRB.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // updateAvailableLanguages();
+ updateResourceSelector();
+ }
+ });
+
+ // init available translations
+ // updateAvailableLanguages();
+
+ // init resource selector
+ updateResourceSelector();
+
+ // update search options
+ updateSearchOptions();
+ }
+
+ protected void updateResourceSelector() {
+ resourceBundle = cmbRB.getText();
+ resourceSelector.setResourceBundle(resourceBundle);
+ }
+
+ protected void updateSearchOptions() {
+ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY
+ : SEARCH_FULLTEXT);
+ // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
+ // lblLanguage.setEnabled(cmbLanguage.getEnabled());
+
+ // update ResourceSelector
+ resourceSelector
+ .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT
+ : ResourceSelector.DISPLAY_KEYS);
+ }
+
+ protected void updateAvailableLanguages() {
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName)
+ .getProvidedLocales(selectedBundle);
+ for (Locale l : locales) {
+ String displayName = l.getDisplayName();
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ }
+
+ // if (locales.size() > 0) {
+ // cmbLanguage.select(0);
+ updateSelectedLocale();
+ // }
+ }
+
+ protected void updateSelectedLocale() {
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName)
+ .getProvidedLocales(selectedBundle);
+ Iterator<Locale> it = locales.iterator();
+ String selectedLocale = cmbLanguage.getText();
+ while (it.hasNext()) {
+ Locale l = it.next();
+ if (l.getDisplayName().equals(selectedLocale)) {
+ resourceSelector.setDisplayLocale(l);
+ break;
+ }
+ }
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructSearchSection(Composite parent) {
+ final Group group = new Group(parent, SWT.NONE);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ group.setText("Resource selection");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+ // TODO export as help text
+
+ final Label spacer = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT);
+ GridData infoGrid = new GridData(GridData.BEGINNING,
+ GridData.BEGINNING, false, false, 1, 1);
+ infoGrid.heightHint = 70;
+ infoLabel.setLayoutData(infoGrid);
+ infoLabel
+ .setText("Select the resource that needs to be refrenced. This is accomplished in two\n"
+ + "steps. First select the Resource-Bundle in which the resource is located. \n"
+ + "In a last step you need to choose a particular resource.");
+
+ // Resource-Bundle
+ final Label lblRB = new Label(group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false,
+ false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
+
+ cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true,
+ false, 1, 1));
+ cmbRB.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ });
+
+ // Search-Options
+ final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT);
+ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
+ false, false, 1, 1));
+
+ Composite searchOptions = new Composite(group, SWT.NONE);
+ searchOptions.setLayout(new GridLayout(2, true));
+
+ btSearchText = new Button(searchOptions, SWT.RADIO);
+ btSearchText.setText("Flat");
+ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
+ btSearchText.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ btSearchKey = new Button(searchOptions, SWT.RADIO);
+ btSearchKey.setText("Hierarchical");
+ btSearchKey.setSelection(searchOption == SEARCH_KEY);
+ btSearchKey.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ // Sprache
+ // lblLanguage = new Label (group, SWT.NONE);
+ // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER,
+ // false, false, 1, 1));
+ // lblLanguage.setText("Language (Country):");
+ //
+ // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ // cmbLanguage.setLayoutData(new GridData(GridData.FILL,
+ // GridData.CENTER, true, false, 1, 1));
+ // cmbLanguage.addSelectionListener(new SelectionListener () {
+ //
+ // @Override
+ // public void widgetDefaultSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // @Override
+ // public void widgetSelected(SelectionEvent e) {
+ // updateSelectedLocale();
+ // }
+ //
+ // });
+ // cmbLanguage.addModifyListener(new ModifyListener() {
+ // @Override
+ // public void modifyText(ModifyEvent e) {
+ // selectedLocale =
+ // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB),
+ // cmbLanguage.getText());
+ // validate();
+ // }
+ // });
+
+ // Filter
+ // final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
+ // GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER,
+ // false, false, 1, 1);
+ // lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ // lblKey.setLayoutData(lblKeyGrid);
+ // lblKey.setText("Filter:");
+ //
+ // txtKey = new Text (group, SWT.BORDER);
+ // txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER,
+ // true, false, 1, 1));
+
+ // Add selector for property keys
+ final Label lblKeys = new Label(group, SWT.NONE);
+ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING,
+ false, false, 1, 1));
+ lblKeys.setText("Resource:");
+
+ resourceSelector = new ResourceSelector(group, SWT.NONE);
+
+ resourceSelector.setProjectName(projectName);
+ resourceSelector.setResourceBundle(cmbRB.getText());
+ resourceSelector.setDisplayMode(searchOption);
+
+ GridData resourceSelectionData = new GridData(GridData.FILL,
+ GridData.CENTER, true, false, 1, 1);
+ resourceSelectionData.heightHint = 150;
+ resourceSelectionData.widthHint = 400;
+ resourceSelector.setLayoutData(resourceSelectionData);
+ resourceSelector
+ .addSelectionChangedListener(new IResourceSelectionListener() {
+
+ @Override
+ public void selectionChanged(ResourceSelectionEvent e) {
+ selectedKey = e.getSelectedKey();
+ updatePreviewLabel(e.getSelectionSummary());
+ validate();
+ }
+ });
+
+ // final Label spacer = new Label (group, SWT.SEPARATOR |
+ // SWT.HORIZONTAL);
+ // spacer.setLayoutData(new GridData(GridData.BEGINNING,
+ // GridData.CENTER, true, false, 2, 1));
+
+ // Preview
+ final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER,
+ false, false, 1, 1);
+ lblTextGrid.heightHint = 120;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Preview:");
+
+ txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
+ txtPreviewText.setEditable(false);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL,
+ true, true, 1, 1);
+ txtPreviewText.setLayoutData(lblTextGrid2);
+ }
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Select Resource-Bundle entry");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("Select a Resource-Bundle entry");
+ this.setMessage("Please, select a resource of a particular Resource-Bundle");
+ }
+
+ protected void updatePreviewLabel(String previewText) {
+ txtPreviewText.setText(previewText);
+ }
+
+ protected void validate() {
+ // Check Resource-Bundle ids
+ boolean rbValid = false;
+ boolean localeValid = false;
+ boolean keyValid = false;
+
+ for (String rbId : ResourceBundleManager.getManager(projectName)
+ .getResourceBundleNames()) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
+
+ if (selectedLocale != null)
+ localeValid = true;
+
+ if (ResourceBundleManager.getManager(projectName).isResourceExisting(
+ selectedRB, selectedKey))
+ keyValid = true;
+
+ // print Validation summary
+ String errorMessage = null;
+ if (!rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist";
+ // else if (! localeValid)
+ // errorMessage =
+ // "The specified Locale does not exist for the selecte Resource-Bundle";
+ else if (!keyValid)
+ errorMessage = "No resource selected";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
+
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ okButton = createButton(parent, OK, "Ok", true);
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
+
+ cancelButton = createButton(parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode(CANCEL);
+ close();
+ }
+ });
+
+ okButton.setEnabled(false);
+ cancelButton.setEnabled(true);
+ }
+
+ public String getSelectedResourceBundle() {
+ return selectedRB;
+ }
+
+ public String getSelectedResource() {
+ return selectedKey;
+ }
+
+ public Locale getSelectedLocale() {
+ return selectedLocale;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public void setBundleName(String bundleName) {
+ this.bundleName = bundleName;
+
+ if (preselectedRB.isEmpty()) {
+ preselectedRB = this.bundleName;
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
new file mode 100644
index 00000000..c01fb367
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
@@ -0,0 +1,121 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Matthias Lettmayer - adapt setInput, so only existing RB get displayed (fixed issue 40)
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.List;
+
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.dialogs.ListDialog;
+
+public class ResourceBundleSelectionDialog extends ListDialog {
+
+ private IProject project;
+
+ public ResourceBundleSelectionDialog(Shell parent, IProject project) {
+ super(parent);
+ this.project = project;
+
+ initDialog();
+ }
+
+ protected void initDialog() {
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following Resource-Bundle to open:");
+ this.setTitle("Resource-Bundle Selector");
+ this.setContentProvider(new RBContentProvider());
+ this.setLabelProvider(new RBLabelProvider());
+ this.setBlockOnOpen(true);
+
+ if (project != null)
+ this.setInput(RBManager.getInstance(project)
+ .getMessagesBundleGroupNames());
+ else
+ this.setInput(RBManager.getAllMessagesBundleGroupNames());
+ }
+
+ public String getSelectedBundleId() {
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (String) selection[0];
+ return null;
+ }
+
+ class RBContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ List<String> resources = (List<String>) inputElement;
+ return resources.toArray();
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ class RBLabelProvider implements ILabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ // TODO Auto-generated method stub
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ }
+
+ @Override
+ public String getText(Object element) {
+ // TODO Auto-generated method stub
+ return ((String) element);
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java
new file mode 100644
index 00000000..79fcfda6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.extensions;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+public abstract class I18nAuditor {
+
+ /**
+ * Audits a project resource for I18N problems. This method is triggered
+ * during the project's build process.
+ *
+ * @param resource
+ * The project resource
+ */
+ public abstract void audit(IResource resource);
+
+ /**
+ * Returns a characterizing identifier of the implemented auditing
+ * functionality. The specified identifier is used for discriminating
+ * registered builder extensions.
+ *
+ * @return The String id of the implemented auditing functionality
+ */
+ public abstract String getContextId();
+
+ /**
+ * Returns a list of supported file endings.
+ *
+ * @return The supported file endings
+ */
+ public abstract String[] getFileEndings();
+
+ /**
+ * Returns a list of quick fixes of a reported Internationalization problem.
+ *
+ * @param marker
+ * The warning marker of the Internationalization problem
+ * @param cause
+ * The problem type
+ * @return The list of marker resolution proposals
+ */
+ public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker);
+
+ /**
+ * Checks if the provided resource auditor is responsible for a particular
+ * resource.
+ *
+ * @param resource
+ * The resource reference
+ * @return True if the resource auditor is responsible for the referenced
+ * resource
+ */
+ public boolean isResourceOfType(IResource resource) {
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..9c0f6c5b
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nRBAuditor.java
@@ -0,0 +1,57 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.extensions;
+
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+
+/**
+ *
+ *
+ */
+public abstract class I18nRBAuditor extends I18nAuditor {
+
+ /**
+ * Mark the end of a audit and reset all problemlists
+ */
+ public abstract void resetProblems();
+
+ /**
+ * Returns the list of missing keys or no specified Resource-Bundle-key
+ * refernces. Each list entry describes the textual position on which this
+ * type of error has been detected.
+ *
+ * @return The list of positions of no specified RB-key refernces
+ */
+ public abstract List<ILocation> getUnspecifiedKeyReferences();
+
+ /**
+ * Returns the list of same Resource-Bundle-value refernces. Each list entry
+ * describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of positions of same RB-value refernces
+ */
+ public abstract Map<ILocation, ILocation> getSameValuesReferences();
+
+ /**
+ * Returns the list of missing Resource-Bundle-languages compared with the
+ * Resource-Bundles of the hole project. Each list entry describes the
+ * textual position on which this type of error has been detected.
+ *
+ * @return
+ */
+ public abstract List<ILocation> getMissingLanguageReferences();
+
+ // public abstract List<ILocation> getUnusedKeyReferences();
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..65fff9ec
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java
@@ -0,0 +1,107 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.extensions;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+/**
+ * Auditor class for finding I18N problems within source code resources. The
+ * objects audit method is called for a particular resource. Found errors are
+ * stored within the object's internal data structure and can be queried with
+ * the help of problem categorized getter methods.
+ */
+public abstract class I18nResourceAuditor extends I18nAuditor {
+ /**
+ * Audits a project resource for I18N problems. This method is triggered
+ * during the project's build process.
+ *
+ * @param resource
+ * The project resource
+ */
+ public abstract void audit(IResource resource);
+
+ /**
+ * Returns a list of supported file endings.
+ *
+ * @return The supported file endings
+ */
+ public abstract String[] getFileEndings();
+
+ /**
+ * Returns the list of found need-to-translate string literals. Each list
+ * entry describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of need-to-translate string literal positions
+ */
+ public abstract List<ILocation> getConstantStringLiterals();
+
+ /**
+ * Returns the list of broken Resource-Bundle references. Each list entry
+ * describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of positions of broken Resource-Bundle references
+ */
+ public abstract List<ILocation> getBrokenResourceReferences();
+
+ /**
+ * Returns the list of broken references to Resource-Bundle entries. Each
+ * list entry describes the textual position on which this type of error has
+ * been detected
+ *
+ * @return The list of positions of broken references to locale-sensitive
+ * resources
+ */
+ public abstract List<ILocation> getBrokenBundleReferences();
+
+ /**
+ * Returns a characterizing identifier of the implemented auditing
+ * functionality. The specified identifier is used for discriminating
+ * registered builder extensions.
+ *
+ * @return The String id of the implemented auditing functionality
+ */
+ public abstract String getContextId();
+
+ /**
+ * Returns a list of quick fixes of a reported Internationalization problem.
+ *
+ * @param marker
+ * The warning marker of the Internationalization problem
+ * @param cause
+ * The problem type
+ * @return The list of marker resolution proposals
+ */
+ public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker);
+
+ /**
+ * Checks if the provided resource auditor is responsible for a particular
+ * resource.
+ *
+ * @param resource
+ * The resource reference
+ * @return True if the resource auditor is responsible for the referenced
+ * resource
+ */
+ public boolean isResourceOfType(IResource resource) {
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..13f6408d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.filters;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+public class PropertiesFileFilter extends ViewerFilter {
+
+ private boolean debugEnabled = true;
+
+ public PropertiesFileFilter() {
+
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (debugEnabled)
+ return true;
+
+ if (element.getClass().getSimpleName().equals("CompilationUnit"))
+ return false;
+
+ if (!(element instanceof IFile))
+ return true;
+
+ IFile file = (IFile) element;
+
+ return file.getFileExtension().equalsIgnoreCase("properties");
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
new file mode 100644
index 00000000..5ff02055
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Matthias Lettmayer - created a marker updater, which updates it's position (fixes Issue 8)
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.markers;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.Position;
+import org.eclipse.ui.texteditor.IMarkerUpdater;
+
+public class MarkerUpdater implements IMarkerUpdater {
+
+ @Override
+ public String getMarkerType() {
+ return "org.eclipse.core.resources.problemmarker";
+ }
+
+ @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;
+ }
+ }
+}
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
new file mode 100644
index 00000000..0588ee2e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java
@@ -0,0 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
new file mode 100644
index 00000000..3c09af58
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
@@ -0,0 +1,127 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.memento;
+
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceDescriptor;
+import org.eclipse.babel.tapiji.tools.core.model.ResourceDescriptor;
+import org.eclipse.babel.tapiji.tools.core.model.manager.IStateLoader;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.FileUtils;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.XMLMemento;
+
+/**
+ * Loads the state of the {@link ResourceBundleManager}.<br>
+ * <br>
+ *
+ * @author Alexej Strelzow
+ */
+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() {
+
+ 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 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 Set<IResourceDescriptor> getExcludedResources() {
+ return excludedResources;
+ }
+
+ /**
+ * {@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
new file mode 100644
index 00000000..5eaca5a5
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
@@ -0,0 +1,432 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.menus;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.AddLanguageDialoge;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.FragmentProjectSelectionDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.GenerateBundleAccessorDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.RemoveLanguageDialoge;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.LanguageUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.progress.IProgressService;
+
+public class InternationalizationMenu extends ContributionItem {
+ private boolean excludeMode = true;
+ private boolean internationalizationEnabled = false;
+
+ private MenuItem mnuToggleInt;
+ private MenuItem excludeResource;
+ private MenuItem addLanguage;
+ private MenuItem removeLanguage;
+
+ public InternationalizationMenu() {
+ }
+
+ public InternationalizationMenu(String id) {
+ super(id);
+ }
+
+ @Override
+ public void fill(Menu menu, int index) {
+ if (getSelectedProjects().size() == 0 || !projectsSupported()) {
+ return;
+ }
+
+ // Toggle Internatinalization
+ mnuToggleInt = new MenuItem(menu, SWT.PUSH);
+ mnuToggleInt.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runToggleInt();
+ }
+
+ });
+
+ // Exclude Resource
+ excludeResource = new MenuItem(menu, SWT.PUSH);
+ excludeResource.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runExclude();
+ }
+
+ });
+
+ new MenuItem(menu, SWT.SEPARATOR);
+
+ // Add Language
+ addLanguage = new MenuItem(menu, SWT.PUSH);
+ addLanguage.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runAddLanguage();
+ }
+
+ });
+
+ // Remove Language
+ removeLanguage = new MenuItem(menu, SWT.PUSH);
+ removeLanguage.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runRemoveLanguage();
+ }
+
+ });
+
+ menu.addMenuListener(new MenuAdapter() {
+ @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 updateStateToggleInt(MenuItem menuItem) {
+ Collection<IProject> projects = getSelectedProjects();
+ boolean enabled = projects.size() > 0;
+ menuItem.setEnabled(enabled);
+ setVisible(enabled);
+ internationalizationEnabled = InternationalizationNature
+ .hasNature(projects.iterator().next());
+ // menuItem.setSelection(enabled && internationalizationEnabled);
+
+ if (internationalizationEnabled) {
+ menuItem.setText("Disable Internationalization");
+ } else {
+ menuItem.setText("Enable Internationalization");
+ }
+ }
+
+ private Collection<IPackageFragment> getSelectedPackageFragments() {
+ Collection<IPackageFragment> frags = new HashSet<IPackageFragment>();
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IPackageFragment) {
+ IPackageFragment frag = (IPackageFragment) elem;
+ if (!frag.isReadOnly()) {
+ frags.add(frag);
+ }
+ }
+ }
+ }
+ return frags;
+ }
+
+ private Collection<IProject> getSelectedProjects() {
+ Collection<IProject> projects = new HashSet<IProject>();
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (!(elem instanceof IResource)) {
+ if (!(elem instanceof IAdaptable)) {
+ continue;
+ }
+ elem = ((IAdaptable) elem).getAdapter(IResource.class);
+ if (!(elem instanceof IResource)) {
+ continue;
+ }
+ }
+ if (!(elem instanceof IProject)) {
+ elem = ((IResource) elem).getProject();
+ if (!(elem instanceof IProject)) {
+ continue;
+ }
+ }
+ if (((IProject) elem).isAccessible()) {
+ projects.add((IProject) elem);
+ }
+
+ }
+ }
+ return projects;
+ }
+
+ protected boolean projectsSupported() {
+ Collection<IProject> projects = getSelectedProjects();
+ for (IProject project : projects) {
+ if (!InternationalizationNature.supportsNature(project)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ protected void runToggleInt() {
+ Collection<IProject> projects = getSelectedProjects();
+ for (IProject project : projects) {
+ toggleNature(project);
+ }
+ }
+
+ private void toggleNature(IProject project) {
+ if (InternationalizationNature.hasNature(project)) {
+ InternationalizationNature.removeNature(project);
+ } else {
+ InternationalizationNature.addNature(project);
+ }
+ }
+
+ protected void updateStateExclude(MenuItem menuItem) {
+ Collection<IResource> resources = getSelectedResources();
+ menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled);
+ ResourceBundleManager manager = null;
+ excludeMode = false;
+
+ for (IResource res : resources) {
+ if (manager == null || (manager.getProject() != res.getProject())) {
+ manager = ResourceBundleManager.getManager(res.getProject());
+ }
+ try {
+ if (!ResourceBundleManager.isResourceExcluded(res)) {
+ excludeMode = true;
+ }
+ } catch (Exception e) {
+ }
+ }
+
+ if (!excludeMode) {
+ menuItem.setText("Include Resource");
+ } else {
+ menuItem.setText("Exclude Resource");
+ }
+ }
+
+ private Collection<IResource> getSelectedResources() {
+ Collection<IResource> resources = new HashSet<IResource>();
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IProject) {
+ continue;
+ }
+
+ if (elem instanceof IResource) {
+ resources.add((IResource) elem);
+ } else if (elem instanceof IJavaElement) {
+ resources.add(((IJavaElement) elem).getResource());
+ }
+ }
+ }
+ return resources;
+ }
+
+ protected void runExclude() {
+ final Collection<IResource> selectedResources = getSelectedResources();
+
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ @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;
+ }
+
+ menuItem.setText("Add Language To Project");
+ menuItem.setEnabled(projects.size() > 0 && hasResourceBundles);
+ }
+
+ protected void runAddLanguage() {
+ AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(
+ Display.getCurrent()));
+ if (dialog.open() == InputDialog.OK) {
+ final Locale locale = dialog.getSelectedLanguage();
+
+ Collection<IProject> selectedProjects = getSelectedProjects();
+ for (IProject project : selectedProjects) {
+ // check if project is fragmentproject and continue working with
+ // the hostproject, if host not member of selectedProjects
+ if (FragmentProjectUtils.isFragment(project)) {
+ IProject host = FragmentProjectUtils
+ .getFragmentHost(project);
+ if (!selectedProjects.contains(host)) {
+ project = host;
+ } else {
+ continue;
+ }
+ }
+
+ List<IProject> fragments = FragmentProjectUtils
+ .getFragments(project);
+
+ if (!fragments.isEmpty()) {
+ FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog(
+ Display.getCurrent().getActiveShell(), project,
+ fragments);
+
+ if (fragmentDialog.open() == InputDialog.OK) {
+ project = fragmentDialog.getSelectedProject();
+ }
+ }
+
+ final IProject selectedProject = project;
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ LanguageUtils.addLanguageToProject(selectedProject,
+ locale);
+ }
+
+ });
+
+ }
+ }
+ }
+
+ protected void updateStateRemoveLanguage(MenuItem menuItem) {
+ Collection<IProject> projects = getSelectedProjects();
+ boolean hasResourceBundles = false;
+ if (projects.size() == 1) {
+ IProject project = projects.iterator().next();
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(project);
+ hasResourceBundles = rbmanager.getResourceBundleIdentifiers()
+ .size() > 0 ? true : false;
+ }
+ menuItem.setText("Remove Language From Project");
+ menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*
+ * && more
+ * than one
+ * common
+ * languages
+ * contained
+ */);
+ }
+
+ protected void runRemoveLanguage() {
+ final IProject project = getSelectedProjects().iterator().next();
+ RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project,
+ new Shell(Display.getCurrent()));
+
+ if (dialog.open() == InputDialog.OK) {
+ final Locale locale = dialog.getSelectedLanguage();
+ if (locale != null) {
+ if (MessageDialog.openConfirm(Display.getCurrent()
+ .getActiveShell(), "Confirm",
+ "Do you really want remove all properties-files for "
+ + locale.getDisplayName() + "?")) {
+ BusyIndicator.showWhile(Display.getCurrent(),
+ new Runnable() {
+ @Override
+ public void run() {
+ 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
new file mode 100644
index 00000000..015af438
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java
@@ -0,0 +1,156 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.preferences;
+
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class BuilderPreferencePage extends PreferencePage implements
+ IWorkbenchPreferencePage {
+ private static final int INDENT = 20;
+
+ private Button checkSameValueButton;
+ private Button checkMissingValueButton;
+ private Button checkMissingLanguageButton;
+
+ private Button rbAuditButton;
+
+ private Button sourceAuditButton;
+
+ @Override
+ public void init(IWorkbench workbench) {
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ IPreferenceStore prefs = getPreferenceStore();
+ Composite composite = new Composite(parent, SWT.SHADOW_OUT);
+
+ composite.setLayout(new GridLayout(1, false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+
+ Composite field = createComposite(parent, 0, 10);
+ Label descriptionLabel = new Label(composite, SWT.NONE);
+ descriptionLabel.setText("Select types of reported problems:");
+
+ field = createComposite(composite, 0, 0);
+ sourceAuditButton = new Button(field, SWT.CHECK);
+ sourceAuditButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_RESOURCE));
+ sourceAuditButton
+ .setText("Check source code for non externalizated Strings");
+
+ field = createComposite(composite, 0, 0);
+ rbAuditButton = new Button(field, SWT.CHECK);
+ rbAuditButton
+ .setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
+ rbAuditButton
+ .setText("Check ResourceBundles on the following problems:");
+ rbAuditButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ setRBAudits();
+ }
+ });
+
+ field = createComposite(composite, INDENT, 0);
+ checkMissingValueButton = new Button(field, SWT.CHECK);
+ checkMissingValueButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
+ checkMissingValueButton.setText("Missing translation for a key");
+
+ field = createComposite(composite, INDENT, 0);
+ checkSameValueButton = new Button(field, SWT.CHECK);
+ checkSameValueButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
+ checkSameValueButton
+ .setText("Same translations for one key in diffrent languages");
+
+ field = createComposite(composite, INDENT, 0);
+ checkMissingLanguageButton = new Button(field, SWT.CHECK);
+ checkMissingLanguageButton.setSelection(prefs
+ .getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
+ checkMissingLanguageButton
+ .setText("Missing languages in a ResourceBundle");
+
+ setRBAudits();
+
+ composite.pack();
+
+ return composite;
+ }
+
+ @Override
+ protected void performDefaults() {
+ IPreferenceStore prefs = getPreferenceStore();
+
+ sourceAuditButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE));
+ rbAuditButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_RB));
+ checkMissingValueButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
+ checkSameValueButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
+ checkMissingLanguageButton.setSelection(prefs
+ .getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
+ }
+
+ @Override
+ public boolean performOk() {
+ IPreferenceStore prefs = getPreferenceStore();
+
+ prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE,
+ sourceAuditButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY,
+ checkMissingValueButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE,
+ checkSameValueButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE,
+ checkMissingLanguageButton.getSelection());
+
+ return super.performOk();
+ }
+
+ private Composite createComposite(Composite parent, int marginWidth,
+ int marginHeight) {
+ Composite composite = new Composite(parent, SWT.NONE);
+
+ GridLayout indentLayout = new GridLayout(1, false);
+ indentLayout.marginWidth = marginWidth;
+ indentLayout.marginHeight = marginHeight;
+ indentLayout.verticalSpacing = 0;
+ composite.setLayout(indentLayout);
+
+ return composite;
+ }
+
+ protected void setRBAudits() {
+ boolean selected = rbAuditButton.getSelection();
+ checkMissingValueButton.setEnabled(selected);
+ checkSameValueButton.setEnabled(selected);
+ checkMissingLanguageButton.setEnabled(selected);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java
new file mode 100644
index 00000000..e974c241
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - moved SWT code to FilePreferencePage
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.preferences;
+
+
+public class CheckItem {
+ boolean checked;
+ String name;
+
+ public CheckItem(String item, boolean checked) {
+ this.name = item;
+ this.checked = checked;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getChecked() {
+ return checked;
+ }
+
+ public 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
new file mode 100644
index 00000000..e1633cd8
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java
@@ -0,0 +1,227 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.preferences;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreatePatternDialoge;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class FilePreferencePage extends PreferencePage implements
+ IWorkbenchPreferencePage {
+
+ private Table table;
+ protected Object dialoge;
+
+ private Button editPatternButton;
+ private Button removePatternButton;
+
+ @Override
+ public void init(IWorkbench workbench) {
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ IPreferenceStore prefs = getPreferenceStore();
+ Composite composite = new Composite(parent, SWT.SHADOW_OUT);
+
+ composite.setLayout(new GridLayout(2, false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+
+ Label descriptionLabel = new Label(composite, SWT.WRAP);
+ GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false);
+ descriptionData.horizontalSpan = 2;
+ descriptionLabel.setLayoutData(descriptionData);
+ descriptionLabel
+ .setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files");
+
+ table = new Table(composite, SWT.SINGLE | SWT.BORDER
+ | SWT.FULL_SELECTION | SWT.CHECK);
+ GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
+ table.setLayoutData(data);
+
+ table.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0) {
+ editPatternButton.setEnabled(true);
+ removePatternButton.setEnabled(true);
+ } else {
+ editPatternButton.setEnabled(false);
+ removePatternButton.setEnabled(false);
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+
+ List<CheckItem> patternItems = TapiJIPreferences
+ .getNonRbPatternAsList();
+ for (CheckItem s : patternItems) {
+ 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]));
+ }
+ }
+
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+
+ composite.pack();
+
+ return composite;
+ }
+
+ @Override
+ protected void performDefaults() {
+ IPreferenceStore prefs = getPreferenceStore();
+
+ table.removeAll();
+
+ List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs
+ .getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
+ for (CheckItem s : patterns) {
+ 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()));
+ }
+
+ 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
new file mode 100644
index 00000000..b5f7d7ca
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.preferences;
+
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class TapiHomePreferencePage extends PreferencePage implements
+ IWorkbenchPreferencePage {
+
+ @Override
+ public void init(IWorkbench workbench) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(1, true));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ Label description = new Label(composite, SWT.WRAP);
+ description.setText("See sub-pages for settings.");
+
+ return parent;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java
new file mode 100644
index 00000000..95e4b264
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.preferences;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
+import org.eclipse.jface.preference.IPreferenceStore;
+
+public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer {
+
+ public TapiJIPreferenceInitializer() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
+
+ // ResourceBundle-Settings
+ List<CheckItem> patterns = new LinkedList<CheckItem>();
+ patterns.add(new CheckItem("^(.)*/build\\.properties", true));
+ patterns.add(new CheckItem("^(.)*/config\\.properties", true));
+ patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true));
+ prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN,
+ TapiJIPreferences.convertListToString(patterns));
+
+ // Builder
+ prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
+ prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..e9506c6d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java
@@ -0,0 +1,124 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.preferences;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.eclipse.babel.core.configuration.IConfiguration;
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.util.IPropertyChangeListener;
+
+public class TapiJIPreferences implements IConfiguration {
+
+ public static final String AUDIT_SAME_VALUE = "auditSameValue";
+ public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue";
+ public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage";
+ public static final String AUDIT_RB = "auditResourceBundle";
+ public static final String AUDIT_RESOURCE = "auditResource";
+
+ public static final String NON_RB_PATTERN = "NoRBPattern";
+
+ private static final IPreferenceStore PREF = Activator.getDefault()
+ .getPreferenceStore();
+
+ private static final String DELIMITER = ";";
+ private static final String ATTRIBUTE_DELIMITER = ":";
+
+ @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));
+ }
+ 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
new file mode 100644
index 00000000..1ef75780
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java
@@ -0,0 +1,201 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.quickfix;
+
+import org.eclipse.babel.editor.wizards.IResourceBundleWizard;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.wizards.IWizardDescriptor;
+
+public class CreateResourceBundle implements IMarkerResolution2 {
+
+ private IResource resource;
+ private int start;
+ private int end;
+ private String key;
+ private boolean jsfContext;
+ private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
+
+ public CreateResourceBundle(String key, IResource resource, int start,
+ int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
+ this.jsfContext = jsfContext;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Create Resource-Bundle '" + key + "'";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ runAction();
+ }
+
+ protected void runAction() {
+ // First see if this is a "new wizard".
+ IWizardDescriptor descriptor = PlatformUI.getWorkbench()
+ .getNewWizardRegistry().findWizard(newBunldeWizard);
+ // If not check if it is an "import wizard".
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
+ if (!(wizard instanceof IResourceBundleWizard)) {
+ return;
+ }
+
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
+
+ rbw.setBundleId(rbName);
+
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
+
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
+
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+
+ rbw.setDefaultPath(pathName);
+
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ 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
new file mode 100644
index 00000000..f93a94e0
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
@@ -0,0 +1,103 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - modified CreateResourceBundleEntryDialog instantiation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class CreateResourceBundleEntry implements IMarkerResolution2 {
+
+ private String key;
+ private String bundleId;
+
+ public CreateResourceBundleEntry(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new Resource-Bundle entry for the property-key '"
+ + key + "'";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Create Resource-Bundle entry for '" + key + "'";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(key != null ? key : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(bundleId);
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ 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
new file mode 100644
index 00000000..ea69e187
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.quickfix;
+
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.progress.IProgressService;
+
+public class IncludeResource implements IMarkerResolution2 {
+
+ private String bundleName;
+ private Set<IResource> bundleResources;
+
+ public IncludeResource(String bundleName, Set<IResource> bundleResources) {
+ this.bundleResources = bundleResources;
+ this.bundleName = bundleName;
+ }
+
+ @Override
+ public String getDescription() {
+ return "The Resource-Bundle with id '"
+ + bundleName
+ + "' has been "
+ + "excluded from Internationalization. Based on this fact, no internationalization "
+ + "supoort is provided for this Resource-Bundle. Performing this action, internationalization "
+ + "support for '" + bundleName + "' will be enabled";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Include excluded Resource-Bundle '" + bundleName + "'";
+ }
+
+ @Override
+ public void run(final IMarker marker) {
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(marker.getResource().getProject());
+ pm.beginTask("Including resources to Internationalization",
+ bundleResources.size());
+ for (IResource resource : bundleResources) {
+ manager.includeResource(resource, pm);
+ pm.worked(1);
+ }
+ pm.done();
+ }
+ });
+ } catch (Exception e) {
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java
new file mode 100644
index 00000000..151a8546
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java
@@ -0,0 +1,190 @@
+package org.eclipse.babel.tapiji.tools.core.ui.utils;
+
+import java.util.Iterator;
+
+import org.eclipse.babel.editor.IMessagesEditor;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
+import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
+
+public class EditorUtils {
+
+ /** Marker constants **/
+ public static final String MARKER_ID = Activator.PLUGIN_ID
+ + ".StringLiteralAuditMarker";
+ public static final String RB_MARKER_ID = Activator.PLUGIN_ID
+ + ".ResourceBundleAuditMarker";
+
+ /** Editor ids **/
+ public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
+
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
+ String editor) {
+ // open the rb-editor for this file type
+ try {
+ return IDE.openEditor(page, file, editor);
+ } catch (PartInitException e) {
+ Logger.logError(e);
+ }
+ return null;
+ }
+
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile file,
+ String editor, String key) {
+ // open the rb-editor for this file type and selects given msg key
+ IEditorPart part = openEditor(page, file, editor);
+ if (part instanceof IMessagesEditor) {
+ IMessagesEditor msgEditor = (IMessagesEditor) part;
+ msgEditor.setSelectedKey(key);
+ }
+ return part;
+ }
+
+ public static void updateMarker(IMarker marker) {
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
+
+ AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) getAnnotationModel(marker);
+ IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
+
+ try {
+ model.updateMarker(doc, marker, getCurPosition(marker, model));
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public static IAnnotationModel getAnnotationModel(IMarker marker) {
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
+
+ return JavaUI.getDocumentProvider().getAnnotationModel(input);
+ }
+
+ private static Position getCurPosition(IMarker marker,
+ IAnnotationModel model) {
+ Iterator iter = model.getAnnotationIterator();
+ Logger.logInfo("Updates Position!");
+ while (iter.hasNext()) {
+ Object curr = iter.next();
+ if (curr instanceof SimpleMarkerAnnotation) {
+ SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
+ if (marker.equals(annot.getMarker())) {
+ return model.getPosition(annot);
+ }
+ }
+ }
+ return null;
+ }
+
+ public static boolean deleteAuditMarkersForResource(IResource resource) {
+ try {
+ if (resource != null && resource.exists()) {
+ resource.deleteMarkers(MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ deleteAllAuditRBMarkersFromRB(resource);
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
+ return true;
+ }
+
+ /*
+ * Delete all RB_MARKER from the hole resourcebundle
+ */
+ private static boolean deleteAllAuditRBMarkersFromRB(IResource resource)
+ throws CoreException {
+ // if (resource.findMarkers(RB_MARKER_ID, false,
+ // IResource.DEPTH_INFINITE).length > 0)
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ String rbId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) resource);
+ if (rbId == null) {
+ return true; // file in no resourcebundle
+ }
+
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(resource.getProject());
+ for (IResource r : rbmanager.getResourceBundles(rbId)) {
+ r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
+ }
+ }
+ return true;
+ }
+
+ public static void reportToMarker(String string, ILocation problem,
+ int cause, String key, ILocation data, String context) {
+ try {
+ IMarker marker = problem.getFile().createMarker(MARKER_ID);
+ marker.setAttribute(IMarker.MESSAGE, string);
+ marker.setAttribute(IMarker.CHAR_START, problem.getStartPos());
+ marker.setAttribute(IMarker.CHAR_END, problem.getEndPos());
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute("cause", cause);
+ marker.setAttribute("key", key);
+ marker.setAttribute("context", context);
+ if (data != null) {
+ marker.setAttribute("bundleName", data.getLiteral());
+ marker.setAttribute("bundleStart", data.getStartPos());
+ marker.setAttribute("bundleEnd", data.getEndPos());
+ }
+
+ // TODO: init attributes
+ marker.setAttribute("stringLiteral", string);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ Logger.logInfo(string);
+ }
+
+ public static void reportToRBMarker(String string, ILocation problem,
+ int cause, String key, String problemPartnerFile, ILocation data,
+ String context) {
+ try {
+ if (!problem.getFile().exists()) {
+ return;
+ }
+ IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
+ marker.setAttribute(IMarker.MESSAGE, string);
+ marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); // TODO
+ // better-dirty
+ // implementation
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute("cause", cause);
+ marker.setAttribute("key", key);
+ marker.setAttribute("context", context);
+ if (data != null) {
+ marker.setAttribute("language", data.getLiteral());
+ marker.setAttribute("bundleLine", data.getStartPos());
+ }
+ marker.setAttribute("stringLiteral", string);
+ marker.setAttribute("problemPartner", problemPartnerFile);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ Logger.logInfo(string);
+ }
+
+}
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
new file mode 100644
index 00000000..fd0942a5
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java
@@ -0,0 +1,102 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.utils;
+
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+
+public class FontUtils {
+
+ /**
+ * Gets a system color.
+ *
+ * @param colorId
+ * SWT constant
+ * @return system color
+ */
+ public static Color getSystemColor(int colorId) {
+ return Activator.getDefault().getWorkbench().getDisplay()
+ .getSystemColor(colorId);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style (size is unaffected).
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style) {
+ // TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style and relative size.
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style, int relSize) {
+ // TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
+ }
+
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(int style) {
+ return createFont(style, 0);
+ }
+
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(int style, int relSize) {
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..52e56608
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java
@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.utils;
+
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Utility methods related to application UI.
+ *
+ * @author Pascal Essiembre ([email protected])
+ * @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $
+ */
+public final class ImageUtils {
+
+ /** Name of resource bundle image. */
+ public static final String IMAGE_RESOURCE_BUNDLE = "icons/resourcebundle.gif"; //$NON-NLS-1$
+ /** Name of properties file image. */
+ public static final String IMAGE_PROPERTIES_FILE = "icons/propertiesfile.gif"; //$NON-NLS-1$
+ /** Name of properties file entry image */
+ public static final String IMAGE_PROPERTIES_FILE_ENTRY = "icons/key.gif";
+ /** Name of new properties file image. */
+ public static final String IMAGE_NEW_PROPERTIES_FILE = "icons/newpropertiesfile.gif"; //$NON-NLS-1$
+ /** Name of hierarchical layout image. */
+ public static final String IMAGE_LAYOUT_HIERARCHICAL = "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
+ /** Name of flat layout image. */
+ public static final String IMAGE_LAYOUT_FLAT = "icons/flatLayout.gif"; //$NON-NLS-1$
+ public static final String IMAGE_INCOMPLETE_ENTRIES = "icons/incomplete.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_ON = "icons/int.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_OFF = "icons/exclude.png"; //$NON-NLS-1$
+ public static final String ICON_RESOURCE = "icons/Resource16_small.png";
+ public static final String ICON_RESOURCE_INCOMPLETE = "icons/Resource16_warning_small.png";
+
+ /** Image registry. */
+ private static final ImageRegistry imageRegistry = new ImageRegistry();
+
+ /**
+ * Constructor.
+ */
+ private ImageUtils() {
+ super();
+ }
+
+ /**
+ * Gets an image.
+ *
+ * @param imageName
+ * image name
+ * @return image
+ */
+ public static Image getImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..a3889000
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java
@@ -0,0 +1,137 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.utils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringBufferInputStream;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class LanguageUtils {
+ private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY;
+
+ private static IFile createFile(IContainer container, String fileName,
+ IProgressMonitor monitor) throws CoreException, IOException {
+ if (!container.exists()) {
+ if (container instanceof IFolder) {
+ ((IFolder) container).create(false, false, monitor);
+ }
+ }
+
+ IFile file = container.getFile(new Path(fileName));
+ if (!file.exists()) {
+ InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
+ file.create(s, true, monitor);
+ s.close();
+ }
+
+ return file;
+ }
+
+ /**
+ * Checks if ResourceBundle provides a given locale. If the locale is not
+ * provided, creates a new properties-file with the ResourceBundle-basename
+ * and the index of the given locale.
+ *
+ * @param project
+ * @param rbId
+ * @param locale
+ */
+ public static void addLanguageToResourceBundle(IProject project,
+ final String rbId, final Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
+
+ if (rbManager.getProvidedLocales(rbId).contains(locale)) {
+ return;
+ }
+
+ final IResource file = rbManager.getRandomFile(rbId);
+ final IContainer c = ResourceUtils.getCorrespondingFolders(
+ file.getParent(), project);
+
+ new Job("create new propertfile") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ String newFilename = ResourceBundleManager
+ .getResourceBundleName(file);
+ if (locale.getLanguage() != null
+ && !locale.getLanguage().equalsIgnoreCase(
+ ResourceBundleManager.defaultLocaleTag)
+ && !locale.getLanguage().equals("")) {
+ newFilename += "_" + locale.getLanguage();
+ }
+ if (locale.getCountry() != null
+ && !locale.getCountry().equals("")) {
+ newFilename += "_" + locale.getCountry();
+ }
+ if (locale.getVariant() != null
+ && !locale.getCountry().equals("")) {
+ newFilename += "_" + locale.getVariant();
+ }
+ newFilename += ".properties";
+
+ createFile(c, newFilename, monitor);
+ } catch (CoreException e) {
+ Logger.logError(
+ "File for locale "
+ + locale
+ + " could not be created in ResourceBundle "
+ + rbId, e);
+ } catch (IOException e) {
+ Logger.logError(
+ "File for locale "
+ + locale
+ + " could not be created in ResourceBundle "
+ + rbId, e);
+ }
+ monitor.done();
+ return Status.OK_STATUS;
+ }
+ }.schedule();
+ }
+
+ /**
+ * Adds new properties-files for a given locale to all ResourceBundles of a
+ * project. If a ResourceBundle already contains the language, happens
+ * nothing.
+ *
+ * @param project
+ * @param locale
+ */
+ public static void addLanguageToProject(IProject project, Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager
+ .getManager(project);
+
+ // Audit if all resourecbundles provide this locale. if not - add new
+ // file
+ for (String rbId : rbManager.getResourceBundleIdentifiers()) {
+ addLanguageToResourceBundle(project, rbId, locale);
+ }
+ }
+
+}
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
new file mode 100644
index 00000000..5a104dd3
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java
@@ -0,0 +1,50 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.utils;
+
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+
+public class LocaleUtils {
+
+ public static Locale getLocaleByDisplayName(Set<Locale> locales,
+ String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (name.equals(displayName)
+ || (name.trim().length() == 0 && displayName
+ .equals(ResourceBundleManager.defaultLocaleTag))) {
+ return l;
+ }
+ }
+
+ return null;
+ }
+
+ public static boolean containsLocaleByDisplayName(Set<Locale> locales,
+ String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName();
+ if (name.equals(displayName)
+ || (name.trim().length() == 0 && displayName
+ .equals(ResourceBundleManager.defaultLocaleTag))) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..dd0b1591
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java
@@ -0,0 +1,249 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.utils;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.preferences.CheckItem;
+import org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiJIPreferences;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.preference.IPreferenceStore;
+
+/**
+ *
+ * @author mgasser
+ *
+ */
+public class RBFileUtils extends Action {
+ public static final String PROPERTIES_EXT = "properties";
+
+ /**
+ * Returns true if a file is a ResourceBundle-file
+ */
+ public static boolean isResourceBundleFile(IResource file) {
+ boolean isValied = false;
+
+ if (file != null && file instanceof IFile && !file.isDerived()
+ && file.getFileExtension() != null
+ && file.getFileExtension().equalsIgnoreCase("properties")) {
+ isValied = true;
+
+ // Check if file is not in the blacklist
+ IPreferenceStore pref = null;
+ if (Activator.getDefault() != null) {
+ pref = Activator.getDefault().getPreferenceStore();
+ }
+
+ if (pref != null) {
+ List<CheckItem> list = TapiJIPreferences
+ .getNonRbPatternAsList();
+ for (CheckItem item : list) {
+ if (item.getChecked()
+ && file.getFullPath().toString()
+ .matches(item.getName())) {
+ isValied = false;
+
+ // if properties-file is not RB-file and has
+ // ResouceBundleMarker, deletes all ResouceBundleMarker
+ // of the file
+ if (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 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();
+ }
+
+ /**
+ * 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 the locale of a given properties-file
+ */
+ public static Locale getLocale(IFile file) {
+ String localeID = file.getName();
+ localeID = localeID.substring(0,
+ localeID.length() - "properties".length() - 1);
+ String baseBundleName = ResourceBundleManager
+ .getResourceBundleName(file);
+
+ Locale locale;
+ if (localeID.length() == baseBundleName.length()) {
+ locale = null; // Default locale
+ } else {
+ localeID = localeID.substring(baseBundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
+ break;
+ default:
+ locale = new Locale("");
+ break;
+ }
+ }
+ return locale;
+ }
+
+ /**
+ * @return number of ResourceBundles in the subtree
+ */
+ public static int countRecursiveResourceBundle(IContainer container) {
+ return getSubResourceBundle(container).size();
+ }
+
+ private static List<String> getSubResourceBundle(IContainer container) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(container.getProject());
+
+ String conatinerId = container.getFullPath().toString();
+ List<String> subResourceBundles = new ArrayList<String>();
+
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ for (IResource r : rbmanager.getResourceBundles(rbId)) {
+ if (r.getFullPath().toString().contains(conatinerId)
+ && (!subResourceBundles.contains(rbId))) {
+ subResourceBundles.add(rbId);
+ }
+ }
+ }
+ return subResourceBundles;
+ }
+
+}
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
new file mode 100644
index 00000000..61217032
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java
@@ -0,0 +1,120 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IPath;
+
+public class ResourceUtils {
+
+ private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*";
+ private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
+
+ public static boolean isValidResourceKey(String key) {
+ boolean isValid = false;
+
+ if (key != null && key.trim().length() > 0) {
+ isValid = key.matches(REGEXP_RESOURCE_KEY);
+ }
+
+ return isValid;
+ }
+
+ public static String deriveNonExistingRBName(String nameProposal,
+ ResourceBundleManager manager) {
+ // Adapt the proposal to the requirements for Resource-Bundle names
+ nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME,
+ "");
+
+ int i = 0;
+ do {
+ if (manager.getResourceBundleIdentifiers().contains(nameProposal)
+ || nameProposal.length() == 0) {
+ nameProposal = nameProposal + (++i);
+ } else {
+ break;
+ }
+ } while (true);
+
+ return nameProposal;
+ }
+
+ public static boolean isJavaCompUnit(IResource res) {
+ boolean result = false;
+
+ if (res.getType() == IResource.FILE && !res.isDerived()
+ && res.getFileExtension().equalsIgnoreCase("java")) {
+ result = true;
+ }
+
+ return result;
+ }
+
+ public static boolean isJSPResource(IResource res) {
+ boolean result = false;
+
+ if (res.getType() == IResource.FILE
+ && !res.isDerived()
+ && (res.getFileExtension().equalsIgnoreCase("jsp") || res
+ .getFileExtension().equalsIgnoreCase("xhtml"))) {
+ result = true;
+ }
+
+ return result;
+ }
+
+ /**
+ *
+ * @param baseFolder
+ * @param targetProjects
+ * Projects with a same structure
+ * @return List of
+ */
+ public static List<IContainer> getCorrespondingFolders(
+ IContainer baseFolder, List<IProject> targetProjects) {
+ List<IContainer> correspondingFolder = new ArrayList<IContainer>();
+
+ for (IProject p : targetProjects) {
+ IContainer c = getCorrespondingFolders(baseFolder, p);
+ if (c.exists()) {
+ correspondingFolder.add(c);
+ }
+ }
+
+ return correspondingFolder;
+ }
+
+ /**
+ *
+ * @param baseFolder
+ * @param targetProject
+ * @return a Container with the corresponding path as the baseFolder. The
+ * Container doesn't must exist.
+ */
+ public static IContainer getCorrespondingFolders(IContainer baseFolder,
+ IProject targetProject) {
+ IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(
+ baseFolder.getProject().getFullPath());
+
+ if (!relativ_folder.isEmpty()) {
+ return targetProject.getFolder(relativ_folder);
+ } else {
+ return targetProject;
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.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
new file mode 100644
index 00000000..24c66b0d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
@@ -0,0 +1,559 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.views.messagesview;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.Scale;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.IViewSite;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.part.ViewPart;
+import org.eclipse.ui.progress.UIJob;
+
+public class MessagesView extends ViewPart implements
+ 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());
+
+ }
+ 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;
+ }
+
+ 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) {
+ }
+ }
+ 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();
+ }
+
+ protected void redrawTreeViewer() {
+ parent.setRedraw(false);
+ treeViewer.dispose();
+ try {
+ initMessagesTree(parent);
+ makeActions();
+ contributeToActionBars();
+ hookContextMenu();
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ parent.setRedraw(true);
+ parent.layout(true);
+ treeViewer.layout(true);
+ refreshSearchbarState();
+ }
+
+ /*** 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");
+ }
+ langAction.setChecked(visibleLocales.contains(locale));
+ visibleLocaleActions.add(langAction);
+ }
+ }
+
+ 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);
+ }
+
+ @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) {
+ }
+ }
+ 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();
+ }
+ } 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) {
+ }
+ }
+}
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
new file mode 100644
index 00000000..6fafc83e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java
@@ -0,0 +1,217 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.views.messagesview;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+
+public class MessagesViewState {
+
+ private static final String TAG_VISIBLE_LOCALES = "visible_locales";
+ private static final String TAG_LOCALE = "locale";
+ private static final String TAG_LOCALE_LANGUAGE = "language";
+ private static final String TAG_LOCALE_COUNTRY = "country";
+ private static final String TAG_LOCALE_VARIANT = "variant";
+ private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
+ private static final String TAG_MATCHING_PRECISION = "matching_precision";
+ private static final String TAG_SELECTED_PROJECT = "selected_project";
+ private static final String TAG_SELECTED_BUNDLE = "selected_bundle";
+ private static final String TAG_ENABLED = "enabled";
+ private static final String TAG_VALUE = "value";
+ private static final String TAG_SEARCH_STRING = "search_string";
+ private static final String TAG_EDITABLE = "editable";
+
+ private List<Locale> visibleLocales;
+ private SortInfo sortings;
+ private boolean fuzzyMatchingEnabled;
+ private float matchingPrecision = .75f;
+ private String selectedProjectName;
+ private String selectedBundleId;
+ private String searchString;
+ private boolean editable;
+
+ public void saveState(IMemento memento) {
+ try {
+ if (memento == null)
+ return;
+
+ if (visibleLocales != null) {
+ IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES);
+ for (Locale loc : visibleLocales) {
+ IMemento memLoc = memVL.createChild(TAG_LOCALE);
+ memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage());
+ memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry());
+ memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant());
+ }
+ }
+
+ if (sortings != null) {
+ sortings.saveState(memento);
+ }
+
+ IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
+ memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
+
+ IMemento memMatchingPrec = memento
+ .createChild(TAG_MATCHING_PRECISION);
+ memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
+
+ selectedProjectName = selectedProjectName != null ? selectedProjectName
+ : "";
+ selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
+
+ IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
+ memSP.putString(TAG_VALUE, selectedProjectName);
+
+ IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
+ memSB.putString(TAG_VALUE, selectedBundleId);
+
+ IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
+ memSStr.putString(TAG_VALUE, searchString);
+
+ IMemento memEditable = memento.createChild(TAG_EDITABLE);
+ memEditable.putBoolean(TAG_ENABLED, editable);
+ } catch (Exception e) {
+
+ }
+ }
+
+ public void init(IMemento memento) {
+ if (memento == null)
+ return;
+
+ if (memento.getChild(TAG_VISIBLE_LOCALES) != null) {
+ if (visibleLocales == null)
+ visibleLocales = new ArrayList<Locale>();
+ IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES)
+ .getChildren(TAG_LOCALE);
+ for (IMemento mLocale : mLocales) {
+ if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null
+ && mLocale.getString(TAG_LOCALE_COUNTRY) == null
+ && mLocale.getString(TAG_LOCALE_VARIANT) == null) {
+ continue;
+ }
+ Locale newLocale = new Locale(
+ mLocale.getString(TAG_LOCALE_LANGUAGE),
+ mLocale.getString(TAG_LOCALE_COUNTRY),
+ mLocale.getString(TAG_LOCALE_VARIANT));
+ if (!this.visibleLocales.contains(newLocale)) {
+ visibleLocales.add(newLocale);
+ }
+ }
+ }
+
+ if (sortings == null)
+ sortings = new SortInfo();
+ sortings.init(memento);
+
+ IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
+ if (mFuzzyMatching != null)
+ fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
+
+ IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
+ if (mMP != null)
+ matchingPrecision = mMP.getFloat(TAG_VALUE);
+
+ IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT);
+ if (mSelProj != null)
+ selectedProjectName = mSelProj.getString(TAG_VALUE);
+
+ IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE);
+ if (mSelBundle != null)
+ selectedBundleId = mSelBundle.getString(TAG_VALUE);
+
+ IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
+ if (mSStr != null)
+ searchString = mSStr.getString(TAG_VALUE);
+
+ IMemento mEditable = memento.getChild(TAG_EDITABLE);
+ if (mEditable != null)
+ editable = mEditable.getBoolean(TAG_ENABLED);
+ }
+
+ public MessagesViewState(List<Locale> visibleLocales, SortInfo sortings,
+ boolean fuzzyMatchingEnabled, String selectedBundleId) {
+ super();
+ this.visibleLocales = visibleLocales;
+ this.sortings = sortings;
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ this.selectedBundleId = selectedBundleId;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public void setVisibleLocales(List<Locale> visibleLocales) {
+ this.visibleLocales = visibleLocales;
+ }
+
+ public SortInfo getSortings() {
+ return sortings;
+ }
+
+ public void setSortings(SortInfo sortings) {
+ this.sortings = sortings;
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ }
+
+ public void setSelectedBundleId(String selectedBundleId) {
+ this.selectedBundleId = selectedBundleId;
+ }
+
+ public void setSelectedProjectName(String selectedProjectName) {
+ this.selectedProjectName = selectedProjectName;
+ }
+
+ public void setSearchString(String searchString) {
+ this.searchString = searchString;
+ }
+
+ public String getSelectedBundleId() {
+ return selectedBundleId;
+ }
+
+ public String getSelectedProjectName() {
+ return selectedProjectName;
+ }
+
+ public String getSearchString() {
+ return searchString;
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ public void setMatchingPrecision(float value) {
+ this.matchingPrecision = value;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..95c37640
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
@@ -0,0 +1,124 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview;
+
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+public class ResourceBundleEntry extends ContributionItem implements
+ ISelectionChangedListener {
+
+ private PropertyKeySelectionTree parentView;
+ private ISelection selection;
+ private boolean legalSelection = false;
+
+ // Menu-Items
+ private MenuItem addItem;
+ private MenuItem editItem;
+ private MenuItem removeItem;
+
+ public ResourceBundleEntry() {
+ }
+
+ public ResourceBundleEntry(PropertyKeySelectionTree view,
+ ISelection selection) {
+ this.selection = selection;
+ this.legalSelection = !selection.isEmpty();
+ this.parentView = view;
+ parentView.addSelectionChangedListener(this);
+ }
+
+ @Override
+ public void fill(Menu menu, int index) {
+
+ // MenuItem for adding a new entry
+ addItem = new MenuItem(menu, SWT.NONE, index);
+ addItem.setText("Add ...");
+ addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
+ addItem.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.addNewItem(selection);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+
+ if ((parentView == null && legalSelection) || parentView != null) {
+ // MenuItem for editing the currently selected entry
+ editItem = new MenuItem(menu, SWT.NONE, index + 1);
+ editItem.setText("Edit");
+ editItem.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.editSelectedItem();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+
+ // MenuItem for deleting the currently selected entry
+ removeItem = new MenuItem(menu, SWT.NONE, index + 2);
+ removeItem.setText("Remove");
+ removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
+ .createImage());
+ removeItem.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.deleteSelectedItems();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+ enableMenuItems();
+ }
+ }
+
+ protected void enableMenuItems() {
+ try {
+ editItem.setEnabled(legalSelection);
+ removeItem.setEnabled(legalSelection);
+ } catch (Exception e) {
+ // silent catch
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ legalSelection = !event.getSelection().isEmpty();
+ // enableMenuItems ();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java
new file mode 100644
index 00000000..b7e9ec0a
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java
@@ -0,0 +1,65 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.views.messagesview;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+
+public class SortInfo {
+
+ public static final String TAG_SORT_INFO = "sort_info";
+ public static final String TAG_COLUMN_INDEX = "col_idx";
+ public static final String TAG_ORDER = "order";
+
+ private int colIdx;
+ private boolean DESC;
+ private List<Locale> visibleLocales;
+
+ public void setDESC(boolean dESC) {
+ DESC = dESC;
+ }
+
+ public boolean isDESC() {
+ return DESC;
+ }
+
+ public void setColIdx(int colIdx) {
+ this.colIdx = colIdx;
+ }
+
+ public int getColIdx() {
+ return colIdx;
+ }
+
+ public void setVisibleLocales(List<Locale> visibleLocales) {
+ this.visibleLocales = visibleLocales;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public void saveState(IMemento memento) {
+ IMemento mCI = memento.createChild(TAG_SORT_INFO);
+ mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
+ mCI.putBoolean(TAG_ORDER, DESC);
+ }
+
+ public void init(IMemento memento) {
+ IMemento mCI = memento.getChild(TAG_SORT_INFO);
+ if (mCI == null)
+ return;
+ colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
+ DESC = mCI.getBoolean(TAG_ORDER);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.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
new file mode 100644
index 00000000..1d59cad0
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
@@ -0,0 +1,180 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Matthias Lettmayer - added functionality to dnd a tree with children (fixed issue 5)
+ * Alexej Strelzow - dnd bug fixes
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.factory.MessageFactory;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.internal.MessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.core.message.tree.IAbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.TreeItem;
+
+public class KeyTreeItemDropTarget extends DropTargetAdapter {
+ private final TreeViewer target;
+
+ public KeyTreeItemDropTarget(TreeViewer viewer) {
+ super();
+ this.target = viewer;
+ }
+
+ public void dragEnter(DropTargetEvent event) {
+ // if (((DropTarget)event.getSource()).getControl() instanceof Tree)
+ // event.detail = DND.DROP_MOVE;
+ }
+
+ private void addBundleEntries(final String keyPrefix, // new prefix
+ final IKeyTreeNode children, final IMessagesBundleGroup bundleGroup) {
+
+ try {
+ String oldKey = children.getMessageKey();
+ String key = children.getName();
+ String newKey = keyPrefix + "." + key;
+
+ IMessage[] messages = bundleGroup.getMessages(oldKey);
+ for (IMessage message : messages) {
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(message.getLocale());
+ IMessage m = MessageFactory.createMessage(newKey,
+ message.getLocale());
+ m.setText(message.getValue());
+ m.setComment(message.getComment());
+ messagesBundle.addMessage(m);
+ }
+
+ if (messages.length == 0) {
+ bundleGroup.addMessages(newKey);
+ }
+
+ for (IKeyTreeNode childs : children.getChildren()) {
+ addBundleEntries(keyPrefix + "." + key, childs, bundleGroup);
+ }
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+
+ }
+
+ private void remBundleEntries(IKeyTreeNode children,
+ IMessagesBundleGroup group) {
+ String key = children.getMessageKey();
+
+ for (IKeyTreeNode childs : children.getChildren()) {
+ remBundleEntries(childs, group);
+ }
+
+ group.removeMessagesAddParentKey(key);
+ }
+
+ public void drop(final DropTargetEvent event) {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ try {
+
+ if (TextTransfer.getInstance().isSupportedType(
+ event.currentDataType)) {
+ String newKeyPrefix = "";
+
+ if (event.item instanceof TreeItem
+ && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item)
+ .getData();
+ newKeyPrefix = targetTreeNode.getMessageKey();
+ }
+
+ String message = (String) event.data;
+ String oldKey = message.replaceAll("\"", "");
+
+ String[] keyArr = (oldKey).split("\\.");
+ String key = keyArr[keyArr.length - 1];
+
+ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target
+ .getContentProvider();
+ IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target
+ .getInput();
+
+ // key gets dropped into it's parent node
+ if (oldKey.equals(newKeyPrefix + "." + key))
+ return; // TODO: give user feedback
+
+ // prevent cycle loop if key gets dropped into its child
+ // node
+ if (newKeyPrefix.contains(oldKey))
+ return; // TODO: give user feedback
+
+ // source node already exists in target
+ IKeyTreeNode targetTreeNode = keyTree
+ .getChild(newKeyPrefix);
+ for (IKeyTreeNode targetChild : targetTreeNode
+ .getChildren()) {
+ if (targetChild.getName().equals(key))
+ return; // TODO: give user feedback
+ }
+
+ IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey);
+
+ IMessagesBundleGroup bundleGroup = contentProvider
+ .getBundle();
+
+ DirtyHack.setFireEnabled(false);
+ DirtyHack.setEditorModificationEnabled(false); // editor
+ // won't
+ // get
+ // dirty
+
+ // add new bundle entries of source node + all children
+ addBundleEntries(newKeyPrefix, sourceTreeNode,
+ bundleGroup);
+
+ // if drag & drop is move event, delete source entry +
+ // it's children
+ if (event.detail == DND.DROP_MOVE) {
+ remBundleEntries(sourceTreeNode, bundleGroup);
+ }
+
+ // Store changes
+ RBManager manager = RBManager
+ .getInstance(((MessagesBundleGroup) bundleGroup)
+ .getProjectName());
+
+ manager.writeToFile(bundleGroup);
+ manager.fireEditorChanged(); // refresh the View
+
+ target.refresh();
+ } else {
+ event.detail = DND.DROP_NONE;
+ }
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ DirtyHack.setFireEnabled(true);
+ DirtyHack.setEditorModificationEnabled(true);
+ }
+ }
+ });
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
new file mode 100644
index 00000000..cc788a4c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
@@ -0,0 +1,116 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.views.messagesview.dnd;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.swt.dnd.ByteArrayTransfer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.TransferData;
+
+public class KeyTreeItemTransfer extends ByteArrayTransfer {
+
+ private static final String KEY_TREE_ITEM = "keyTreeItem";
+
+ private static final int TYPEID = registerType(KEY_TREE_ITEM);
+
+ private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer();
+
+ public static KeyTreeItemTransfer getInstance() {
+ return transfer;
+ }
+
+ public void javaToNative(Object object, TransferData transferData) {
+ if (!checkType(object) || !isSupportedType(transferData)) {
+ DND.error(DND.ERROR_INVALID_DATA);
+ }
+ IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream oOut = new ObjectOutputStream(out);
+ for (int i = 0, length = terms.length; i < length; i++) {
+ oOut.writeObject(terms[i]);
+ }
+ byte[] buffer = out.toByteArray();
+ oOut.close();
+
+ super.javaToNative(buffer, transferData);
+ } catch (IOException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public Object nativeToJava(TransferData transferData) {
+ if (isSupportedType(transferData)) {
+
+ byte[] buffer;
+ try {
+ buffer = (byte[]) super.nativeToJava(transferData);
+ } catch (Exception e) {
+ Logger.logError(e);
+ buffer = null;
+ }
+ if (buffer == null)
+ return null;
+
+ List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>();
+ try {
+ ByteArrayInputStream in = new ByteArrayInputStream(buffer);
+ ObjectInputStream readIn = new ObjectInputStream(in);
+ // while (readIn.available() > 0) {
+ IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
+ terms.add(newTerm);
+ // }
+ readIn.close();
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ return null;
+ }
+ return terms.toArray(new IKeyTreeNode[terms.size()]);
+ }
+
+ return null;
+ }
+
+ protected String[] getTypeNames() {
+ return new String[] { KEY_TREE_ITEM };
+ }
+
+ protected int[] getTypeIds() {
+ return new int[] { TYPEID };
+ }
+
+ boolean checkType(Object object) {
+ if (object == null || !(object instanceof IKeyTreeNode[])
+ || ((IKeyTreeNode[]) object).length == 0) {
+ return false;
+ }
+ IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object;
+ for (int i = 0; i < myTypes.length; i++) {
+ if (myTypes[i] == null) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ protected boolean validate(Object object) {
+ return checkType(object);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
new file mode 100644
index 00000000..1a770030
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.views.messagesview.dnd;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+
+public class MessagesDragSource implements DragSourceListener {
+
+ private final TreeViewer source;
+ private String bundleId;
+
+ public MessagesDragSource(TreeViewer sourceView, String bundleId) {
+ source = sourceView;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public void dragFinished(DragSourceEvent event) {
+
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent event) {
+ IKeyTreeNode selectionObject = (IKeyTreeNode) ((IStructuredSelection) source
+ .getSelection()).toList().get(0);
+
+ String key = selectionObject.getMessageKey();
+
+ // TODO Solve the problem that its not possible to retrieve the editor
+ // position of the drop event
+
+ // event.data = "(new ResourceBundle(\"" + bundleId +
+ // "\")).getString(\"" + key + "\")";
+ event.data = "\"" + key + "\"";
+ }
+
+ @Override
+ public void dragStart(DragSourceEvent event) {
+ event.doit = !source.getSelection().isEmpty();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
new file mode 100644
index 00000000..9221b9e6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - modified CreateResourceBundleEntryDialog instantiation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
+
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.TreeItem;
+
+public class MessagesDropTarget extends DropTargetAdapter {
+ private final String projectName;
+ private String bundleName;
+
+ public MessagesDropTarget(TreeViewer viewer, String projectName,
+ String bundleName) {
+ super();
+ this.projectName = projectName;
+ this.bundleName = bundleName;
+ }
+
+ public void dragEnter(DropTargetEvent event) {
+ }
+
+ public void drop(DropTargetEvent event) {
+ if (event.detail != DND.DROP_COPY)
+ return;
+
+ if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
+
+ if (event.item instanceof TreeItem
+ && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
+ newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item)
+ .getData()).getMessageKey();
+ }
+
+ String message = (String) event.data;
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
+ + "." + "[Platzhalter]"
+ : "");
+ config.setPreselectedMessage(message);
+ config.setPreselectedBundle(bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+ } else
+ event.detail = DND.DROP_NONE;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java
new file mode 100644
index 00000000..68d47807
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java
@@ -0,0 +1,18 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets;
+
+public class MVTextTransfer {
+
+ private MVTextTransfer() {
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
new file mode 100644
index 00000000..3eec260f
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
@@ -0,0 +1,809 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * 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)
+ * Alexej Strelzow - modified CreateResourceBundleEntryDialog instantiation
+ * - tree expand, Babel integration
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.factory.MessageFactory;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.core.message.tree.IAbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.core.util.FileUtils;
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.SortInfo;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.ExactMatcher;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IElementComparer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.events.TraverseEvent;
+import org.eclipse.swt.events.TraverseListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.ui.IViewSite;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+
+public class PropertyKeySelectionTree extends Composite implements
+ IResourceBundleChangedListener {
+
+ private final int KEY_COLUMN_WEIGHT = 1;
+ private final int LOCALE_COLUMN_WEIGHT = 1;
+
+ private List<Locale> visibleLocales = new ArrayList<Locale>();
+ private boolean editable;
+ private String resourceBundle;
+
+ private IWorkbenchPartSite site;
+ private TreeColumnLayout basicLayout;
+ private TreeViewer treeViewer;
+ private TreeColumn keyColumn;
+ private boolean grouped = true;
+ private boolean fuzzyMatchingEnabled = false;
+ private float matchingPrecision = .75f;
+ private Locale uiLocale = new Locale("en");
+
+ private SortInfo sortInfo;
+
+ private ResKeyTreeContentProvider contentProvider;
+ private ResKeyTreeLabelProvider labelProvider;
+ private TreeType treeType = TreeType.Tree;
+
+ private IMessagesEditorListener editorListener;
+
+ /*** MATCHER ***/
+ ExactMatcher matcher;
+
+ /*** SORTER ***/
+ ValuedKeyTreeItemSorter sorter;
+
+ /*** ACTIONS ***/
+ private Action doubleClickAction;
+
+ /*** LISTENERS ***/
+ private ISelectionChangedListener selectionChangedListener;
+ private String projectName;
+
+ public PropertyKeySelectionTree(IViewSite viewSite,
+ IWorkbenchPartSite site, Composite parent, int style,
+ String projectName, String resources, List<Locale> locales) {
+ super(parent, style);
+ this.site = site;
+ this.resourceBundle = resources;
+ this.projectName = projectName;
+
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ if (locales == null)
+ initVisibleLocales();
+ else
+ this.visibleLocales = locales;
+ }
+
+ constructWidget();
+
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ initTreeViewer();
+ initMatchers();
+ initSorters();
+ treeViewer.expandAll();
+ }
+
+ hookDragAndDrop();
+ registerListeners();
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ unregisterListeners();
+ }
+
+ protected void initSorters() {
+ sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo);
+ treeViewer.setSorter(sorter);
+ }
+
+ public void enableFuzzyMatching(boolean enable) {
+ String pattern = "";
+ if (matcher != null) {
+ pattern = matcher.getPattern();
+
+ if (!fuzzyMatchingEnabled && enable) {
+ if (matcher.getPattern().trim().length() > 1
+ && matcher.getPattern().startsWith("*")
+ && matcher.getPattern().endsWith("*"))
+ pattern = pattern.substring(1).substring(0,
+ pattern.length() - 2);
+ matcher.setPattern(null);
+ }
+ }
+ fuzzyMatchingEnabled = enable;
+ initMatchers();
+
+ matcher.setPattern(pattern);
+ treeViewer.refresh();
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ protected void initMatchers() {
+ treeViewer.resetFilters();
+
+ if (fuzzyMatchingEnabled) {
+ matcher = new FuzzyMatcher(treeViewer);
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
+ } else
+ matcher = new ExactMatcher(treeViewer);
+
+ }
+
+ protected void initTreeViewer() {
+ this.setRedraw(false);
+ // init content provider
+ contentProvider = new ResKeyTreeContentProvider(visibleLocales,
+ projectName, resourceBundle, treeType);
+ treeViewer.setContentProvider(contentProvider);
+
+ // init label provider
+ labelProvider = new ResKeyTreeLabelProvider(visibleLocales);
+ treeViewer.setLabelProvider(labelProvider);
+
+ // we need this to keep the tree expanded
+ treeViewer.setComparer(new IElementComparer() {
+
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
+
+ setTreeStructure();
+ this.setRedraw(true);
+ }
+
+ public void setTreeStructure() {
+ IAbstractKeyTreeModel model = KeyTreeFactory
+ .createModel(ResourceBundleManager.getManager(projectName)
+ .getResourceBundle(resourceBundle));
+ if (treeViewer.getInput() == null) {
+ treeViewer.setUseHashlookup(true);
+ }
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer
+ .getExpandedTreePaths();
+ treeViewer.setInput(model);
+ treeViewer.refresh();
+ treeViewer.setExpandedTreePaths(expandedTreePaths);
+ }
+
+ protected void refreshContent(ResourceBundleChangedEvent event) {
+ if (visibleLocales == null) {
+ initVisibleLocales();
+ }
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+
+ // update content provider
+ contentProvider.setLocales(visibleLocales);
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
+
+ // init label provider
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ labelProvider.setLocales(visibleLocales);
+ if (treeViewer.getLabelProvider() != labelProvider)
+ treeViewer.setLabelProvider(labelProvider);
+
+ // define input of treeviewer
+ setTreeStructure();
+ }
+
+ protected void initVisibleLocales() {
+ SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ sortInfo = new SortInfo();
+ visibleLocales.clear();
+ if (resourceBundle != null) {
+ for (Locale l : manager.getProvidedLocales(resourceBundle)) {
+ if (l == null) {
+ locSorted.put("Default", null);
+ } else {
+ locSorted.put(l.getDisplayName(uiLocale), l);
+ }
+ }
+ }
+
+ for (String lString : locSorted.keySet()) {
+ visibleLocales.add(locSorted.get(lString));
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ }
+
+ protected void constructWidget() {
+ basicLayout = new TreeColumnLayout();
+ this.setLayout(basicLayout);
+
+ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
+ | SWT.BORDER);
+ Tree tree = treeViewer.getTree();
+
+ if (resourceBundle != null) {
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // create tree-columns
+ constructTreeColumns(tree);
+ } else {
+ tree.setHeaderVisible(false);
+ tree.setLinesVisible(false);
+ }
+
+ makeActions();
+ hookDoubleClickAction();
+
+ // register messages table as selection provider
+ site.setSelectionProvider(treeViewer);
+ }
+
+ protected void constructTreeColumns(Tree tree) {
+ tree.removeAll();
+ // tree.getColumns().length;
+
+ // construct key-column
+ keyColumn = new TreeColumn(tree, SWT.NONE);
+ keyColumn.setText("Key");
+ keyColumn.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(keyColumn, new ColumnWeightData(
+ KEY_COLUMN_WEIGHT));
+
+ if (visibleLocales != null) {
+ final ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ for (final Locale l : visibleLocales) {
+ TreeColumn col = new TreeColumn(tree, SWT.NONE);
+
+ // Add editing support to this table column
+ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
+ tCol.setEditingSupport(new EditingSupport(treeViewer) {
+
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+
+ 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 CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer
+ .getControl();
+ editor = new TextCellEditor(tree);
+ editor.getControl().addTraverseListener(
+ new TraverseListener() {
+
+ @Override
+ public void keyTraversed(TraverseEvent e) {
+ Logger.logInfo("CELL_EDITOR: "
+ + e.toString());
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT
+ || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+
+ e.doit = false;
+ int colIndex = visibleLocales
+ .indexOf(l) + 1;
+ Object sel = ((IStructuredSelection) treeViewer
+ .getSelection())
+ .getFirstElement();
+ int noOfCols = treeViewer
+ .getTree()
+ .getColumnCount();
+
+ // go to next cell
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
+ int nextColIndex = colIndex + 1;
+ if (nextColIndex < noOfCols)
+ treeViewer.editElement(
+ sel,
+ nextColIndex);
+ // go to previous cell
+ } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+ int prevColIndex = colIndex - 1;
+ if (prevColIndex > 0)
+ treeViewer.editElement(
+ sel,
+ colIndex - 1);
+ }
+ }
+ }
+ });
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayName(uiLocale);
+
+ col.setText(displayName);
+ col.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+ });
+ basicLayout.setColumnData(col, new ColumnWeightData(
+ LOCALE_COLUMN_WEIGHT));
+ }
+ }
+ }
+
+ protected void updateSorter(int idx) {
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ sorter.setSortInfo(sortInfo);
+ treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
+ setTreeStructure();
+ treeViewer.refresh();
+ }
+
+ @Override
+ public boolean setFocus() {
+ return treeViewer.getControl().setFocus();
+ }
+
+ /*** DRAG AND DROP ***/
+ protected void hookDragAndDrop() {
+ // KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource
+ // (treeViewer);
+ KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
+ MessagesDragSource source = new MessagesDragSource(treeViewer,
+ this.resourceBundle);
+ MessagesDropTarget target = new MessagesDropTarget(treeViewer,
+ projectName, resourceBundle);
+
+ // Initialize drag source for copy event
+ DragSource dragSource = new DragSource(treeViewer.getControl(),
+ DND.DROP_COPY | DND.DROP_MOVE);
+ dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
+ // dragSource.addDragListener(ktiSource);
+ dragSource.addDragListener(source);
+
+ // Initialize drop target for copy event
+ DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
+ DND.DROP_MOVE | DND.DROP_COPY);
+ dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(),
+ JavaUI.getJavaElementClipboardTransfer() });
+ dropTarget.addDropListener(ktiTarget);
+ dropTarget.addDropListener(target);
+ }
+
+ /*** ACTIONS ***/
+
+ private void makeActions() {
+ doubleClickAction = new Action() {
+
+ @Override
+ public void run() {
+ editSelectedItem();
+ }
+
+ };
+ }
+
+ private void hookDoubleClickAction() {
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
+ }
+
+ /*** SELECTION LISTENER ***/
+
+ protected void registerListeners() {
+
+ this.editorListener = new MessagesEditorListener();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject())
+ .addMessagesEditorListener(editorListener);
+ }
+
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
+
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
+ }
+
+ protected void unregisterListeners() {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject())
+ .removeMessagesEditorListener(editorListener);
+ }
+ treeViewer.removeSelectionChangedListener(selectionChangedListener);
+ }
+
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
+ treeViewer.addSelectionChangedListener(listener);
+ selectionChangedListener = listener;
+ }
+
+ @Override
+ public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
+ if (event.getType() != ResourceBundleChangedEvent.MODIFIED
+ || !event.getBundle().equals(this.getResourceBundle()))
+ return;
+
+ if (Display.getCurrent() != null) {
+ refreshViewer(event, true);
+ return;
+ }
+
+ Display.getDefault().asyncExec(new Runnable() {
+
+ public void run() {
+ refreshViewer(event, true);
+ }
+ });
+ }
+
+ private void refreshViewer(ResourceBundleChangedEvent event,
+ boolean computeVisibleLocales) {
+ // manager.loadResourceBundle(resourceBundle);
+ if (computeVisibleLocales) {
+ refreshContent(event);
+ }
+
+ // Display.getDefault().asyncExec(new Runnable() {
+ // public void run() {
+ treeViewer.refresh();
+ // }
+ // });
+ }
+
+ public StructuredViewer getViewer() {
+ return this.treeViewer;
+ }
+
+ public void setSearchString(String pattern) {
+ matcher.setPattern(pattern);
+ treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat
+ : TreeType.Tree;
+ labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
+ // WTF?
+ treeType = treeType.equals(TreeType.Tree)
+ && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree
+ : TreeType.Flat;
+ treeViewer.refresh();
+ this.refreshContent(null);
+ }
+
+ public SortInfo getSortInfo() {
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ sortInfo.setVisibleLocales(visibleLocales);
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree
+ : TreeType.Flat;
+ treeViewer.refresh();
+ }
+ }
+
+ public String getSearchString() {
+ return matcher.getPattern();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void editSelectedItem() {
+ String key = "";
+ ISelection selection = treeViewer.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structSel = (IStructuredSelection) selection;
+ if (structSel.getFirstElement() instanceof IKeyTreeNode) {
+ IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel
+ .getFirstElement();
+ key = keyTreeNode.getMessageKey();
+ }
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ EditorUtils.openEditor(site.getPage(),
+ manager.getRandomFile(resourceBundle),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
+ }
+
+ public void deleteSelectedItems() {
+ List<String> keys = new ArrayList<String>();
+
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ addKeysToRemove((IKeyTreeNode) elem, keys);
+ }
+ }
+ }
+
+ try {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+ manager.removeResourceBundleEntry(getResourceBundle(), keys);
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ }
+ }
+
+ private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
+ keys.add(node.getMessageKey());
+ for (IKeyTreeNode ktn : node.getChildren()) {
+ addKeysToRemove(ktn, keys);
+ }
+ }
+
+ public void addNewItem(ISelection selection) {
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
+
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
+ break;
+ }
+ }
+ }
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix
+ + "." + "[Platzhalter]"
+ : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(getResourceBundle());
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+ }
+
+ public void setMatchingPrecision(float value) {
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ private class MessagesEditorListener implements IMessagesEditorListener {
+ @Override
+ public void onSave() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onModify() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onResourceChanged(IMessagesBundle bundle) {
+ // TODO Auto-generated method stub
+
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
new file mode 100644
index 00000000..dba51f8a
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
@@ -0,0 +1,270 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.tree.IAbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.IElementComparer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+
+public class ResourceSelector extends Composite {
+
+ public static final int DISPLAY_KEYS = 0;
+ public static final int DISPLAY_TEXT = 1;
+
+ private Locale displayLocale = null; // default
+ private int displayMode;
+ private String resourceBundle;
+ private String projectName;
+ private boolean showTree = true;
+
+ private TreeViewer viewer;
+ private TreeColumnLayout basicLayout;
+ private TreeColumn entries;
+ private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>();
+
+ // Viewer model
+ private TreeType treeType = TreeType.Tree;
+ private StyledCellLabelProvider labelProvider;
+
+ public ResourceSelector(Composite parent, int style) {
+ super(parent, style);
+
+ initLayout(this);
+ initViewer(this);
+ }
+
+ protected void updateContentProvider(IMessagesBundleGroup group) {
+ // define input of treeviewer
+ if (!showTree || displayMode == DISPLAY_TEXT) {
+ treeType = TreeType.Flat;
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+
+ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager
+ .getResourceBundle(resourceBundle));
+ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) viewer
+ .getContentProvider();
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
+ contentProvider.setTreeType(treeType);
+ if (viewer.getInput() == null) {
+ viewer.setUseHashlookup(true);
+ }
+
+ // viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer
+ .getExpandedTreePaths();
+ viewer.setInput(model);
+ viewer.refresh();
+ viewer.setExpandedTreePaths(expandedTreePaths);
+ }
+
+ protected void updateViewer(boolean updateContent) {
+ IMessagesBundleGroup group = ResourceBundleManager.getManager(
+ projectName).getResourceBundle(resourceBundle);
+
+ if (group == null)
+ return;
+
+ if (displayMode == DISPLAY_TEXT) {
+ labelProvider = new ValueKeyTreeLabelProvider(
+ group.getMessagesBundle(displayLocale));
+ treeType = TreeType.Flat;
+ ((ResKeyTreeContentProvider) viewer.getContentProvider())
+ .setTreeType(treeType);
+ } else {
+ labelProvider = new ResKeyTreeLabelProvider(null);
+ treeType = TreeType.Tree;
+ ((ResKeyTreeContentProvider) viewer.getContentProvider())
+ .setTreeType(treeType);
+ }
+
+ viewer.setLabelProvider(labelProvider);
+ if (updateContent)
+ updateContentProvider(group);
+ }
+
+ protected void initLayout(Composite parent) {
+ basicLayout = new TreeColumnLayout();
+ parent.setLayout(basicLayout);
+ }
+
+ protected void initViewer(Composite parent) {
+ viewer = new TreeViewer(parent, SWT.BORDER | SWT.SINGLE
+ | SWT.FULL_SELECTION);
+ Tree table = viewer.getTree();
+
+ // Init table-columns
+ entries = new TreeColumn(table, SWT.NONE);
+ basicLayout.setColumnData(entries, new ColumnWeightData(1));
+
+ viewer.setContentProvider(new ResKeyTreeContentProvider());
+ viewer.addSelectionChangedListener(new ISelectionChangedListener() {
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ ISelection selection = event.getSelection();
+ String selectionSummary = "";
+ String selectedKey = "";
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(projectName);
+
+ if (selection instanceof IStructuredSelection) {
+ Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection)
+ .iterator();
+ if (itSel.hasNext()) {
+ IKeyTreeNode selItem = itSel.next();
+ IMessagesBundleGroup group = manager
+ .getResourceBundle(resourceBundle);
+ selectedKey = selItem.getMessageKey();
+
+ if (group == null)
+ return;
+ Iterator<Locale> itLocales = manager
+ .getProvidedLocales(resourceBundle).iterator();
+ while (itLocales.hasNext()) {
+ Locale l = itLocales.next();
+ try {
+ selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag
+ : l.getDisplayLanguage())
+ + ":\n";
+ selectionSummary += "\t"
+ + group.getMessagesBundle(l)
+ .getMessage(
+ selItem.getMessageKey())
+ .getValue() + "\n";
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ // construct ResourceSelectionEvent
+ ResourceSelectionEvent e = new ResourceSelectionEvent(
+ selectedKey, selectionSummary);
+ fireSelectionChanged(e);
+ }
+ });
+
+ // we need this to keep the tree expanded
+ viewer.setComparer(new IElementComparer() {
+
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
+ }
+
+ public Locale getDisplayLocale() {
+ return displayLocale;
+ }
+
+ public void setDisplayLocale(Locale displayLocale) {
+ this.displayLocale = displayLocale;
+ updateViewer(false);
+ }
+
+ public int getDisplayMode() {
+ return displayMode;
+ }
+
+ public void setDisplayMode(int displayMode) {
+ this.displayMode = displayMode;
+ updateViewer(true);
+ }
+
+ public void setResourceBundle(String resourceBundle) {
+ this.resourceBundle = resourceBundle;
+ updateViewer(true);
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void addSelectionChangedListener(IResourceSelectionListener l) {
+ listeners.add(l);
+ }
+
+ public void removeSelectionChangedListener(IResourceSelectionListener l) {
+ listeners.remove(l);
+ }
+
+ private void fireSelectionChanged(ResourceSelectionEvent event) {
+ Iterator<IResourceSelectionListener> itResList = listeners.iterator();
+ while (itResList.hasNext()) {
+ itResList.next().selectionChanged(event);
+ }
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public boolean isShowTree() {
+ return showTree;
+ }
+
+ public void setShowTree(boolean showTree) {
+ if (this.showTree != showTree) {
+ this.showTree = showTree;
+ this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
+ updateViewer(false);
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
new file mode 100644
index 00000000..3b58fc8a
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.event;
+
+public class ResourceSelectionEvent {
+
+ private String selectionSummary;
+ private String selectedKey;
+
+ public ResourceSelectionEvent(String selectedKey, String selectionSummary) {
+ this.setSelectionSummary(selectionSummary);
+ this.setSelectedKey(selectedKey);
+ }
+
+ public void setSelectedKey(String key) {
+ selectedKey = key;
+ }
+
+ public void setSelectionSummary(String selectionSummary) {
+ this.selectionSummary = selectionSummary;
+ }
+
+ public String getSelectionSummary() {
+ return selectionSummary;
+ }
+
+ public String getSelectedKey() {
+ return selectedKey;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
new file mode 100644
index 00000000..419bc725
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
@@ -0,0 +1,89 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets.filter;
+
+import java.util.Locale;
+
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+public class ExactMatcher extends ViewerFilter {
+
+ protected final StructuredViewer viewer;
+ protected String pattern = "";
+ protected StringMatcher matcher;
+
+ public ExactMatcher(StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public String getPattern() {
+ return pattern;
+ }
+
+ public void setPattern(String p) {
+ boolean filtering = matcher != null;
+ if (p != null && p.trim().length() > 0) {
+ pattern = p;
+ matcher = new StringMatcher("*" + pattern + "*", true, false);
+ if (!filtering)
+ viewer.addFilter(this);
+ else
+ viewer.refresh();
+ } else {
+ pattern = "";
+ matcher = null;
+ if (filtering) {
+ viewer.removeFilter(this);
+ }
+ }
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = matcher.match(vEle.getMessageKey());
+
+ if (selected) {
+ int start = -1;
+ while ((start = vEle.getMessageKey().toLowerCase()
+ .indexOf(pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo.addKeyOccurrence(start, pattern.length());
+ }
+ filterInfo.setFoundInKey(selected);
+ filterInfo.setFoundInKey(true);
+ } else
+ filterInfo.setFoundInKey(false);
+
+ // Iterate translations
+ for (Locale l : vEle.getLocales()) {
+ String value = vEle.getValue(l);
+ if (matcher.match(value)) {
+ filterInfo.addFoundInLocale(l);
+ filterInfo.addSimilarity(l, 1d);
+ int start = -1;
+ while ((start = value.toLowerCase().indexOf(
+ pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo
+ .addFoundInLocaleRange(l, start, pattern.length());
+ }
+ selected = true;
+ }
+ }
+
+ vEle.setInfo(filterInfo);
+ return selected;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
new file mode 100644
index 00000000..ee6725be
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
@@ -0,0 +1,94 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.jface.text.Region;
+
+public class FilterInfo {
+
+ private boolean foundInKey;
+ private List<Locale> foundInLocales = new ArrayList<Locale>();
+ private List<Region> keyOccurrences = new ArrayList<Region>();
+ private Double keySimilarity;
+ private Map<Locale, List<Region>> occurrences = new HashMap<Locale, List<Region>>();
+ private Map<Locale, Double> localeSimilarity = new HashMap<Locale, Double>();
+
+ public FilterInfo() {
+
+ }
+
+ public void setKeySimilarity(Double similarity) {
+ keySimilarity = similarity;
+ }
+
+ public Double getKeySimilarity() {
+ return keySimilarity;
+ }
+
+ public void addSimilarity(Locale l, Double similarity) {
+ localeSimilarity.put(l, similarity);
+ }
+
+ public Double getSimilarityLevel(Locale l) {
+ return localeSimilarity.get(l);
+ }
+
+ public void setFoundInKey(boolean foundInKey) {
+ this.foundInKey = foundInKey;
+ }
+
+ public boolean isFoundInKey() {
+ return foundInKey;
+ }
+
+ public void addFoundInLocale(Locale loc) {
+ foundInLocales.add(loc);
+ }
+
+ public void removeFoundInLocale(Locale loc) {
+ foundInLocales.remove(loc);
+ }
+
+ public void clearFoundInLocale() {
+ foundInLocales.clear();
+ }
+
+ public boolean hasFoundInLocale(Locale l) {
+ return foundInLocales.contains(l);
+ }
+
+ public List<Region> getFoundInLocaleRanges(Locale locale) {
+ List<Region> reg = occurrences.get(locale);
+ return (reg == null ? new ArrayList<Region>() : reg);
+ }
+
+ public void addFoundInLocaleRange(Locale locale, int start, int length) {
+ List<Region> regions = occurrences.get(locale);
+ if (regions == null)
+ regions = new ArrayList<Region>();
+ regions.add(new Region(start, length));
+ occurrences.put(locale, regions);
+ }
+
+ public List<Region> getKeyOccurrences() {
+ return keyOccurrences;
+ }
+
+ public void addKeyOccurrence(int start, int length) {
+ keyOccurrences.add(new Region(start, length));
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
new file mode 100644
index 00000000..c5302f50
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
@@ -0,0 +1,65 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets.filter;
+
+import java.util.Locale;
+
+import org.eclipse.babel.editor.api.AnalyzerFactory;
+import org.eclipse.babel.editor.api.ILevenshteinDistanceAnalyzer;
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+
+public class FuzzyMatcher extends ExactMatcher {
+
+ protected ILevenshteinDistanceAnalyzer lvda;
+ protected float minimumSimilarity = 0.75f;
+
+ public FuzzyMatcher(StructuredViewer viewer) {
+ super(viewer);
+ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
+ ;
+ }
+
+ public double getMinimumSimilarity() {
+ return minimumSimilarity;
+ }
+
+ public void setMinimumSimilarity(float similarity) {
+ this.minimumSimilarity = similarity;
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ boolean exactMatch = super.select(viewer, parentElement, element);
+ boolean match = exactMatch;
+
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
+
+ for (Locale l : vkti.getLocales()) {
+ String value = vkti.getValue(l);
+ if (filterInfo.hasFoundInLocale(l))
+ continue;
+ double dist = lvda.analyse(value, getPattern());
+ if (dist >= minimumSimilarity) {
+ filterInfo.addFoundInLocale(l);
+ filterInfo.addSimilarity(l, dist);
+ match = true;
+ filterInfo.addFoundInLocaleRange(l, 0, value.length());
+ }
+ }
+
+ vkti.setInfo(filterInfo);
+ return match;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
new file mode 100644
index 00000000..52238ec9
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
@@ -0,0 +1,496 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets.filter;
+
+import java.util.Vector;
+
+/**
+ * A string pattern matcher, suppporting "*" and "?" wildcards.
+ */
+public class StringMatcher {
+ protected String fPattern;
+
+ protected int fLength; // pattern length
+
+ protected boolean fIgnoreWildCards;
+
+ protected boolean fIgnoreCase;
+
+ protected boolean fHasLeadingStar;
+
+ protected boolean fHasTrailingStar;
+
+ protected String fSegments[]; // the given pattern is split into * separated
+ // segments
+
+ /* boundary value beyond which we don't need to search in the text */
+ protected int fBound = 0;
+
+ protected static final char fSingleWildCard = '\u0000';
+
+ public static class Position {
+ int start; // inclusive
+
+ int end; // exclusive
+
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getEnd() {
+ return end;
+ }
+ }
+
+ /**
+ * StringMatcher constructor takes in a String object that is a simple
+ * pattern which may contain '*' for 0 and many characters and '?' for
+ * exactly one character.
+ *
+ * Literal '*' and '?' characters must be escaped in the pattern e.g.,
+ * "\*" means literal "*", etc.
+ *
+ * Escaping any other character (including the escape character itself),
+ * just results in that character in the pattern. e.g., "\a" means "a" and
+ * "\\" means "\"
+ *
+ * If invoking the StringMatcher with string literals in Java, don't forget
+ * escape characters are represented by "\\".
+ *
+ * @param pattern
+ * the pattern to match text against
+ * @param ignoreCase
+ * if true, case is ignored
+ * @param ignoreWildCards
+ * if true, wild cards and their escape sequences are ignored
+ * (everything is taken literally).
+ */
+ public StringMatcher(String pattern, boolean ignoreCase,
+ boolean ignoreWildCards) {
+ if (pattern == null) {
+ throw new IllegalArgumentException();
+ }
+ fIgnoreCase = ignoreCase;
+ fIgnoreWildCards = ignoreWildCards;
+ fPattern = pattern;
+ fLength = pattern.length();
+
+ if (fIgnoreWildCards) {
+ parseNoWildCards();
+ } else {
+ parseWildCards();
+ }
+ }
+
+ /**
+ * Find the first occurrence of the pattern between <code>start</code
+ * )(inclusive) and <code>end</code>(exclusive).
+ *
+ * @param text
+ * the String object to search in
+ * @param start
+ * the starting index of the search range, inclusive
+ * @param end
+ * the ending index of the search range, exclusive
+ * @return an <code>StringMatcher.Position</code> object that keeps the
+ * starting (inclusive) and ending positions (exclusive) of the
+ * first occurrence of the pattern in the specified range of the
+ * text; return null if not found or subtext is empty (start==end).
+ * A pair of zeros is returned if pattern is empty string Note that
+ * for pattern like "*abc*" with leading and trailing stars,
+ * position of "abc" is returned. For a pattern like"*??*" in text
+ * "abcdf", (1,3) is returned
+ */
+ public StringMatcher.Position find(String text, int start, int end) {
+ if (text == null) {
+ throw new IllegalArgumentException();
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+ if (end < 0 || start >= end) {
+ return null;
+ }
+ if (fLength == 0) {
+ return new Position(start, start);
+ }
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
+ return null;
+ }
+ return new Position(x, x + fLength);
+ }
+
+ int segCount = fSegments.length;
+ if (segCount == 0) {
+ return new Position(start, end);
+ }
+
+ int curPos = start;
+ int matchStart = -1;
+ int i;
+ for (i = 0; i < segCount && curPos < end; ++i) {
+ String current = fSegments[i];
+ int nextMatch = regExpPosIn(text, curPos, end, current);
+ if (nextMatch < 0) {
+ return null;
+ }
+ if (i == 0) {
+ matchStart = nextMatch;
+ }
+ curPos = nextMatch + current.length();
+ }
+ if (i < segCount) {
+ return null;
+ }
+ return new Position(matchStart, curPos);
+ }
+
+ /**
+ * match the given <code>text</code> with the pattern
+ *
+ * @return true if matched otherwise false
+ * @param text
+ * a String object
+ */
+ public boolean match(String text) {
+ if (text == null) {
+ return false;
+ }
+ return match(text, 0, text.length());
+ }
+
+ /**
+ * Given the starting (inclusive) and the ending (exclusive) positions in
+ * the <code>text</code>, determine if the given substring matches with
+ * aPattern
+ *
+ * @return true if the specified portion of the text matches the pattern
+ * @param text
+ * a String object that contains the substring to match
+ * @param start
+ * marks the starting position (inclusive) of the substring
+ * @param end
+ * marks the ending index (exclusive) of the substring
+ */
+ public boolean match(String text, int start, int end) {
+ if (null == text) {
+ throw new IllegalArgumentException();
+ }
+
+ if (start > end) {
+ return false;
+ }
+
+ if (fIgnoreWildCards) {
+ return (end - start == fLength)
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
+ }
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ return true;
+ }
+ if (start == end) {
+ return fLength == 0;
+ }
+ if (fLength == 0) {
+ return start == end;
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+
+ int tCurPos = start;
+ int bound = end - fBound;
+ if (bound < 0) {
+ return false;
+ }
+ int i = 0;
+ String current = fSegments[i];
+ int segLength = current.length();
+
+ /* process first segment */
+ if (!fHasLeadingStar) {
+ if (!regExpRegionMatches(text, start, current, 0, segLength)) {
+ return false;
+ } else {
+ ++i;
+ tCurPos = tCurPos + segLength;
+ }
+ }
+ if ((fSegments.length == 1) && (!fHasLeadingStar)
+ && (!fHasTrailingStar)) {
+ // only one segment to match, no wildcards specified
+ return tCurPos == end;
+ }
+ /* process middle segments */
+ while (i < segCount) {
+ current = fSegments[i];
+ int currentMatch;
+ int k = current.indexOf(fSingleWildCard);
+ if (k < 0) {
+ currentMatch = textPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ } else {
+ currentMatch = regExpPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
+
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
+ }
+
+ /**
+ * This method parses the given pattern into segments seperated by wildcard
+ * '*' characters. Since wildcards are not being used in this case, the
+ * pattern consists of a single segment.
+ */
+ private void parseNoWildCards() {
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
+ }
+
+ /**
+ * Parses the given pattern into segments seperated by wildcard '*'
+ * characters.
+ *
+ * @param p
+ * , a String object that is a simple regular expression with '*'
+ * and/or '?'
+ */
+ private void parseWildCards() {
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
+ fHasLeadingStar = true;
+ }
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
+
+ Vector temp = new Vector();
+
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
+
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
+
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
+ }
+
+ /**
+ * @param text
+ * a string which contains no wildcard
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int posIn(String text, int start, int end) {// no wild card in
+ // pattern
+ int max = end - fLength;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ /**
+ * @param text
+ * a simple regular expression that may only contain '?'(s)
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @param p
+ * a simple regular expression that may contains '?'
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int regExpPosIn(String text, int start, int end, String p) {
+ int plen = p.length();
+
+ int max = end - plen;
+ for (int i = start; i <= max; ++i) {
+ if (regExpRegionMatches(text, i, p, 0, plen)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ *
+ * @return boolean
+ * @param text
+ * a String to match
+ * @param start
+ * int that indicates the starting index of match, inclusive
+ * @param end
+ * </code> int that indicates the ending index of match,
+ * exclusive
+ * @param p
+ * String, String, a simple regular expression that may contain
+ * '?'
+ * @param ignoreCase
+ * boolean indicating wether code>p</code> is case sensitive
+ */
+ protected boolean regExpRegionMatches(String text, int tStart, String p,
+ int pStart, int plen) {
+ while (plen-- > 0) {
+ char tchar = text.charAt(tStart++);
+ char pchar = p.charAt(pStart++);
+
+ /* process wild cards */
+ if (!fIgnoreWildCards) {
+ /* skip single wild cards */
+ if (pchar == fSingleWildCard) {
+ continue;
+ }
+ }
+ if (pchar == tchar) {
+ continue;
+ }
+ if (fIgnoreCase) {
+ if (Character.toUpperCase(tchar) == Character
+ .toUpperCase(pchar)) {
+ continue;
+ }
+ // comparing after converting to upper case doesn't handle all
+ // cases;
+ // also compare after converting to lower case
+ if (Character.toLowerCase(tchar) == Character
+ .toLowerCase(pchar)) {
+ continue;
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @param text
+ * the string to match
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @param p
+ * a pattern string that has no wildcard
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int textPosIn(String text, int start, int end, String p) {
+
+ int plen = p.length();
+ int max = end - plen;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(p, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
new file mode 100644
index 00000000..3c44d65e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets.listener;
+
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+
+public interface IResourceSelectionListener {
+
+ public void selectionChanged(ResourceSelectionEvent e);
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
new file mode 100644
index 00000000..c6b95277
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
@@ -0,0 +1,181 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
+ *
+ * This file is part of Essiembre ResourceBundle Editor.
+ *
+ * Essiembre ResourceBundle Editor is free software; you can redistribute it
+ * and/or modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Essiembre ResourceBundle Editor is distributed in the hope that it will be
+ * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Essiembre ResourceBundle Editor; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307 USA
+ */
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.tapiji.tools.core.ui.Activator;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.FontUtils;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Label provider for key tree viewer.
+ *
+ * @author Pascal Essiembre ([email protected])
+ * @version $Author: nl_carnage $ $Revision: 1.11 $ $Date: 2007/09/11 16:11:09 $
+ */
+public class KeyTreeLabelProvider extends StyledCellLabelProvider /*
+ * implements
+ * IFontProvider
+ * ,
+ * IColorProvider
+ */{
+
+ private static final int KEY_DEFAULT = 1 << 1;
+ private static final int KEY_COMMENTED = 1 << 2;
+ private static final int KEY_NOT = 1 << 3;
+ private static final int WARNING = 1 << 4;
+ private static final int WARNING_GREY = 1 << 5;
+
+ /** Registry instead of UIUtils one for image not keyed by file name. */
+ private static ImageRegistry imageRegistry = new ImageRegistry();
+
+ private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+
+ /** Group font. */
+ private Font groupFontKey = FontUtils.createFont(SWT.BOLD);
+ private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
+
+ /**
+ * @see ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ IKeyTreeNode treeItem = ((IKeyTreeNode) element);
+
+ int iconFlags = 0;
+
+ // Figure out background icon
+ if (treeItem.getMessagesBundleGroup() != null
+ && treeItem.getMessagesBundleGroup().isKey(
+ treeItem.getMessageKey())) {
+ iconFlags += KEY_DEFAULT;
+ } else {
+ iconFlags += KEY_NOT;
+ }
+
+ return generateImage(iconFlags);
+ }
+
+ /**
+ * @see ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ return ((IKeyTreeNode) element).getName();
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ groupFontKey.dispose();
+ groupFontNoKey.dispose();
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
+ */
+ public Font getFont(Object element) {
+ IKeyTreeNode item = (IKeyTreeNode) element;
+ if (item.getChildren().length > 0
+ && item.getMessagesBundleGroup() != null) {
+ if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) {
+ return groupFontKey;
+ }
+ return groupFontNoKey;
+ }
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
+ */
+ public Color getForeground(Object element) {
+ IKeyTreeNode treeItem = (IKeyTreeNode) element;
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
+ */
+ public Color getBackground(Object element) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /**
+ * Generates an image based on icon flags.
+ *
+ * @param iconFlags
+ * @return generated image
+ */
+ private Image generateImage(int iconFlags) {
+ Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
+ if (image == null) {
+ // Figure background image
+ if ((iconFlags & KEY_COMMENTED) != 0) {
+ image = getRegistryImage("keyCommented.gif"); //$NON-NLS-1$
+ } else if ((iconFlags & KEY_NOT) != 0) {
+ image = getRegistryImage("key.gif"); //$NON-NLS-1$
+ } else {
+ image = getRegistryImage("key.gif"); //$NON-NLS-1$
+ }
+
+ }
+ return image;
+ }
+
+ private Image getRegistryImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ cell.setBackground(getBackground(cell.getElement()));
+ cell.setFont(getFont(cell.getElement()));
+ cell.setForeground(getForeground(cell.getElement()));
+
+ cell.setText(getText(cell.getElement()));
+ cell.setImage(getImage(cell.getElement()));
+ super.update(cell);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
new file mode 100644
index 00000000..08b5525f
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
@@ -0,0 +1,27 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets.provider;
+
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements
+ ITableLabelProvider {
+ @Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ @Override
+ public String getColumnText(Object element, int columnIndex) {
+ return super.getText(element);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
new file mode 100644
index 00000000..0daf1c94
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
@@ -0,0 +1,230 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - Babel integration
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.core.message.tree.IAbstractKeyTreeModel;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.core.message.tree.IKeyTreeVisitor;
+import org.eclipse.babel.core.message.tree.TreeType;
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+
+public class ResKeyTreeContentProvider implements ITreeContentProvider {
+
+ private IAbstractKeyTreeModel keyTreeModel;
+ private Viewer viewer;
+
+ private TreeType treeType = TreeType.Tree;
+
+ /** Viewer this provided act upon. */
+ protected TreeViewer treeViewer;
+
+ private List<Locale> locales;
+ private String bundleId;
+ private String projectName;
+
+ public ResKeyTreeContentProvider(List<Locale> locales, String projectName,
+ String bundleId, TreeType treeType) {
+ this.locales = locales;
+ this.projectName = projectName;
+ this.bundleId = bundleId;
+ this.treeType = treeType;
+ }
+
+ public void setBundleId(String bundleId) {
+ this.bundleId = bundleId;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public ResKeyTreeContentProvider() {
+ locales = new ArrayList<Locale>();
+ }
+
+ public void setLocales(List<Locale> locales) {
+ this.locales = locales;
+ }
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ IKeyTreeNode parentNode = (IKeyTreeNode) parentElement;
+ switch (treeType) {
+ case Tree:
+ return convertKTItoVKTI(keyTreeModel.getChildren(parentNode));
+ case Flat:
+ return new IKeyTreeNode[0];
+ default:
+ // Should not happen
+ return new IKeyTreeNode[0];
+ }
+ }
+
+ protected Object[] convertKTItoVKTI(Object[] children) {
+ Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>();
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ this.projectName).getMessagesBundleGroup(this.bundleId);
+
+ for (Object o : children) {
+ if (o instanceof IValuedKeyTreeNode)
+ items.add((IValuedKeyTreeNode) o);
+ else {
+ IKeyTreeNode kti = (IKeyTreeNode) o;
+ IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(
+ kti.getParent(), kti.getName(), kti.getMessageKey(),
+ messagesBundleGroup);
+
+ for (IKeyTreeNode k : kti.getChildren()) {
+ vkti.addChild(k);
+ }
+
+ // init translations
+ for (Locale l : locales) {
+ try {
+ IMessage message = messagesBundleGroup
+ .getMessagesBundle(l).getMessage(
+ kti.getMessageKey());
+ if (message != null) {
+ vkti.addValue(l, message.getValue());
+ }
+ } catch (Exception e) {
+ }
+ }
+ items.add(vkti);
+ }
+ }
+
+ return items.toArray();
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ switch (treeType) {
+ case Tree:
+ return convertKTItoVKTI(keyTreeModel.getRootNodes());
+ case Flat:
+ final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
+ IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
+ public void visitKeyTreeNode(IKeyTreeNode node) {
+ if (node.isUsedAsKey()) {
+ actualKeys.add(node);
+ }
+ }
+ };
+ keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
+
+ return actualKeys.toArray();
+ default:
+ // Should not happen
+ return new IKeyTreeNode[0];
+ }
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ IKeyTreeNode node = (IKeyTreeNode) element;
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getParent(node);
+ case Flat:
+ return keyTreeModel;
+ default:
+ // Should not happen
+ return null;
+ }
+ }
+
+ /**
+ * @see ITreeContentProvider#hasChildren(Object)
+ */
+ public boolean hasChildren(Object element) {
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0;
+ case Flat:
+ return false;
+ default:
+ // Should not happen
+ return false;
+ }
+ }
+
+ public int countChildren(Object element) {
+
+ if (element instanceof IKeyTreeNode) {
+ return ((IKeyTreeNode) element).getChildren().length;
+ } else if (element instanceof IValuedKeyTreeNode) {
+ return ((IValuedKeyTreeNode) element).getChildren().length;
+ } else {
+ System.out.println("wait a minute");
+ return 1;
+ }
+ }
+
+ /**
+ * Gets the selected key tree item.
+ *
+ * @return key tree item
+ */
+ private IKeyTreeNode getTreeSelection() {
+ IStructuredSelection selection = (IStructuredSelection) treeViewer
+ .getSelection();
+ return ((IKeyTreeNode) selection.getFirstElement());
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ this.viewer = (TreeViewer) viewer;
+ this.keyTreeModel = (IAbstractKeyTreeModel) newInput;
+ }
+
+ public IMessagesBundleGroup getBundle() {
+ return RBManager.getInstance(projectName).getMessagesBundleGroup(
+ this.bundleId);
+ }
+
+ public String getBundleId() {
+ return bundleId;
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public TreeType getTreeType() {
+ return treeType;
+ }
+
+ public void setTreeType(TreeType treeType) {
+ if (this.treeType != treeType) {
+ this.treeType = treeType;
+ if (viewer != null) {
+ viewer.refresh();
+ }
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
new file mode 100644
index 00000000..5fd75862
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
@@ -0,0 +1,173 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - Babel integration
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.FontUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.FilterInfo;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider {
+
+ private List<Locale> locales;
+ private boolean searchEnabled = false;
+
+ /*** COLORS ***/
+ private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+ private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
+ private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
+
+ /*** FONTS ***/
+ private Font bold = FontUtils.createFont(SWT.BOLD);
+ private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
+
+ public ResKeyTreeLabelProvider(List<Locale> locales) {
+ this.locales = locales;
+ }
+
+ // @Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ if (columnIndex == 0) {
+ IKeyTreeNode kti = (IKeyTreeNode) element;
+ IMessage[] be = kti.getMessagesBundleGroup().getMessages(
+ kti.getMessageKey());
+ boolean incomplete = false;
+
+ if (be.length != kti.getMessagesBundleGroup()
+ .getMessagesBundleCount())
+ incomplete = true;
+ else {
+ for (IMessage b : be) {
+ if (b.getValue() == null
+ || b.getValue().trim().length() == 0) {
+ incomplete = true;
+ break;
+ }
+ }
+ }
+
+ if (incomplete)
+ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
+ else
+ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE);
+ }
+ return null;
+ }
+
+ // @Override
+ public String getColumnText(Object element, int columnIndex) {
+ if (columnIndex == 0)
+ return super.getText(element);
+
+ if (columnIndex <= locales.size()) {
+ IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
+ String entry = item.getValue(locales.get(columnIndex - 1));
+ if (entry != null) {
+ return entry;
+ }
+ }
+ return "";
+ }
+
+ public void setSearchEnabled(boolean enabled) {
+ this.searchEnabled = enabled;
+ }
+
+ public boolean isSearchEnabled() {
+ return this.searchEnabled;
+ }
+
+ public void setLocales(List<Locale> visibleLocales) {
+ locales = visibleLocales;
+ }
+
+ protected boolean isMatchingToPattern(Object element, int columnIndex) {
+ boolean matching = false;
+
+ if (element instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+
+ if (vkti.getInfo() == null)
+ return false;
+
+ FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
+
+ if (columnIndex == 0) {
+ matching = filterInfo.isFoundInKey();
+ } else {
+ matching = filterInfo.hasFoundInLocale(locales
+ .get(columnIndex - 1));
+ }
+ }
+
+ return matching;
+ }
+
+ protected boolean isSearchEnabled(Object element) {
+ return (element instanceof IValuedKeyTreeNode && searchEnabled);
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ Object element = cell.getElement();
+ int columnIndex = cell.getColumnIndex();
+
+ if (isSearchEnabled(element)) {
+ if (isMatchingToPattern(element, columnIndex)) {
+ List<StyleRange> styleRanges = new ArrayList<StyleRange>();
+ FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element)
+ .getInfo();
+
+ if (columnIndex > 0) {
+ for (Region reg : filterInfo.getFoundInLocaleRanges(locales
+ .get(columnIndex - 1))) {
+ styleRanges.add(new StyleRange(reg.getOffset(), reg
+ .getLength(), black, info_color, SWT.BOLD));
+ }
+ } else {
+ // check if the pattern has been found within the key
+ // section
+ if (filterInfo.isFoundInKey()) {
+ for (Region reg : filterInfo.getKeyOccurrences()) {
+ StyleRange sr = new StyleRange(reg.getOffset(),
+ reg.getLength(), black, info_color,
+ SWT.BOLD);
+ styleRanges.add(sr);
+ }
+ }
+ }
+ cell.setStyleRanges(styleRanges
+ .toArray(new StyleRange[styleRanges.size()]));
+ } else {
+ cell.setForeground(gray);
+ }
+ } else if (columnIndex == 0)
+ super.update(cell);
+
+ cell.setImage(this.getColumnImage(element, columnIndex));
+ cell.setText(this.getColumnText(element, columnIndex));
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
new file mode 100644
index 00000000..0c2cca68
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundle;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.jface.viewers.ITableColorProvider;
+import org.eclipse.jface.viewers.ITableFontProvider;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
+ ITableColorProvider, ITableFontProvider {
+
+ private IMessagesBundle locale;
+
+ public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) {
+ this.locale = iBundle;
+ }
+
+ // @Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ // @Override
+ public String getColumnText(Object element, int columnIndex) {
+ try {
+ IKeyTreeNode item = (IKeyTreeNode) element;
+ IMessage entry = locale.getMessage(item.getMessageKey());
+ if (entry != null) {
+ String value = entry.getValue();
+ if (value.length() > 40)
+ value = value.substring(0, 39) + "...";
+ }
+ } catch (Exception e) {
+ }
+ return "";
+ }
+
+ @Override
+ public Color getBackground(Object element, int columnIndex) {
+ return null;// return new Color(Display.getDefault(), 255, 0, 0);
+ }
+
+ @Override
+ public Color getForeground(Object element, int columnIndex) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Font getFont(Object element, int columnIndex) {
+ return null; // UIUtils.createFont(SWT.BOLD);
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ Object element = cell.getElement();
+ int columnIndex = cell.getColumnIndex();
+ cell.setImage(this.getColumnImage(element, columnIndex));
+ cell.setText(this.getColumnText(element, columnIndex));
+
+ super.update(cell);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
new file mode 100644
index 00000000..30314848
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.widgets.sorter;
+
+import java.util.Locale;
+
+import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.SortInfo;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+
+public class ValuedKeyTreeItemSorter extends ViewerSorter {
+
+ private StructuredViewer viewer;
+ private SortInfo sortInfo;
+
+ public ValuedKeyTreeItemSorter(StructuredViewer viewer, SortInfo sortInfo) {
+ this.viewer = viewer;
+ this.sortInfo = sortInfo;
+ }
+
+ public StructuredViewer getViewer() {
+ return viewer;
+ }
+
+ public void setViewer(StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public SortInfo getSortInfo() {
+ return sortInfo;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ this.sortInfo = sortInfo;
+ }
+
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ try {
+ if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode))
+ return super.compare(viewer, e1, e2);
+ IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
+ IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
+
+ int result = 0;
+
+ if (sortInfo == null)
+ return 0;
+
+ if (sortInfo.getColIdx() == 0)
+ result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
+ else {
+ Locale loc = sortInfo.getVisibleLocales().get(
+ sortInfo.getColIdx() - 1);
+ result = (comp1.getValue(loc) == null ? "" : comp1
+ .getValue(loc))
+ .compareTo((comp2.getValue(loc) == null ? "" : comp2
+ .getValue(loc)));
+ }
+
+ return result * (sortInfo.isDESC() ? -1 : 1);
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.core/.classpath b/org.eclipse.babel.tapiji.tools.core/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/.classpath
rename to org.eclipse.babel.tapiji.tools.core/.classpath
diff --git a/org.eclipse.babel.tapiji.tools.core/.project b/org.eclipse.babel.tapiji.tools.core/.project
new file mode 100644
index 00000000..6d850ba3
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.tapiji.tools.core</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.pde.core.prefs b/org.eclipse.babel.tapiji.tools.core/.settings/org.eclipse.pde.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.pde.core.prefs
rename to org.eclipse.babel.tapiji.tools.core/.settings/org.eclipse.pde.core.prefs
diff --git a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..3f1023cd
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF
@@ -0,0 +1,30 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: TapiJI Tools
+Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.core;singleton:=true
+Bundle-Version: 0.0.2.qualifier
+Bundle-Activator: org.eclipse.babel.tapiji.tools.core.Activator
+Bundle-Vendor: Vienna University of Technology
+Require-Bundle: org.eclipse.core.runtime,
+ org.eclipse.jdt.core;bundle-version="3.5.2",
+ org.eclipse.core.resources,
+ org.eclipse.babel.core;bundle-version="0.8.0";visibility:=reexport,
+ org.eclipse.ui.ide;bundle-version="3.7.0",
+ org.eclipse.ui;bundle-version="3.7.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Import-Package: org.apache.commons.io,
+ org.eclipse.core.filebuffers,
+ org.eclipse.core.resources,
+ org.eclipse.jdt.core,
+ org.eclipse.jdt.core.dom,
+ org.eclipse.jface.text,
+ org.eclipse.jface.text.contentassist,
+ org.eclipse.ui.ide,
+ org.eclipse.ui.texteditor
+Export-Package: org.eclipse.babel.tapiji.tools.core,
+ org.eclipse.babel.tapiji.tools.core.extensions,
+ org.eclipse.babel.tapiji.tools.core.model,
+ org.eclipse.babel.tapiji.tools.core.model.exception,
+ org.eclipse.babel.tapiji.tools.core.model.manager,
+ org.eclipse.babel.tapiji.tools.core.util
+Bundle-ActivationPolicy: lazy
diff --git a/org.eclipselabs.tapiji.tools.core/Splash.bmp b/org.eclipse.babel.tapiji.tools.core/Splash.bmp
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/Splash.bmp
rename to org.eclipse.babel.tapiji.tools.core/Splash.bmp
diff --git a/org.eclipselabs.tapiji.tools.core/TapiJI.png b/org.eclipse.babel.tapiji.tools.core/TapiJI.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/TapiJI.png
rename to org.eclipse.babel.tapiji.tools.core/TapiJI.png
diff --git a/org.eclipselabs.tapiji.tools.core/about.html b/org.eclipse.babel.tapiji.tools.core/about.html
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/about.html
rename to org.eclipse.babel.tapiji.tools.core/about.html
diff --git a/org.eclipselabs.tapiji.tools.core/about.ini b/org.eclipse.babel.tapiji.tools.core/about.ini
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/about.ini
rename to org.eclipse.babel.tapiji.tools.core/about.ini
diff --git a/org.eclipselabs.tapiji.tools.core/about.mappings b/org.eclipse.babel.tapiji.tools.core/about.mappings
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/about.mappings
rename to org.eclipse.babel.tapiji.tools.core/about.mappings
diff --git a/org.eclipselabs.tapiji.tools.core/about.properties b/org.eclipse.babel.tapiji.tools.core/about.properties
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/about.properties
rename to org.eclipse.babel.tapiji.tools.core/about.properties
diff --git a/org.eclipselabs.tapiji.tools.core/build.properties b/org.eclipse.babel.tapiji.tools.core/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/build.properties
rename to org.eclipse.babel.tapiji.tools.core/build.properties
diff --git a/org.eclipselabs.tapiji.tools.core/epl-v10.html b/org.eclipse.babel.tapiji.tools.core/epl-v10.html
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/epl-v10.html
rename to org.eclipse.babel.tapiji.tools.core/epl-v10.html
diff --git a/org.eclipselabs.tapiji.tools.core/icons/Folder.png b/org.eclipse.babel.tapiji.tools.core/icons/Folder.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/Folder.png
rename to org.eclipse.babel.tapiji.tools.core/icons/Folder.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/Glossary.psd b/org.eclipse.babel.tapiji.tools.core/icons/Glossary.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/Glossary.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/Glossary.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/NewGlossary.png b/org.eclipse.babel.tapiji.tools.core/icons/NewGlossary.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/NewGlossary.png
rename to org.eclipse.babel.tapiji.tools.core/icons/NewGlossary.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary.png b/org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/OpenGlossary.png
rename to org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary2.png b/org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary2.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/OpenGlossary2.png
rename to org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary2.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary3.png b/org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary3.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/OpenGlossary3.png
rename to org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary3.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary4.png b/org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary4.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/OpenGlossary4.png
rename to org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary4.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary5.png b/org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary5.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/OpenGlossary5.png
rename to org.eclipse.babel.tapiji.tools.core/icons/OpenGlossary5.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/Resource16.png b/org.eclipse.babel.tapiji.tools.core/icons/Resource16.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/Resource16.png
rename to org.eclipse.babel.tapiji.tools.core/icons/Resource16.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/Resource16_small.png b/org.eclipse.babel.tapiji.tools.core/icons/Resource16_small.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/Resource16_small.png
rename to org.eclipse.babel.tapiji.tools.core/icons/Resource16_small.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/Resource16_warning_small.png b/org.eclipse.babel.tapiji.tools.core/icons/Resource16_warning_small.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/Resource16_warning_small.png
rename to org.eclipse.babel.tapiji.tools.core/icons/Resource16_warning_small.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI.png b/org.eclipse.babel.tapiji.tools.core/icons/TapiJI.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/TapiJI.png
rename to org.eclipse.babel.tapiji.tools.core/icons/TapiJI.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png b/org.eclipse.babel.tapiji.tools.core/icons/TapiJI_128.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png
rename to org.eclipse.babel.tapiji.tools.core/icons/TapiJI_128.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png b/org.eclipse.babel.tapiji.tools.core/icons/TapiJI_16.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png
rename to org.eclipse.babel.tapiji.tools.core/icons/TapiJI_16.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_32.png b/org.eclipse.babel.tapiji.tools.core/icons/TapiJI_32.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/TapiJI_32.png
rename to org.eclipse.babel.tapiji.tools.core/icons/TapiJI_32.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png b/org.eclipse.babel.tapiji.tools.core/icons/TapiJI_48.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png
rename to org.eclipse.babel.tapiji.tools.core/icons/TapiJI_48.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png b/org.eclipse.babel.tapiji.tools.core/icons/TapiJI_64.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png
rename to org.eclipse.babel.tapiji.tools.core/icons/TapiJI_64.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/.cvsignore b/org.eclipse.babel.tapiji.tools.core/icons/countries/.cvsignore
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/.cvsignore
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/.cvsignore
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/__.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/__.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/__.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/__.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/_f.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/_f.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/_f.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/_f.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ad.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ad.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ad.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ad.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ae.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ae.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ae.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ae.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/af.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/af.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/af.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/af.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ag.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ag.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ag.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/al.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/al.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/al.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/al.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/am.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/am.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/am.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/am.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ao.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ao.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ao.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ao.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/aq.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/aq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/aq.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/aq.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ar.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ar.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ar.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/at.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/at.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/at.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/at.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/au.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/au.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/au.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/au.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/az.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/az.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/az.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/az.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ba.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ba.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ba.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ba.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/be.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/be.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/be.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/be.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bf.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bf.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bf.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bi.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bi.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bi.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/blank.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/blank.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/blank.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/blank.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bo.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bo.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bo.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/br.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/br.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/br.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/br.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bs.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bs.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bs.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/by.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/by.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/by.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/by.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/bz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/bz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/bz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ca.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ca.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ca.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ca.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cf.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cf.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cf.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ch.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ch.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ch.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ch.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ci.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ci.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ci.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ci.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/co.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/co.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/co.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/co.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cs.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cs.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cs.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/cz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/cz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/cz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/dd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/dd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/dd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/de.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/de.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/de.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/de.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/dj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/dj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/dj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/dk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/dk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/dk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/dm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/dm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/dm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/do.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/do.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/do.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/do.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/dz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/dz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/dz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ec.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ec.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ec.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ec.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ee.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ee.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ee.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ee.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/eg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/eg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/eg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/eg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/eh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/eh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/eh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/eh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/er.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/er.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/er.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/er.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/es.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/es.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/es.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/es.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/et.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/et.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/et.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/et.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/eu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/eu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/eu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/eu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fi.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/fi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/fi.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/fi.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/fj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/fj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/fj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/fm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/fm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/fm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/fr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/fr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/fr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ga.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ga.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ga.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ga.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ge.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ge.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ge.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ge.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gq.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gq.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gq.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/gy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/gy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/gy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/hk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/hk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/hk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/hn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/hn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/hn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/hr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/hr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/hr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ht.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ht.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ht.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ht.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/hu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/hu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/hu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/id.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/id.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/id.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/id.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ie.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ie.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ie.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ie.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/il.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/il.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/il.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/il.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/in.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/in.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/in.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/in.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/iq.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/iq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/iq.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/iq.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ir.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ir.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ir.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ir.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/is.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/is.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/is.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/is.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/it.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/it.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/it.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/it.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/jm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/jm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/jm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/jm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/jo.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/jo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/jo.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/jo.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/jp.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/jp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/jp.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/jp.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ke.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ke.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ke.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ke.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ki.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ki.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ki.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ki.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/km.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/km.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/km.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/km.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kp.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kp.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kp.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/kz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/kz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/kz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/la.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/la.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/la.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/la.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/li.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/li.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/li.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/li.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ls.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ls.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ls.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ls.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/lv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/lv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/lv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ly.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ly.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ly.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ly.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ma.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ma.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ma.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ma.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/md.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/md.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/md.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/md.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ml.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ml.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ml.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ml.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mx.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mx.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mx.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mx.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/my.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/my.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/my.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/my.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/mz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/mz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/mz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/na.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/na.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/na.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/na.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ne.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ne.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ne.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ne.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ng.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ng.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ng.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ng.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ni.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ni.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ni.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ni.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/nl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/nl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/nl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/no.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/no.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/no.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/no.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/np.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/np.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/np.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/np.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/nr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/nr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/nr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/nu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/nu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/nu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/nz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/nz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/nz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/om.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/om.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/om.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/om.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pa.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pa.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pa.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pe.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pe.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pe.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pe.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ph.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ph.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ph.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ph.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ps.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ps.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ps.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ps.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/pw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/pw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/pw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/py.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/py.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/py.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/py.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/qa.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/qa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/qa.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/qa.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ro.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ro.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ro.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ro.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ru.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ru.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ru.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ru.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/rw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/rw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/rw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/rw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sa.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sa.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sa.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/se.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/se.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/se.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/se.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/si.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/si.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/si.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/si.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/__.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/__.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/__.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/__.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/_f.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/_f.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/_f.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/_f.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ad.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ad.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ad.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ad.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ae.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ae.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ae.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ae.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/af.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/af.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/af.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/af.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ag.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ag.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ag.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/al.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/al.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/al.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/al.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/am.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/am.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/am.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/am.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ao.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ao.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ao.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ao.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/aq.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/aq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/aq.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/aq.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ar.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ar.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ar.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/at.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/at.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/at.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/at.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/au.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/au.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/au.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/au.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/az.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/az.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/az.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/az.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ba.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ba.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ba.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ba.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/be.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/be.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/be.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/be.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bf.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bf.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bf.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bi.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bi.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bi.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/blank.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/blank.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/blank.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/blank.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bo.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bo.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bo.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/br.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/br.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/br.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/br.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bs.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bs.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bs.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/by.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/by.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/by.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/by.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/bz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/bz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/bz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ca.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ca.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ca.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ca.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cf.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cf.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cf.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ch.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ch.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ch.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ch.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ci.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ci.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ci.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ci.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/co.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/co.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/co.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/co.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cs.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cs.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cs.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/cz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/cz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/cz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/dd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/dd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/dd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/de.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/de.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/de.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/de.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/dj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/dj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/dj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/dk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/dk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/dk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/dm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/dm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/dm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/do.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/do.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/do.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/do.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/dz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/dz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/dz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ec.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ec.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ec.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ec.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ee.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ee.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ee.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ee.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/eg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/eg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/eg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/eg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/eh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/eh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/eh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/eh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/er.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/er.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/er.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/er.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/es.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/es.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/es.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/es.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/et.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/et.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/et.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/et.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/eu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/eu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/eu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/eu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fi.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/fi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/fi.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/fi.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/fj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/fj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/fj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/fm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/fm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/fm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/fr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/fr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/fr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ga.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ga.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ga.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ga.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ge.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ge.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ge.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ge.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gq.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gq.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gq.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/gy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/gy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/gy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/hk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/hk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/hk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/hn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/hn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/hn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/hr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/hr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/hr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ht.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ht.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ht.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ht.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/hu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/hu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/hu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/id.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/id.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/id.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/id.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ie.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ie.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ie.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ie.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/il.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/il.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/il.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/il.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/in.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/in.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/in.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/in.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/iq.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/iq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/iq.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/iq.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ir.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ir.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ir.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ir.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/is.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/is.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/is.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/is.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/it.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/it.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/it.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/it.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/jm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/jm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/jm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/jm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/jo.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/jo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/jo.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/jo.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/jp.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/jp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/jp.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/jp.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ke.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ke.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ke.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ke.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ki.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ki.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ki.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ki.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/km.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/km.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/km.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/km.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kp.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kp.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kp.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/kz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/kz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/kz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/la.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/la.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/la.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/la.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/li.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/li.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/li.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/li.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ls.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ls.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ls.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ls.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/lv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/lv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/lv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ly.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ly.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ly.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ly.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ma.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ma.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ma.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ma.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/md.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/md.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/md.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/md.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mh.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mh.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mh.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ml.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ml.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ml.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ml.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mx.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mx.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mx.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mx.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/my.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/my.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/my.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/my.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/mz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/mz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/mz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/na.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/na.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/na.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/na.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ne.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ne.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ne.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ne.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ng.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ng.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ng.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ng.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ni.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ni.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ni.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ni.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/nl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/nl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/nl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/no.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/no.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/no.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/no.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/np.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/np.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/np.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/np.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/nr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/nr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/nr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/nu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/nu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/nu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/nz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/nz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/nz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/om.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/om.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/om.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/om.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pa.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pa.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pa.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pe.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pe.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pe.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pe.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ph.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ph.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ph.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ph.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ps.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ps.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ps.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ps.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/pw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/pw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/pw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/py.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/py.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/py.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/py.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/qa.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/qa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/qa.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/qa.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ro.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ro.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ro.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ro.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ru.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ru.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ru.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ru.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/rw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/rw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/rw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/rw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sa.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sa.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sa.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sb.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sb.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sb.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sd.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sd.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sd.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/se.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/se.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/se.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/se.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/si.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/si.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/si.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/si.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sk.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sk.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sk.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sl.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sl.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sl.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/so.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/so.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/so.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/so.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/st.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/st.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/st.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/st.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/su.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/su.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/su.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/su.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/sz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/sz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/sz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/td.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/td.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/td.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/td.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/th.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/th.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/th.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/th.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/to.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/to.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/to.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/to.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tp.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tp.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tp.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/tz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/tz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/tz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ua.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ua.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ua.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ua.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ug.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ug.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ug.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ug.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/un.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/un.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/un.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/un.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/us.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/us.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/us.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/us.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/uy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/uy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/uy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/uy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/uz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/uz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/uz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/uz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/va.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/va.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/va.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/va.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/vc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/vc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/vc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/vc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ve.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ve.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ve.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ve.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/vn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/vn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/vn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/vn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/vu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/vu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/vu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/vu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ws.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ws.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ws.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ws.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ya.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ya.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ya.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ya.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ye.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ye.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ye.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye0.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/ye0.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/ye0.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/ye0.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/yu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/yu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/yu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/yu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/za.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/za.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/za.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/za.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/zm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/zm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/zm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/zm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/zw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/small/zw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/small/zw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/small/zw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/so.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/so.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/so.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/so.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/st.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/st.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/st.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/st.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/su.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/su.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/su.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/su.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/sz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/sz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/sz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/td.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/td.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/td.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/td.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tg.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tg.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tg.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/th.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/th.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/th.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/th.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tj.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/to.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/to.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/to.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/to.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tp.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tp.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tp.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tr.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tr.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tr.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tt.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tt.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tt.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tv.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tv.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tv.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/tz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/tz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/tz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ua.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ua.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ua.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ua.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ug.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ug.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ug.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ug.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/un.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/un.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/un.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/un.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/us.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/us.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/us.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/us.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/uy.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/uy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/uy.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/uy.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/uz.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/uz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/uz.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/uz.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/va.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/va.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/va.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/va.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/vc.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/vc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/vc.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/vc.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ve.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ve.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ve.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ve.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/vn.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/vn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/vn.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/vn.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/vu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/vu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/vu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/vu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ws.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ws.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ws.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ws.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ya.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ya.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ya.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ya.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ye.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ye.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ye.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ye.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ye0.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/ye0.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/ye0.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/ye0.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/yu.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/yu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/yu.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/yu.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/za.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/za.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/za.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/za.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/zm.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/zm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/zm.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/zm.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/zw.gif b/org.eclipse.babel.tapiji.tools.core/icons/countries/zw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/countries/zw.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/countries/zw.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/duplicate.gif b/org.eclipse.babel.tapiji.tools.core/icons/duplicate.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/duplicate.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/duplicate.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/entry.gif b/org.eclipse.babel.tapiji.tools.core/icons/entry.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/entry.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/entry.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/exclude.png b/org.eclipse.babel.tapiji.tools.core/icons/exclude.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/exclude.png
rename to org.eclipse.babel.tapiji.tools.core/icons/exclude.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/file_obj.gif b/org.eclipse.babel.tapiji.tools.core/icons/file_obj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/file_obj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/file_obj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/flatLayout.gif b/org.eclipse.babel.tapiji.tools.core/icons/flatLayout.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/flatLayout.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/flatLayout.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/fldr_obj.gif b/org.eclipse.babel.tapiji.tools.core/icons/fldr_obj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/fldr_obj.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/fldr_obj.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/hierarchicalLayout.gif b/org.eclipse.babel.tapiji.tools.core/icons/hierarchicalLayout.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/hierarchicalLayout.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/hierarchicalLayout.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/icon_new_memory_view.png b/org.eclipse.babel.tapiji.tools.core/icons/icon_new_memory_view.png
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/icon_new_memory_view.png
rename to org.eclipse.babel.tapiji.tools.core/icons/icon_new_memory_view.png
diff --git a/org.eclipselabs.tapiji.tools.core/icons/incomplete.gif b/org.eclipse.babel.tapiji.tools.core/icons/incomplete.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/incomplete.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/incomplete.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/int.gif b/org.eclipse.babel.tapiji.tools.core/icons/int.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/int.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/int.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/key.gif b/org.eclipse.babel.tapiji.tools.core/icons/key.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/key.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/key.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/keyCommented.gif b/org.eclipse.babel.tapiji.tools.core/icons/keyCommented.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/keyCommented.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/keyCommented.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/keyNone.gif b/org.eclipse.babel.tapiji.tools.core/icons/keyNone.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/keyNone.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/keyNone.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/newpropertiesfile.gif b/org.eclipse.babel.tapiji.tools.core/icons/newpropertiesfile.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/newpropertiesfile.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/newpropertiesfile.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/no_int1.gif b/org.eclipse.babel.tapiji.tools.core/icons/no_int1.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/no_int1.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/no_int1.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/no_int2.gif b/org.eclipse.babel.tapiji.tools.core/icons/no_int2.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/no_int2.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/no_int2.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/original/entry.gif b/org.eclipse.babel.tapiji.tools.core/icons/original/entry.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/original/entry.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/original/entry.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/original/entry.psd b/org.eclipse.babel.tapiji.tools.core/icons/original/entry.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/original/entry.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/original/entry.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/IconResource.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/IconResource.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/IconResource.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/IconResource.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/NewGlossary.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/NewGlossary.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/NewGlossary.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/NewGlossary.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/OpenGlossary.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/OpenGlossary.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/OpenGlossary.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/OpenGlossary.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/Resource16.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/Resource16.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_small.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/Resource16_small.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_small.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/Resource16_small.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Splash.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/Splash.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/Splash.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/Splash.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/TJ.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/TJ.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/TJ.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/TJ.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/TapiJI.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/TapiJI.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/TapiJI.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/TapiJI.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/exclude.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/exclude.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude2.psd b/org.eclipse.babel.tapiji.tools.core/icons/photoshop/exclude2.psd
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude2.psd
rename to org.eclipse.babel.tapiji.tools.core/icons/photoshop/exclude2.psd
diff --git a/org.eclipselabs.tapiji.tools.core/icons/propertiesfile.gif b/org.eclipse.babel.tapiji.tools.core/icons/propertiesfile.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/propertiesfile.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/propertiesfile.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/read_only.gif b/org.eclipse.babel.tapiji.tools.core/icons/read_only.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/read_only.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/read_only.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/resourcebundle.gif b/org.eclipse.babel.tapiji.tools.core/icons/resourcebundle.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/resourcebundle.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/resourcebundle.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/sample.gif b/org.eclipse.babel.tapiji.tools.core/icons/sample.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/sample.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/sample.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/similar.gif b/org.eclipse.babel.tapiji.tools.core/icons/similar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/similar.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/similar.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/toc_open.gif b/org.eclipse.babel.tapiji.tools.core/icons/toc_open.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/toc_open.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/toc_open.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/warning.gif b/org.eclipse.babel.tapiji.tools.core/icons/warning.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/warning.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/warning.gif
diff --git a/org.eclipselabs.tapiji.tools.core/icons/warningGrey.gif b/org.eclipse.babel.tapiji.tools.core/icons/warningGrey.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.core/icons/warningGrey.gif
rename to org.eclipse.babel.tapiji.tools.core/icons/warningGrey.gif
diff --git a/org.eclipse.babel.tapiji.tools.core/plugin.xml b/org.eclipse.babel.tapiji.tools.core/plugin.xml
new file mode 100644
index 00000000..d940b2bf
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/plugin.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+ <extension-point id="org.eclipse.babel.tapiji.tools.core.builderExtension" name="BuilderExtension" schema="schema/org.eclipse.babel.tapiji.tools.core.builderExtension.exsd"/>
+ <extension-point id="org.eclipse.babel.tapiji.tools.core.stateLoader" name="StateLoader" schema="schema/org.eclipse.babel.tapiji.tools.core.stateLoader.exsd"/>
+</plugin>
diff --git a/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.builderExtension.exsd b/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.builderExtension.exsd
new file mode 100644
index 00000000..98da3a4e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.builderExtension.exsd
@@ -0,0 +1,222 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipselabs.tapiji.tools.core" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipselabs.tapiji.tools.core" id="builderExtension" name="BuilderExtension"/>
+ </appinfo>
+ <documentation>
+ The TapiJI core plug-in does not contribute any coding assistances into the source code editor. Analogically, it does not provide logic for finding Internationalization problems within sources resources. Moreover, it offers a platform for contributing source code analysis and problem resolution proposals for Internationalization problems in a uniform way. For this purpose, the TapiJI core plug-in provides the extension point org.eclipselabs.tapiji.tools.core.builderExtension that allows other plug-ins to register Internationalization related coding assistances. This concept realizes a loose coupling between basic Internationalization functionality and coding dialect specific help. Once the TapiJI core plug-in is installed, it allows an arbitrary number of extensions to provide their own assistances based on the TapiJI Tools suite.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <choice minOccurs="0" maxOccurs="unbounded">
+ <element ref="i18nAuditor"/>
+ </choice>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="i18nAuditor">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn="org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor:"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ 0.0.1
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ The following example demonstrates registration of Java Programming dialect specific Internationalization assistance.
+
+<pre>
+<extension point="org.eclipselabs.tapiji.tools.core.builderExtension">
+ <i18nResourceAuditor
+ class="ui.JavaResourceAuditor">
+ </i18nResourceAuditor>
+</extension>
+</pre>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiinfo"/>
+ </appinfo>
+ <documentation>
+ Extending plug-ins need to extend the abstract class <strong>org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor</strong>.
+
+<pre>
+package org.eclipselabs.tapiji.tools.core.extensions;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+/**
+ * Auditor class for finding I18N problems within source code resources. The
+ * objects audit method is called for a particular resource. Found errors are
+ * stored within the object's internal data structure and can be queried with
+ * the help of problem categorized getter methods.
+ */
+public abstract class I18nResourceAuditor {
+ /**
+ * Audits a project resource for I18N problems. This method is triggered
+ * during the project's build process.
+ *
+ * @param resource
+ * The project resource
+ */
+ public abstract void audit(IResource resource);
+
+ /**
+ * Returns a list of supported file endings.
+ *
+ * @return The supported file endings
+ */
+ public abstract String[] getFileEndings();
+
+ /**
+ * Returns the list of found need-to-translate string literals. Each list
+ * entry describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of need-to-translate string literal positions
+ */
+ public abstract List<ILocation> getConstantStringLiterals();
+
+ /**
+ * Returns the list of broken Resource-Bundle references. Each list entry
+ * describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of positions of broken Resource-Bundle references
+ */
+ public abstract List<ILocation> getBrokenResourceReferences();
+
+ /**
+ * Returns the list of broken references to Resource-Bundle entries. Each
+ * list entry describes the textual position on which this type of error has
+ * been detected
+ *
+ * @return The list of positions of broken references to locale-sensitive
+ * resources
+ */
+ public abstract List<ILocation> getBrokenBundleReferences();
+
+ /**
+ * Returns a characterizing identifier of the implemented auditing
+ * functionality. The specified identifier is used for discriminating
+ * registered builder extensions.
+ *
+ * @return The String id of the implemented auditing functionality
+ */
+ public abstract String getContextId();
+
+ /**
+ * Returns a list of quick fixes of a reported Internationalization problem.
+ *
+ * @param marker
+ * The warning marker of the Internationalization problem
+ * @param cause
+ * The problem type
+ * @return The list of marker resolution proposals
+ */
+ public abstract List<IMarkerResolution> getMarkerResolutions(
+ IMarker marker);
+
+ /**
+ * Checks if the provided resource auditor is responsible for a particular
+ * resource.
+ *
+ * @param resource
+ * The resource reference
+ * @return True if the resource auditor is responsible for the referenced
+ * resource
+ */
+ public boolean isResourceOfType(IResource resource) {
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
+ }
+}
+
+</pre>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="implementation"/>
+ </appinfo>
+ <documentation>
+ <ul>
+ <li>Java Internationalization help: <span style="font-family:monospace">org.eclipselabs.tapiji.tools.java</span></li>
+ <li>JSF Internaization help: <span style="font-family:monospace">org.eclipselabs.tapiji.tools.jsf</span></li>
+</ul>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ Copyright (c) 2011 Stefan Strobl and Martin Reiterer 2011. All rights reserved.
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.stateLoader.exsd b/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.stateLoader.exsd
new file mode 100644
index 00000000..a40e3228
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.stateLoader.exsd
@@ -0,0 +1,119 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="stateLoader" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="stateLoader" id="stateLoader" name="StateLoader"/>
+ </appinfo>
+ <documentation>
+ Xpt, which is implemented by TapiJI to provide a class, which loads the state of the ResourceBundleManager
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="IStateLoader"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="IStateLoader">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.babel.tapiji.tools.core.model.manager.IStateLoader"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiinfo"/>
+ </appinfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="implementation"/>
+ </appinfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ /*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - creation
+ ******************************************************************************/
+ </documentation>
+ </annotation>
+
+</schema>
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
new file mode 100644
index 00000000..3d99da71
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
@@ -0,0 +1,155 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+import org.eclipse.core.runtime.Plugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends Plugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core";
+
+ // The builder extension id
+ public static final String BUILDER_EXTENSION_ID = "org.eclipse.babel.tapiji.tools.core.builderExtension";
+
+ // The shared instance
+ private static Activator plugin;
+
+ // Resource bundle.
+ private ResourceBundle resourceBundle;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key) {
+ ResourceBundle bundle = Activator.getDefault().getResourceBundle();
+ try {
+ return (bundle != null) ? bundle.getString(key) : key;
+ } catch (MissingResourceException e) {
+ return key;
+ }
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime argument to replace in key value
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key, String arg1) {
+ return MessageFormat.format(getString(key), new String[] { arg1 });
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime first argument to replace in key value
+ * @param arg2
+ * runtime second argument to replace in key value
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key, String arg1, String arg2) {
+ return MessageFormat
+ .format(getString(key), new String[] { arg1, arg2 });
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime argument to replace in key value
+ * @param arg2
+ * runtime second argument to replace in key value
+ * @param arg3
+ * runtime third argument to replace in key value
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key, String arg1, String arg2,
+ String arg3) {
+ return MessageFormat.format(getString(key), new String[] { arg1, arg2,
+ arg3 });
+ }
+
+ /**
+ * Returns the plugin's resource bundle.
+ *
+ * @return resource bundle
+ */
+ protected ResourceBundle getResourceBundle() {
+ return resourceBundle;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
new file mode 100644
index 00000000..af681415
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+
+public class Logger {
+
+ public static void logInfo(String message) {
+ log(IStatus.INFO, IStatus.OK, message, null);
+ }
+
+ public static void logError(Throwable exception) {
+ logError("Unexpected Exception", exception);
+ }
+
+ public static void logError(String message, Throwable exception) {
+ log(IStatus.ERROR, IStatus.OK, message, exception);
+ }
+
+ public static void log(int severity, int code, String message,
+ Throwable exception) {
+ log(createStatus(severity, code, message, exception));
+ }
+
+ public static IStatus createStatus(int severity, int code, String message,
+ Throwable exception) {
+ return new Status(severity, Activator.PLUGIN_ID, code, message,
+ exception);
+ }
+
+ public static void log(IStatus status) {
+ Activator.getDefault().getLog().log(status);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
new file mode 100644
index 00000000..d8a77ebb
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
@@ -0,0 +1,60 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.extensions;
+
+import java.io.Serializable;
+
+import org.eclipse.core.resources.IFile;
+
+/**
+ * Describes a text fragment within a source resource.
+ *
+ * @author Martin Reiterer
+ */
+public interface ILocation {
+
+ /**
+ * Returns the source resource's physical location.
+ *
+ * @return The file within the text fragment is located
+ */
+ public IFile getFile();
+
+ /**
+ * Returns the position of the text fragments starting character.
+ *
+ * @return The position of the first character
+ */
+ public int getStartPos();
+
+ /**
+ * Returns the position of the text fragments last character.
+ *
+ * @return The position of the last character
+ */
+ public int getEndPos();
+
+ /**
+ * Returns the text fragment.
+ *
+ * @return The text fragment
+ */
+ public String getLiteral();
+
+ /**
+ * Returns additional metadata. The type and content of this property is not
+ * specified and can be used to marshal additional data for the computation
+ * of resolution proposals.
+ *
+ * @return The metadata associated with the text fragment
+ */
+ public Serializable getData();
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
new file mode 100644
index 00000000..b5a62072
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
@@ -0,0 +1,21 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.extensions;
+
+public interface IMarkerConstants {
+ public static final int CAUSE_BROKEN_REFERENCE = 0;
+ public static final int CAUSE_CONSTANT_LITERAL = 1;
+ public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
+
+ public static final int CAUSE_UNSPEZIFIED_KEY = 3;
+ public static final int CAUSE_SAME_VALUE = 4;
+ public static final int CAUSE_MISSING_LANGUAGE = 5;
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
new file mode 100644
index 00000000..a13886a6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+
+public interface IResourceBundleChangedListener {
+
+ public void resourceBundleChanged(ResourceBundleChangedEvent event);
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
new file mode 100644
index 00000000..7a9b5b00
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model;
+
+public interface IResourceDescriptor {
+
+ public void setProjectName(String projName);
+
+ public void setRelativePath(String relPath);
+
+ public void setAbsolutePath(String absPath);
+
+ public void setBundleId(String bundleId);
+
+ public String getProjectName();
+
+ public String getRelativePath();
+
+ public String getAbsolutePath();
+
+ public String getBundleId();
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
new file mode 100644
index 00000000..09ac533d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+
+public interface IResourceExclusionListener {
+
+ public void exclusionChanged(ResourceExclusionEvent event);
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
new file mode 100644
index 00000000..9492ce65
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model;
+
+import org.eclipse.core.resources.IResource;
+
+public class ResourceDescriptor implements IResourceDescriptor {
+
+ private String projectName;
+ private String relativePath;
+ private String absolutePath;
+ private String bundleId;
+
+ public ResourceDescriptor(IResource resource) {
+ projectName = resource.getProject().getName();
+ relativePath = resource.getProjectRelativePath().toString();
+ absolutePath = resource.getRawLocation().toString();
+ }
+
+ public ResourceDescriptor() {
+ }
+
+ @Override
+ public String getAbsolutePath() {
+ return absolutePath;
+ }
+
+ @Override
+ public String getProjectName() {
+ return projectName;
+ }
+
+ @Override
+ public String getRelativePath() {
+ return relativePath;
+ }
+
+ @Override
+ public int hashCode() {
+ return projectName.hashCode() + relativePath.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof ResourceDescriptor))
+ return false;
+
+ return absolutePath.equals(absolutePath);
+ }
+
+ @Override
+ public void setAbsolutePath(String absPath) {
+ this.absolutePath = absPath;
+ }
+
+ @Override
+ public void setProjectName(String projName) {
+ this.projectName = projName;
+ }
+
+ @Override
+ public void setRelativePath(String relPath) {
+ this.relativePath = relPath;
+ }
+
+ @Override
+ public String getBundleId() {
+ return this.bundleId;
+ }
+
+ @Override
+ public void setBundleId(String bundleId) {
+ this.bundleId = bundleId;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
new file mode 100644
index 00000000..1afbb963
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+public class SLLocation implements Serializable, ILocation {
+
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
+
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
+
+ public IFile getFile() {
+ return file;
+ }
+
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+
+ public int getStartPos() {
+ return startPos;
+ }
+
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+
+ public int getEndPos() {
+ return endPos;
+ }
+
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+
+ public String getLiteral() {
+ return literal;
+ }
+
+ public Serializable getData() {
+ return data;
+ }
+
+ public void setData(Serializable data) {
+ this.data = data;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
new file mode 100644
index 00000000..beb7436b
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
@@ -0,0 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model.exception;
+
+public class NoSuchResourceAuditorException extends Exception {
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
new file mode 100644
index 00000000..40331555
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model.exception;
+
+public class ResourceBundleException extends Exception {
+
+ private static final long serialVersionUID = -2039182473628481126L;
+
+ public ResourceBundleException(String msg) {
+ super(msg);
+ }
+
+ public ResourceBundleException() {
+ super();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java
new file mode 100644
index 00000000..c900c924
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Alexej Strelzow - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.manager;
+
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.IResourceDescriptor;
+
+/**
+ * Interface for state loading.
+ *
+ * @author Alexej Strelzow
+ */
+public interface IStateLoader {
+
+ /**
+ * Loads the state from a xml-file
+ */
+ void loadState();
+
+ /**
+ * Stores the state into a xml-file
+ */
+ void saveState();
+
+ /**
+ * @return The excluded resources
+ */
+ Set<IResourceDescriptor> getExcludedResources();
+}
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
new file mode 100644
index 00000000..d1344cf2
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
@@ -0,0 +1,56 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model.manager;
+
+import org.eclipse.core.resources.IProject;
+
+public class ResourceBundleChangedEvent {
+
+ public final static int ADDED = 0;
+ public final static int DELETED = 1;
+ public final static int MODIFIED = 2;
+ public final static int EXCLUDED = 3;
+ public final static int INCLUDED = 4;
+
+ private IProject project;
+ private String bundle = "";
+ private int type = -1;
+
+ public ResourceBundleChangedEvent(int type, String bundle, IProject project) {
+ this.type = type;
+ this.bundle = bundle;
+ this.project = project;
+ }
+
+ public IProject getProject() {
+ return project;
+ }
+
+ public void setProject(IProject project) {
+ this.project = project;
+ }
+
+ public String getBundle() {
+ return bundle;
+ }
+
+ public void setBundle(String bundle) {
+ this.bundle = bundle;
+ }
+
+ public int getType() {
+ return type;
+ }
+
+ public void setType(int type) {
+ this.type = type;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java
new file mode 100644
index 00000000..7bae005b
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java
@@ -0,0 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model.manager;
+
+public class ResourceBundleDetector {
+
+}
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
new file mode 100644
index 00000000..35611b04
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.model.manager;
+
+import java.util.Collection;
+
+public class ResourceExclusionEvent {
+
+ private Collection<Object> changedResources;
+
+ public ResourceExclusionEvent(Collection<Object> changedResources) {
+ super();
+ this.changedResources = changedResources;
+ }
+
+ public void setChangedResources(Collection<Object> changedResources) {
+ this.changedResources = changedResources;
+ }
+
+ public Collection<Object> getChangedResources() {
+ return changedResources;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
new file mode 100644
index 00000000..dfbe4097
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * 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)
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.text.MessageFormat;
+
+import org.eclipse.core.resources.IMarker;
+
+public class EditorUtils {
+
+ /** Marker constants **/
+ public static final String MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ui.StringLiteralAuditMarker";
+ public static final String RB_MARKER_ID = "org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleAuditMarker";
+
+ /** Error messages **/
+ public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
+ public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
+ public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
+
+ public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
+ public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
+ public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
+
+ public static String getFormattedMessage(String pattern, Object[] arguments) {
+ String formattedMessage = "";
+
+ MessageFormat formatter = new MessageFormat(pattern);
+ formattedMessage = formatter.format(arguments);
+
+ return formattedMessage;
+ }
+
+ public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add) {
+ IMarker[] old_ms = ms;
+ ms = new IMarker[old_ms.length + ms_to_add.length];
+
+ System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
+ System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
+
+ return ms;
+ }
+
+}
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
new file mode 100644
index 00000000..3e3d9319
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Matthias Lettmayer - improved readFileAsString() to use Apache Commons IO (fixed issue 74)
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.core.internal.resources.ResourceException;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.OperationCanceledException;
+
+public class FileUtils {
+
+ public static String readFile(IResource resource) {
+ return readFileAsString(resource.getRawLocation().toFile());
+ }
+
+ protected static String readFileAsString(File filePath) {
+ String content = "";
+
+ try {
+ content = org.apache.commons.io.FileUtils
+ .readFileToString(filePath);
+ } catch (IOException e) {
+ Logger.logError(e);
+ }
+
+ return content;
+ }
+
+ public static File getRBManagerStateFile() {
+ return Activator.getDefault().getStateLocation()
+ .append("internationalization.xml").toFile();
+ }
+
+ /**
+ * Don't use that -> causes {@link ResourceException} -> because File out of
+ * sync
+ *
+ * @param file
+ * @param editorContent
+ * @throws CoreException
+ * @throws OperationCanceledException
+ */
+ public synchronized void saveTextFile(IFile file, String editorContent)
+ throws CoreException, OperationCanceledException {
+ try {
+ file.setContents(
+ new ByteArrayInputStream(editorContent.getBytes()), false,
+ true, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
new file mode 100644
index 00000000..5e5038fa
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.util;
+
+import java.util.List;
+
+import org.eclipse.babel.core.util.PDEUtils;
+import org.eclipse.core.resources.IProject;
+
+public class FragmentProjectUtils {
+
+ public static String getPluginId(IProject project) {
+ return PDEUtils.getPluginId(project);
+ }
+
+ public static IProject[] lookupFragment(IProject pluginProject) {
+ return PDEUtils.lookupFragment(pluginProject);
+ }
+
+ public static boolean isFragment(IProject pluginProject) {
+ return PDEUtils.isFragment(pluginProject);
+ }
+
+ public static List<IProject> getFragments(IProject hostProject) {
+ return PDEUtils.getFragments(hostProject);
+ }
+
+ public static String getFragmentId(IProject project, String hostPluginId) {
+ return PDEUtils.getFragmentId(project, hostPluginId);
+ }
+
+ public static IProject getFragmentHost(IProject fragment) {
+ return PDEUtils.getFragmentHost(fragment);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
new file mode 100644
index 00000000..e824855e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import org.eclipse.jface.resource.CompositeImageDescriptor;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.ImageData;
+import org.eclipse.swt.graphics.Point;
+
+public class OverlayIcon extends CompositeImageDescriptor {
+
+ public static final int TOP_LEFT = 0;
+ public static final int TOP_RIGHT = 1;
+ public static final int BOTTOM_LEFT = 2;
+ public static final int BOTTOM_RIGHT = 3;
+
+ private Image img;
+ private Image overlay;
+ private int location;
+ private Point imgSize;
+
+ public OverlayIcon(Image baseImage, Image overlayImage, int location) {
+ super();
+ this.img = baseImage;
+ this.overlay = overlayImage;
+ this.location = location;
+ this.imgSize = new Point(baseImage.getImageData().width,
+ baseImage.getImageData().height);
+ }
+
+ @Override
+ protected void drawCompositeImage(int width, int height) {
+ drawImage(img.getImageData(), 0, 0);
+ ImageData imageData = overlay.getImageData();
+
+ switch (location) {
+ case TOP_LEFT:
+ drawImage(imageData, 0, 0);
+ break;
+ case TOP_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, 0);
+ break;
+ case BOTTOM_LEFT:
+ drawImage(imageData, 0, imgSize.y - imageData.height);
+ break;
+ case BOTTOM_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, imgSize.y
+ - imageData.height);
+ break;
+ }
+ }
+
+ @Override
+ protected Point getSize() {
+ return new Point(img.getImageData().width, img.getImageData().height);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java
new file mode 100644
index 00000000..c268c8c4
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java
@@ -0,0 +1,347 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
new file mode 100644
index 00000000..b8873ceb
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Michael Gasser - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.action.Action;
+
+public class RBFileUtils extends Action {
+ 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;
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.feature/.project b/org.eclipse.babel.tapiji.tools.feature/.project
similarity index 100%
rename from org.eclipselabs.tapiji.tools.feature/.project
rename to org.eclipse.babel.tapiji.tools.feature/.project
diff --git a/org.eclipselabs.tapiji.tools.feature/build.properties b/org.eclipse.babel.tapiji.tools.feature/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.tools.feature/build.properties
rename to org.eclipse.babel.tapiji.tools.feature/build.properties
diff --git a/org.eclipselabs.tapiji.tools.feature/epl-v10.html b/org.eclipse.babel.tapiji.tools.feature/epl-v10.html
similarity index 100%
rename from org.eclipselabs.tapiji.tools.feature/epl-v10.html
rename to org.eclipse.babel.tapiji.tools.feature/epl-v10.html
diff --git a/org.eclipselabs.tapiji.tools.feature/feature.xml b/org.eclipse.babel.tapiji.tools.feature/feature.xml
similarity index 98%
rename from org.eclipselabs.tapiji.tools.feature/feature.xml
rename to org.eclipse.babel.tapiji.tools.feature/feature.xml
index c1fe149a..e8346026 100644
--- a/org.eclipselabs.tapiji.tools.feature/feature.xml
+++ b/org.eclipse.babel.tapiji.tools.feature/feature.xml
@@ -137,28 +137,28 @@ This Agreement is governed by the laws of the State of New York and the intellec
</requires>
<plugin
- id="org.eclipselabs.tapiji.tools.core"
+ id="org.eclipse.babel.tapiji.tools.core"
download-size="0"
install-size="0"
version="0.0.2.qualifier"
unpack="false"/>
<plugin
- id="org.eclipselabs.tapiji.tools.java"
+ id="org.eclipse.babel.tapiji.tools.java"
download-size="0"
install-size="0"
version="0.0.2.qualifier"
unpack="false"/>
<plugin
- id="org.eclipselabs.tapiji.translator.rbe"
+ id="org.eclipse.babel.tapiji.translator.rbe"
download-size="0"
install-size="0"
version="0.0.2.qualifier"
unpack="false"/>
<plugin
- id="org.eclipselabs.tapiji.tools.rbmanager"
+ id="org.eclipse.babel.tapiji.tools.rbmanager"
download-size="0"
install-size="0"
version="0.0.2.qualifier"
diff --git a/org.eclipselabs.tapiji.tools.java/.classpath b/org.eclipse.babel.tapiji.tools.java.ui/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.tools.java/.classpath
rename to org.eclipse.babel.tapiji.tools.java.ui/.classpath
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/.project b/org.eclipse.babel.tapiji.tools.java.ui/.project
new file mode 100644
index 00000000..fc555eb9
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.tapiji.tools.java.ui</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.tools.java.ui/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.tapiji.tools.java.ui/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..466dfa53
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF
@@ -0,0 +1,31 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: TapiJI Tools Java UI contribution
+Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.java.ui;singleton:=true
+Bundle-Version: 0.0.2.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.eclipse.core.resources;bundle-version="3.6.0",
+ org.eclipse.core.runtime;bundle-version="3.6.0",
+ org.eclipse.jdt.ui;bundle-version="3.6.0",
+ org.eclipse.jface,
+ org.eclipse.babel.tapiji.tools.core.ui;bundle-version="0.0.2",
+ org.eclipse.babel.tapiji.tools.java;bundle-version="0.0.2",
+ org.eclipse.jdt.core
+Import-Package: org.eclipse.core.filebuffers,
+ org.eclipse.jface.dialogs,
+ org.eclipse.jface.text,
+ org.eclipse.jface.text.contentassist,
+ org.eclipse.jface.text.source,
+ org.eclipse.jface.wizard,
+ org.eclipse.swt.graphics,
+ org.eclipse.swt.widgets,
+ org.eclipse.text.edits,
+ org.eclipse.ui,
+ org.eclipse.ui.part,
+ org.eclipse.ui.progress,
+ org.eclipse.ui.texteditor,
+ org.eclipse.ui.wizards
+Bundle-Vendor: Vienna University of Technology
+Export-Package: org.eclipse.babel.tapiji.tools.java.ui.util
+
+
diff --git a/org.eclipselabs.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java.ui/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.tools.java/build.properties
rename to org.eclipse.babel.tapiji.tools.java.ui/build.properties
diff --git a/org.eclipselabs.tapiji.tools.java/epl-v10.html b/org.eclipse.babel.tapiji.tools.java.ui/epl-v10.html
similarity index 100%
rename from org.eclipselabs.tapiji.tools.java/epl-v10.html
rename to org.eclipse.babel.tapiji.tools.java.ui/epl-v10.html
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml
new file mode 100644
index 00000000..4e8e6b97
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+ <extension
+ point="org.eclipse.babel.tapiji.tools.core.builderExtension">
+ <i18nResourceAuditor
+ class="org.eclipse.babel.tapiji.tools.java.ui.JavaResourceAuditor">
+ </i18nResourceAuditor>
+ </extension>
+ <extension
+ point="org.eclipse.jdt.ui.javaEditorTextHovers">
+ <hover
+ activate="true"
+ class="org.eclipse.babel.tapiji.tools.java.ui.ConstantStringHover"
+ description="hovers constant strings"
+ id="org.eclipse.babel.tapiji.tools.java.ui.ConstantStringHover"
+ label="Constant Strings">
+ </hover>
+ </extension>
+ <extension
+ id="org.eclipse.babel.tapiji.tools.java.ui.MessageCompletionProcessor"
+ name="org.eclipse.babel.tapiji.tools.java.ui.MessageCompletionProcessor"
+ point="org.eclipse.jdt.ui.javaCompletionProposalComputer">
+ <javaCompletionProposalComputer
+ activate="true"
+ categoryId="org.eclipse.jdt.ui.defaultProposalCategory"
+ class="org.eclipse.babel.tapiji.tools.java.ui.MessageCompletionProposalComputer">
+ <partition
+ type="__java_string">
+ </partition>
+ <partition
+ type="__dftl_partition_content_type">
+ </partition>
+ </javaCompletionProposalComputer>
+
+ </extension>
+</plugin>
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
new file mode 100644
index 00000000..c3e5e692
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
@@ -0,0 +1,94 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.babel.tapiji.tools.java.visitor.ResourceAuditVisitor;
+import org.eclipse.jdt.core.ITypeRoot;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.ui.IEditorPart;
+
+public class ConstantStringHover implements IJavaEditorTextHover {
+
+ IEditorPart editor = null;
+ ResourceAuditVisitor csf = null;
+ ResourceBundleManager manager = null;
+
+ @Override
+ public void setEditor(IEditorPart editor) {
+ this.editor = editor;
+ initConstantStringAuditor();
+ }
+
+ protected void initConstantStringAuditor() {
+ // parse editor content and extract resource-bundle access strings
+
+ // get the type of the currently loaded resource
+ ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
+ .getEditorInput());
+
+ if (typeRoot == null) {
+ return;
+ }
+
+ CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot);
+
+ if (cu == null) {
+ return;
+ }
+
+ manager = ResourceBundleManager.getManager(cu.getJavaElement()
+ .getResource().getProject());
+
+ // determine the element at the position of the cursur
+ csf = new ResourceAuditVisitor(null, manager.getProject().getName());
+ cu.accept(csf);
+ }
+
+ @Override
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+ initConstantStringAuditor();
+ if (hoverRegion == null) {
+ return null;
+ }
+
+ // get region for string literals
+ hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset());
+
+ if (hoverRegion == null) {
+ return null;
+ }
+
+ String bundleName = csf.getBundleReference(hoverRegion);
+ String key = csf.getKeyAt(hoverRegion);
+
+ String hoverText = manager.getKeyHoverString(bundleName, key);
+ if (hoverText == null || hoverText.equals("")) {
+ return null;
+ } else {
+ return hoverText;
+ }
+ }
+
+ @Override
+ public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
+ if (editor == null) {
+ return null;
+ }
+
+ // Retrieve the property key at this position. Otherwise, null is
+ // returned.
+ return csf.getKeyAt(Long.valueOf(offset));
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.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
new file mode 100644
index 00000000..db3864da
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java
@@ -0,0 +1,162 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.SLLocation;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundle;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.IncludeResource;
+import org.eclipse.babel.tapiji.tools.java.ui.quickfix.ExcludeResourceFromInternationalization;
+import org.eclipse.babel.tapiji.tools.java.ui.quickfix.ExportToResourceBundleResolution;
+import org.eclipse.babel.tapiji.tools.java.ui.quickfix.IgnoreStringFromInternationalization;
+import org.eclipse.babel.tapiji.tools.java.ui.quickfix.ReplaceResourceBundleDefReference;
+import org.eclipse.babel.tapiji.tools.java.ui.quickfix.ReplaceResourceBundleReference;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.babel.tapiji.tools.java.visitor.ResourceAuditVisitor;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.ui.IMarkerResolution;
+
+public class JavaResourceAuditor extends I18nResourceAuditor {
+
+ protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>();
+ protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>();
+ protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>();
+
+ @Override
+ public String[] getFileEndings() {
+ return new String[] { "java" };
+ }
+
+ @Override
+ public void audit(IResource resource) {
+
+ ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
+ .getProject().getFile(resource.getProjectRelativePath()),
+ resource.getProject().getName());
+
+ // get a reference to the shared AST of the loaded CompilationUnit
+ CompilationUnit cu = 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 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));
+ }
+ 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
new file mode 100644
index 00000000..fff6d5b6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
@@ -0,0 +1,265 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.InsertResourceBundleReferenceProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.MessageCompletionProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NewResourceBundleEntryProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NoActionProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.babel.tapiji.tools.java.visitor.ResourceAuditVisitor;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jdt.core.CompletionContext;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.StringLiteral;
+import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer;
+import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+
+public class MessageCompletionProposalComputer implements
+ IJavaCompletionProposalComputer {
+
+ private ResourceAuditVisitor csav;
+ private IResource resource;
+ private CompilationUnit cu;
+ private ResourceBundleManager manager;
+
+ public MessageCompletionProposalComputer() {
+
+ }
+
+ @Override
+ public List<ICompletionProposal> computeCompletionProposals(
+ ContentAssistInvocationContext context, IProgressMonitor monitor) {
+
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+
+ if (!InternationalizationNature
+ .hasNature(((JavaContentAssistInvocationContext) context)
+ .getCompilationUnit().getResource().getProject())) {
+ return completions;
+ }
+
+ try {
+ JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
+ CompletionContext coreContext = javaContext.getCoreContext();
+
+ int tokenStart = coreContext.getTokenStart();
+ int tokenEnd = coreContext.getTokenEnd();
+ int tokenOffset = coreContext.getOffset();
+ boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;
+
+ if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
+ && (tokenEnd + 1) - tokenStart > 0) {
+ return completions;
+ }
+
+ if (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;
+ }
+
+ private Collection<ICompletionProposal> getRBReferenceCompletionProposals(
+ int tokenStart, int tokenEnd, String fullToken,
+ boolean isStringLiteral, ResourceBundleManager manager,
+ IResource resource) {
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ boolean hit = false;
+
+ // Show a list of available resource bundles
+ List<String> resourceBundles = manager.getResourceBundleIdentifiers();
+ for (String rbName : resourceBundles) {
+ if (rbName.startsWith(fullToken)) {
+ if (rbName.equals(fullToken)) {
+ hit = true;
+ } else {
+ completions.add(new MessageCompletionProposal(tokenStart,
+ tokenEnd - tokenStart, rbName, true));
+ }
+ }
+ }
+
+ if (!hit && fullToken.trim().length() > 0) {
+ completions.add(new CreateResourceBundleProposal(fullToken,
+ resource, tokenStart, tokenEnd));
+ }
+
+ return completions;
+ }
+
+ protected List<ICompletionProposal> getBasicJavaCompletionProposals(
+ int tokenStart, int tokenEnd, int tokenOffset, String fullToken,
+ boolean isStringLiteral, ResourceBundleManager manager,
+ ResourceAuditVisitor csav, IResource resource) {
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+
+ if (fullToken.length() == 0) {
+ // If nothing has been entered
+ completions.add(new InsertResourceBundleReferenceProposal(
+ tokenStart, tokenEnd - tokenStart, manager.getProject()
+ .getName(), resource, csav
+ .getDefinedResourceBundles(tokenOffset)));
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, false,
+ manager.getProject().getName(), null));
+ } else {
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, false,
+ manager.getProject().getName(), null));
+ }
+ return completions;
+ }
+
+ protected List<ICompletionProposal> getResourceBundleCompletionProposals(
+ int tokenStart, int tokenEnd, int tokenOffset,
+ boolean isStringLiteral, String fullToken,
+ ResourceBundleManager manager, ResourceAuditVisitor csav,
+ IResource resource) {
+
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ IRegion region = csav.getKeyAt(new Long(tokenOffset));
+ String bundleName = csav.getBundleReference(region);
+ IMessagesBundleGroup bundleGroup = manager
+ .getResourceBundle(bundleName);
+
+ if (fullToken.length() > 0) {
+ boolean hit = false;
+ // If a part of a String has already been entered
+ for (String key : bundleGroup.getMessageKeys()) {
+ if (key.toLowerCase().startsWith(fullToken)) {
+ if (!key.equals(fullToken)) {
+ completions.add(new MessageCompletionProposal(
+ tokenStart, tokenEnd - tokenStart, key, false));
+ } else {
+ hit = true;
+ }
+ }
+ }
+ if (!hit) {
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, true,
+ manager.getProject().getName(), bundleName));
+
+ // TODO: reference to existing resource
+ }
+ } else {
+ for (String key : bundleGroup.getMessageKeys()) {
+ completions.add(new MessageCompletionProposal(tokenStart,
+ tokenEnd - tokenStart, key, false));
+ }
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, true,
+ manager.getProject().getName(), bundleName));
+
+ }
+ return completions;
+ }
+
+ @Override
+ public 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
new file mode 100644
index 00000000..c6f5b402
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
@@ -0,0 +1,228 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.babel.editor.wizards.IResourceBundleWizard;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.wizards.IWizardDescriptor;
+
+public class CreateResourceBundleProposal implements IJavaCompletionProposal {
+
+ private IResource resource;
+ private int start;
+ private int end;
+ private String key;
+ private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
+
+ public CreateResourceBundleProposal(String key, IResource resource,
+ int start, int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
+ }
+
+ public String getDescription() {
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
+ }
+
+ public String getLabel() {
+ return "Create Resource-Bundle '" + key + "'";
+ }
+
+ @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);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
+
+ if (!(wizard instanceof IResourceBundleWizard)) {
+ return;
+ }
+
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
+
+ rbw.setBundleId(rbName);
+
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
+
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
+
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+
+ rbw.setDefaultPath(pathName);
+
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
+
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ 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) {
+ }
+ }
+ }
+ }
+ } 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
new file mode 100644
index 00000000..cc00eb45
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
@@ -0,0 +1,101 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import java.util.Collection;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+public class InsertResourceBundleReferenceProposal implements
+ IJavaCompletionProposal {
+
+ private int offset = 0;
+ private int length = 0;
+ private IResource resource;
+ private String reference;
+ private String projectName;
+
+ public InsertResourceBundleReferenceProposal(int offset, int length,
+ String projectName, IResource resource,
+ Collection<String> availableBundles) {
+ this.offset = offset;
+ this.length = length;
+ this.resource = resource;
+ this.projectName = projectName;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+ dialog.setProjectName(projectName);
+
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
+
+ reference = 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
new file mode 100644
index 00000000..75ecf676
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+
+public class MessageCompletionProposal implements IJavaCompletionProposal {
+
+ private int offset = 0;
+ private int length = 0;
+ private String content = "";
+ private boolean messageAccessor = false;
+
+ public MessageCompletionProposal(int offset, int length, String content,
+ boolean messageAccessor) {
+ this.offset = offset;
+ this.length = length;
+ this.content = content;
+ this.messageAccessor = messageAccessor;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ try {
+ document.replace(offset, length, content);
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ return "Inserts the resource key '" + this.content + "'";
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ return content;
+ }
+
+ @Override
+ public Image getImage() {
+ if (messageAccessor)
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ return new Point(offset + content.length() + 1, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ return 99;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.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
new file mode 100644
index 00000000..3cbe372e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -0,0 +1,138 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
+
+ private int startPos;
+ private int endPos;
+ private String value;
+ private boolean bundleContext;
+ private String projectName;
+ private IResource resource;
+ private String bundleName;
+ private String reference;
+
+ public NewResourceBundleEntryProposal(IResource resource, int startPos,
+ int endPos, String value, boolean isStringLiteral,
+ boolean bundleContext, String projectName, String bundleName) {
+
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.value = value;
+ this.bundleContext = bundleContext;
+ this.projectName = projectName;
+ this.resource = resource;
+ this.bundleName = bundleName;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(bundleContext ? value : "");
+ config.setPreselectedMessage(value);
+ config.setPreselectedBundle(bundleName == null ? "" : bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedKey();
+
+ try {
+ if (!bundleContext) {
+ reference = 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 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
new file mode 100644
index 00000000..f16c4cd6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+
+public class NoActionProposal implements IJavaCompletionProposal {
+
+ public NoActionProposal() {
+ super();
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ // TODO Auto-generated method stub
+ return "No Default Proposals";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ return 100;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.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
new file mode 100644
index 00000000..2961808c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.jdt.ui.text.java.AbstractProposalSorter;
+import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+
+public class Sorter extends AbstractProposalSorter {
+
+ public Sorter() {
+ }
+
+ @Override
+ public void beginSorting(ContentAssistInvocationContext context) {
+ // TODO Auto-generated method stub
+ super.beginSorting(context);
+ }
+
+ @Override
+ public int compare(ICompletionProposal prop1, ICompletionProposal prop2) {
+ return getIndex(prop1) - getIndex(prop2);
+ }
+
+ protected int getIndex(ICompletionProposal prop) {
+ if (prop instanceof NoActionProposal) {
+ return 1;
+ } else if (prop instanceof MessageCompletionProposal) {
+ return 2;
+ } else if (prop instanceof InsertResourceBundleReferenceProposal) {
+ return 3;
+ } else if (prop instanceof NewResourceBundleEntryProposal) {
+ return 4;
+ } else {
+ return 0;
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.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
new file mode 100644
index 00000000..3fb44e82
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.model;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+public class SLLocation implements Serializable, ILocation {
+
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
+
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
+
+ @Override
+ public IFile getFile() {
+ return file;
+ }
+
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+
+ @Override
+ public int getStartPos() {
+ return startPos;
+ }
+
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+
+ @Override
+ public int getEndPos() {
+ return endPos;
+ }
+
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+
+ @Override
+ public String getLiteral() {
+ return literal;
+ }
+
+ @Override
+ public Serializable getData() {
+ return 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
new file mode 100644
index 00000000..1b394ed4
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.progress.IProgressService;
+
+public class ExcludeResourceFromInternationalization implements
+ IMarkerResolution2 {
+
+ @Override
+ public String getLabel() {
+ return "Exclude Resource";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ final IResource resource = marker.getResource();
+
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
+
+ ResourceBundleManager manager = null;
+ pm.beginTask(
+ "Excluding Resource from Internationalization", 1);
+
+ if (manager == null
+ || (manager.getProject() != resource.getProject()))
+ manager = ResourceBundleManager.getManager(resource
+ .getProject());
+ manager.excludeResource(resource, pm);
+ pm.worked(1);
+ pm.done();
+ }
+ });
+ } catch (Exception e) {
+ }
+ }
+
+ @Override
+ public String getDescription() {
+ return "Exclude Resource from Internationalization";
+ }
+
+ @Override
+ public Image getImage() {
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
new file mode 100644
index 00000000..a325404b
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class ExportToResourceBundleResolution implements IMarkerResolution2 {
+
+ public ExportToResourceBundleResolution() {
+ }
+
+ @Override
+ public String getDescription() {
+ return "Export constant string literal to a resource bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Export to Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey("");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle((startPos + 1 < document.getLength() && endPos > 1) ? document
+ .get(startPos + 1, endPos - 2) : "");
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ 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
new file mode 100644
index 00000000..6cf88284
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.java.ui.util.ASTutilsUI;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class IgnoreStringFromInternationalization implements IMarkerResolution2 {
+
+ @Override
+ public String getLabel() {
+ return "Ignore String";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ IResource resource = marker.getResource();
+
+ CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource);
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ int position = marker.getAttribute(IMarker.CHAR_START, 0);
+
+ ASTutils.createReplaceNonInternationalisationComment(cu, document,
+ position);
+ textFileBuffer.commit(null, false);
+
+ } catch (JavaModelException e) {
+ Logger.logError(e);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Ignore String from Internationalization";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
new file mode 100644
index 00000000..5cc5bd0f
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
@@ -0,0 +1,94 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
+
+ private String key;
+ private int start;
+ private int end;
+
+ public ReplaceResourceBundleDefReference(String key, int start, int end) {
+ this.key = key;
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle reference '" + key
+ + "' with a reference to an already existing Resource-Bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select an alternative Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = start;
+ int endPos = end - start;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(
+ Display.getDefault().getActiveShell(),
+ resource.getProject());
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ key = dialog.getSelectedBundleId();
+ int iSep = key.lastIndexOf("/");
+ key = iSep != -1 ? key.substring(iSep + 1) : key;
+
+ document.replace(startPos, endPos, "\"" + key + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
new file mode 100644
index 00000000..f75cf058
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.quickfix;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class ReplaceResourceBundleReference implements IMarkerResolution2 {
+
+ private String key;
+ private String bundleId;
+
+ public ReplaceResourceBundleReference(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle key '"
+ + key
+ + "' with a reference to an already existing localized string literal.";
+ }
+
+ @Override
+ public Image getImage() {
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select alternative Resource-Bundle entry";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(
+ path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+
+ dialog.setProjectName(resource.getProject().getName());
+ dialog.setBundleName(bundleId);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
+
+ document.replace(startPos, endPos, "\"" + key + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
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
new file mode 100644
index 00000000..8b96bc7d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java
@@ -0,0 +1,150 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - seperation of ui/non-ui (methods moved from ASTUtils)
+ ******************************************************************************/
+
+package org.eclipse.babel.tapiji.tools.java.ui.util;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.core.ICompilationUnit;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.ITypeRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.ui.SharedASTProvider;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+
+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);
+
+ 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);
+
+ 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;
+ }
+
+ 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/.classpath b/org.eclipse.babel.tapiji.tools.java/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipse.babel.tapiji.tools.java/.project b/org.eclipse.babel.tapiji.tools.java/.project
new file mode 100644
index 00000000..72635d93
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.tapiji.tools.java</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipse.babel.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..c537b630
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..8f20432e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF
@@ -0,0 +1,21 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: TapiJI Tools Java extension
+Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.java
+Bundle-Version: 0.0.2.qualifier
+Bundle-Vendor: Vienna University of Technology
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.babel.tapiji.tools.java.util,
+ org.eclipse.babel.tapiji.tools.java.visitor
+Import-Package: org.eclipse.babel.tapiji.tools.core.model.manager,
+ org.eclipse.core.filebuffers,
+ org.eclipse.core.resources,
+ org.eclipse.jdt.ui,
+ org.eclipse.jface.text,
+ org.eclipse.text.edits,
+ org.eclipse.ui
+Require-Bundle: org.eclipse.core.resources,
+ org.eclipse.jdt.core,
+ org.eclipse.core.runtime,
+ org.eclipse.jface,
+ org.eclipse.babel.tapiji.tools.core.ui;bundle-version="0.0.2"
diff --git a/org.eclipse.babel.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java/build.properties
new file mode 100644
index 00000000..e9863e28
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/build.properties
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml
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
new file mode 100644
index 00000000..7d912328
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
@@ -0,0 +1,943 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ * Alexej Strelzow - seperation of ui/non-ui
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.util;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.SLLocation;
+import org.eclipse.babel.tapiji.tools.java.visitor.MethodParameterDescriptor;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.core.ICompilationUnit;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.AST;
+import org.eclipse.jdt.core.dom.ASTNode;
+import org.eclipse.jdt.core.dom.ASTParser;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.ExpressionStatement;
+import org.eclipse.jdt.core.dom.FieldDeclaration;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.IVariableBinding;
+import org.eclipse.jdt.core.dom.ImportDeclaration;
+import org.eclipse.jdt.core.dom.MethodDeclaration;
+import org.eclipse.jdt.core.dom.MethodInvocation;
+import org.eclipse.jdt.core.dom.Modifier;
+import org.eclipse.jdt.core.dom.SimpleName;
+import org.eclipse.jdt.core.dom.SimpleType;
+import org.eclipse.jdt.core.dom.StringLiteral;
+import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
+import org.eclipse.jdt.core.dom.TypeDeclaration;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
+import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.text.edits.TextEdit;
+
+public class ASTutils {
+
+ private static MethodParameterDescriptor rbDefinition;
+ private static MethodParameterDescriptor rbAccessor;
+
+ public static MethodParameterDescriptor getRBDefinitionDesc() {
+ if (rbDefinition == null) {
+ // Init descriptor for Resource-Bundle-Definition
+ List<String> definition = new ArrayList<String>();
+ definition.add("getBundle");
+ rbDefinition = new MethodParameterDescriptor(definition,
+ "java.util.ResourceBundle", true, 0);
+ }
+
+ return rbDefinition;
+ }
+
+ public static MethodParameterDescriptor getRBAccessorDesc() {
+ if (rbAccessor == null) {
+ // Init descriptor for Resource-Bundle-Accessors
+ List<String> accessors = new ArrayList<String>();
+ accessors.add("getString");
+ accessors.add("getStringArray");
+ rbAccessor = new MethodParameterDescriptor(accessors,
+ "java.util.ResourceBundle", true, 0);
+ }
+
+ return rbAccessor;
+ }
+
+ public static String resolveRBReferenceVar(IDocument document,
+ IResource resource, int pos, final String bundleId,
+ CompilationUnit cu) {
+ String bundleVar;
+
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
+ TypeDeclaration td = typeFinder.getEnclosingType();
+ MethodDeclaration meth = typeFinder.getEnclosingMethod();
+
+ if (atd == null) {
+ BundleDeclarationFinder bdf = new BundleDeclarationFinder(
+ bundleId,
+ td,
+ meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+ td.accept(bdf);
+
+ bundleVar = bdf.getVariableName();
+ } else {
+ BundleDeclarationFinder bdf = new BundleDeclarationFinder(
+ bundleId,
+ atd,
+ meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+ atd.accept(bdf);
+
+ bundleVar = bdf.getVariableName();
+ }
+
+ // Check also method body
+ if (meth != null) {
+ try {
+ InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder(
+ bundleId, pos);
+ typeFinder.getEnclosingMethod().accept(imbdf);
+ bundleVar = imbdf.getVariableName() != null ? imbdf
+ .getVariableName() : bundleVar;
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+
+ return bundleVar;
+ }
+
+ public static String getNonExistingRBRefName(String bundleId,
+ IDocument document, CompilationUnit cu) {
+ String referenceName = null;
+ int i = 0;
+
+ while (referenceName == null) {
+ String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1)
+ + "Ref" + (i == 0 ? "" : i);
+ actRef = actRef.toLowerCase();
+
+ VariableFinder vf = new VariableFinder(actRef);
+ cu.accept(vf);
+
+ if (!vf.isVariableFound()) {
+ referenceName = actRef;
+ break;
+ }
+
+ i++;
+ }
+
+ return referenceName;
+ }
+
+ @Deprecated
+ public static String resolveResourceBundle(
+ MethodInvocation methodInvocation,
+ MethodParameterDescriptor rbDefinition,
+ Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
+ String bundleName = null;
+
+ if (methodInvocation.getExpression() instanceof SimpleName) {
+ SimpleName vName = (SimpleName) methodInvocation.getExpression();
+ IVariableBinding vBinding = (IVariableBinding) vName
+ .resolveBinding();
+ VariableDeclarationFragment dec = variableBindingManagers
+ .get(vBinding);
+
+ if (dec.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation init = (MethodInvocation) dec.getInitializer();
+
+ // Check declaring class
+ boolean isValidClass = false;
+ ITypeBinding type = init.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(
+ rbDefinition.getDeclaringClass())) {
+ isValidClass = true;
+ break;
+ } else {
+ if (rbDefinition.isConsiderSuperclass()) {
+ type = type.getSuperclass();
+ } else {
+ type = null;
+ }
+ }
+
+ }
+ if (!isValidClass) {
+ return null;
+ }
+
+ boolean isValidMethod = false;
+ for (String mn : rbDefinition.getMethodName()) {
+ if (init.getName().getFullyQualifiedName().equals(mn)) {
+ isValidMethod = true;
+ break;
+ }
+ }
+ if (!isValidMethod) {
+ return null;
+ }
+
+ // retrieve bundlename
+ if (init.arguments().size() < rbDefinition.getPosition() + 1) {
+ return null;
+ }
+
+ bundleName = ((StringLiteral) init.arguments().get(
+ rbDefinition.getPosition())).getLiteralValue();
+ }
+ }
+
+ return bundleName;
+ }
+
+ public static SLLocation resolveResourceBundleLocation(
+ MethodInvocation methodInvocation,
+ MethodParameterDescriptor rbDefinition,
+ Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
+ SLLocation bundleDesc = null;
+
+ if (methodInvocation.getExpression() instanceof SimpleName) {
+ SimpleName vName = (SimpleName) methodInvocation.getExpression();
+ IVariableBinding vBinding = (IVariableBinding) vName
+ .resolveBinding();
+ VariableDeclarationFragment dec = variableBindingManagers
+ .get(vBinding);
+
+ if (dec.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation init = (MethodInvocation) dec.getInitializer();
+
+ // Check declaring class
+ boolean isValidClass = false;
+ ITypeBinding type = init.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(
+ rbDefinition.getDeclaringClass())) {
+ isValidClass = true;
+ break;
+ } else {
+ if (rbDefinition.isConsiderSuperclass()) {
+ type = type.getSuperclass();
+ } else {
+ type = null;
+ }
+ }
+
+ }
+ if (!isValidClass) {
+ return null;
+ }
+
+ boolean isValidMethod = false;
+ for (String mn : rbDefinition.getMethodName()) {
+ if (init.getName().getFullyQualifiedName().equals(mn)) {
+ isValidMethod = true;
+ break;
+ }
+ }
+ if (!isValidMethod) {
+ return null;
+ }
+
+ // retrieve bundlename
+ if (init.arguments().size() < rbDefinition.getPosition() + 1) {
+ return null;
+ }
+
+ StringLiteral bundleLiteral = ((StringLiteral) init.arguments()
+ .get(rbDefinition.getPosition()));
+ bundleDesc = new SLLocation(null,
+ bundleLiteral.getStartPosition(),
+ bundleLiteral.getLength()
+ + bundleLiteral.getStartPosition(),
+ bundleLiteral.getLiteralValue());
+ }
+ }
+
+ return bundleDesc;
+ }
+
+ private static boolean isMatchingMethodDescriptor(
+ MethodInvocation methodInvocation, MethodParameterDescriptor desc) {
+ boolean result = false;
+
+ if (methodInvocation.resolveMethodBinding() == null) {
+ return false;
+ }
+
+ String methodName = methodInvocation.resolveMethodBinding().getName();
+
+ // Check declaring class
+ ITypeBinding type = methodInvocation.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(desc.getDeclaringClass())) {
+ result = true;
+ break;
+ } else {
+ if (desc.isConsiderSuperclass()) {
+ type = type.getSuperclass();
+ } else {
+ type = null;
+ }
+ }
+
+ }
+
+ if (!result) {
+ return false;
+ }
+
+ result = !result;
+
+ // Check method name
+ for (String method : desc.getMethodName()) {
+ if (method.equals(methodName)) {
+ result = true;
+ break;
+ }
+ }
+
+ return result;
+ }
+
+ public static boolean isMatchingMethodParamDesc(
+ MethodInvocation methodInvocation, String literal,
+ MethodParameterDescriptor desc) {
+ boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
+
+ if (!result) {
+ return false;
+ } else {
+ result = false;
+ }
+
+ if (methodInvocation.arguments().size() > desc.getPosition()) {
+ if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) {
+ StringLiteral sl = (StringLiteral) methodInvocation.arguments()
+ .get(desc.getPosition());
+ if (sl.getLiteralValue().trim().toLowerCase()
+ .equals(literal.toLowerCase())) {
+ result = true;
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static boolean isMatchingMethodParamDesc(
+ MethodInvocation methodInvocation, StringLiteral literal,
+ MethodParameterDescriptor desc) {
+ int keyParameter = desc.getPosition();
+ boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
+
+ if (!result) {
+ return false;
+ }
+
+ // Check position within method call
+ StructuralPropertyDescriptor spd = literal.getLocationInParent();
+ if (spd.isChildListProperty()) {
+ @SuppressWarnings("unchecked")
+ List<ASTNode> arguments = (List<ASTNode>) methodInvocation
+ .getStructuralProperty(spd);
+ result = (arguments.size() > keyParameter && arguments
+ .get(keyParameter) == literal);
+ }
+
+ return result;
+ }
+
+ public static ICompilationUnit createCompilationUnit(IResource resource) {
+ // Instantiate a new AST parser
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setResolveBindings(true);
+
+ ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource
+ .getProject().getFile(resource.getRawLocation()));
+
+ return cu;
+ }
+
+ public static CompilationUnit createCompilationUnit(IDocument document) {
+ // Instantiate a new AST parser
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setResolveBindings(true);
+
+ parser.setSource(document.get().toCharArray());
+ return (CompilationUnit) parser.createAST(null);
+ }
+
+ public static void createImport(IDocument doc, IResource resource,
+ CompilationUnit cu, AST ast, ASTRewrite rewriter,
+ String qualifiedClassName) throws CoreException,
+ BadLocationException {
+
+ ImportFinder impFinder = new ImportFinder(qualifiedClassName);
+
+ cu.accept(impFinder);
+
+ if (!impFinder.isImportFound()) {
+ // ITextFileBufferManager bufferManager =
+ // FileBuffers.getTextFileBufferManager();
+ // IPath path = resource.getFullPath();
+ //
+ // bufferManager.connect(path, LocationKind.IFILE, null);
+ // ITextFileBuffer textFileBuffer =
+ // bufferManager.getTextFileBuffer(doc);
+
+ // TODO create new import
+ ImportDeclaration id = ast.newImportDeclaration();
+ id.setName(ast.newName(qualifiedClassName.split("\\.")));
+ id.setStatic(false);
+
+ ListRewrite lrw = rewriter.getListRewrite(cu,
+ 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 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);
+ }
+ }
+
+ // 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;
+ }
+
+ MethodDeclaration meth = typeFinder.getEnclosingMethod();
+ AST ast = node.getAST();
+
+ VariableDeclarationFragment vdf = ast
+ .newVariableDeclarationFragment();
+ vdf.setName(ast.newSimpleName(variableName));
+
+ // set initializer
+ vdf.setInitializer(createResourceBundleGetter(ast, bundleId,
+ locale));
+
+ FieldDeclaration fd = ast.newFieldDeclaration(vdf);
+ fd.setType(ast.newSimpleType(ast
+ .newName(new String[] { "ResourceBundle" })));
+
+ if (meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
+ fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC));
+ }
+
+ // rewrite AST
+ ASTRewrite rewriter = ASTRewrite.create(ast);
+ ListRewrite lrw = rewriter
+ .getListRewrite(
+ node,
+ node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY
+ : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
+ lrw.insertAt(fd, /*
+ * findIndexOfLastField(node.bodyDeclarations())
+ * +1
+ */
+ 0, null);
+
+ // create import if required
+ createImport(doc, resource, cu, ast, rewriter,
+ getRBDefinitionDesc().getDeclaringClass());
+
+ TextEdit te = rewriter.rewriteAST(doc, null);
+ te.apply(doc);
+ } else {
+
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @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);
+ }
+
+ SimpleName name = ast.newSimpleName(accessorName);
+ mi.setExpression(name);
+
+ return mi;
+ }
+
+ public static String createResourceReference(String bundleId, String key,
+ Locale locale, IResource resource, int typePos,
+ String accessorName, IDocument doc, CompilationUnit cu) {
+
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos);
+ cu.accept(typeFinder);
+ AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
+ TypeDeclaration td = typeFinder.getEnclosingType();
+
+ // retrieve compilation unit from document
+ ASTNode node = atd == null ? td : atd;
+ AST ast = node.getAST();
+
+ ExpressionStatement expressionStatement = ast
+ .newExpressionStatement(referenceResource(ast, accessorName,
+ key, locale));
+
+ String exp = expressionStatement.toString();
+
+ // remove semicolon and line break at the end of this expression
+ // statement
+ if (exp.endsWith(";\n")) {
+ exp = exp.substring(0, exp.length() - 2);
+ }
+
+ return exp;
+ }
+
+ private static int findNonInternationalisationPosition(CompilationUnit cu,
+ IDocument doc, int offset) {
+ LinePreStringsFinder lsfinder = null;
+ try {
+ lsfinder = new LinePreStringsFinder(offset, doc);
+ cu.accept(lsfinder);
+ } catch (BadLocationException e) {
+ Logger.logError(e);
+ }
+ if (lsfinder == null) {
+ return 1;
+ }
+
+ List<StringLiteral> strings = lsfinder.getStrings();
+
+ return strings.size() + 1;
+ }
+
+ public static boolean existsNonInternationalisationComment(
+ StringLiteral literal) throws BadLocationException {
+ CompilationUnit cu = (CompilationUnit) literal.getRoot();
+ ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
+
+ IDocument doc = null;
+ try {
+ doc = new Document(icu.getSource());
+ } catch (JavaModelException e) {
+ Logger.logError(e);
+ }
+
+ // get whole line in which string literal
+ int lineNo = doc.getLineOfOffset(literal.getStartPosition());
+ int lineOffset = doc.getLineOffset(lineNo);
+ int lineLength = doc.getLineLength(lineNo);
+ String lineOfString = doc.get(lineOffset, lineLength);
+
+ // search for a line comment in this line
+ int indexComment = lineOfString.indexOf("//");
+
+ if (indexComment == -1) {
+ return false;
+ }
+
+ String comment = lineOfString.substring(indexComment);
+
+ // remove first "//" of line comment
+ comment = comment.substring(2).toLowerCase();
+
+ // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
+ String[] comments = comment.split("//");
+
+ for (String commentFrag : comments) {
+ commentFrag = commentFrag.trim();
+
+ // if comment match format: "$non-nls$" then ignore whole line
+ if (commentFrag.matches("^\\$non-nls\\$$")) {
+ return true;
+
+ // if comment match format: "$non-nls-{number}$" then only
+ // ignore string which is on given position
+ } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
+ int iString = findNonInternationalisationPosition(cu, doc,
+ literal.getStartPosition());
+ int iComment = new Integer(commentFrag.substring(9, 10));
+ if (iString == iComment) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static StringLiteral getStringLiteralAtPos(CompilationUnit cu, int position) {
+ StringLiteralFinder strFinder = new StringLiteralFinder(position);
+ cu.accept(strFinder);
+ return strFinder.getStringLiteral();
+ }
+
+ static class PositionalTypeFinder extends ASTVisitor {
+
+ private int position;
+ private TypeDeclaration enclosingType;
+ private AnonymousClassDeclaration enclosingAnonymType;
+ private MethodDeclaration enclosingMethod;
+
+ public PositionalTypeFinder(int pos) {
+ position = pos;
+ }
+
+ public TypeDeclaration getEnclosingType() {
+ return enclosingType;
+ }
+
+ public AnonymousClassDeclaration getEnclosingAnonymType() {
+ return enclosingAnonymType;
+ }
+
+ public MethodDeclaration getEnclosingMethod() {
+ return enclosingMethod;
+ }
+
+ @Override
+ public boolean visit(MethodDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingMethod = node;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean visit(TypeDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingType = node;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean visit(AnonymousClassDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingAnonymType = node;
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ static class ImportFinder extends ASTVisitor {
+
+ String qName;
+ boolean importFound = false;
+
+ public ImportFinder(String qName) {
+ this.qName = qName;
+ }
+
+ public boolean isImportFound() {
+ return importFound;
+ }
+
+ @Override
+ public boolean visit(ImportDeclaration id) {
+ if (id.getName().getFullyQualifiedName().equals(qName)) {
+ importFound = true;
+ }
+
+ return true;
+ }
+ }
+
+ static class VariableFinder extends ASTVisitor {
+
+ boolean found = false;
+ String variableName;
+
+ public boolean isVariableFound() {
+ return found;
+ }
+
+ public VariableFinder(String variableName) {
+ this.variableName = variableName;
+ }
+
+ @Override
+ public boolean visit(VariableDeclarationFragment vdf) {
+ if (vdf.getName().getFullyQualifiedName().equals(variableName)) {
+ found = true;
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ static class InMethodBundleDeclFinder extends ASTVisitor {
+ String varName;
+ String bundleId;
+ int pos;
+
+ public InMethodBundleDeclFinder(String bundleId, int pos) {
+ this.bundleId = bundleId;
+ this.pos = pos;
+ }
+
+ public String getVariableName() {
+ return varName;
+ }
+
+ @Override
+ public boolean visit(VariableDeclarationFragment fdvd) {
+ if (fdvd.getStartPosition() > pos) {
+ return false;
+ }
+
+ // boolean bStatic = (fdvd.resolveBinding().getModifiers() &
+ // Modifier.STATIC) == Modifier.STATIC;
+ // if (!bStatic && isStatic)
+ // return true;
+
+ String tmpVarName = fdvd.getName().getFullyQualifiedName();
+
+ if (fdvd.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
+ if (isMatchingMethodParamDesc(fdi, bundleId,
+ getRBDefinitionDesc())) {
+ varName = tmpVarName;
+ }
+ }
+ return true;
+ }
+ }
+
+ static class BundleDeclarationFinder extends ASTVisitor {
+
+ String varName;
+ String bundleId;
+ ASTNode typeDef;
+ boolean isStatic;
+
+ public BundleDeclarationFinder(String bundleId, ASTNode td,
+ boolean isStatic) {
+ this.bundleId = bundleId;
+ this.typeDef = td;
+ this.isStatic = isStatic;
+ }
+
+ public String getVariableName() {
+ return varName;
+ }
+
+ @Override
+ public boolean visit(MethodDeclaration md) {
+ return true;
+ }
+
+ @Override
+ public boolean visit(FieldDeclaration fd) {
+ if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) {
+ return false;
+ }
+
+ boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
+ if (!bStatic && isStatic) {
+ return true;
+ }
+
+ if (fd.getType() instanceof SimpleType) {
+ SimpleType fdType = (SimpleType) fd.getType();
+ String typeName = fdType.getName().getFullyQualifiedName();
+ String referenceName = getRBDefinitionDesc()
+ .getDeclaringClass();
+ if (typeName.equals(referenceName)
+ || (referenceName.lastIndexOf(".") >= 0 && typeName
+ .equals(referenceName.substring(referenceName
+ .lastIndexOf(".") + 1)))) {
+ // Check VariableDeclarationFragment
+ if (fd.fragments().size() == 1) {
+ if (fd.fragments().get(0) instanceof VariableDeclarationFragment) {
+ VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd
+ .fragments().get(0);
+ String tmpVarName = fdvd.getName()
+ .getFullyQualifiedName();
+
+ if (fdvd.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation fdi = (MethodInvocation) fdvd
+ .getInitializer();
+ if (isMatchingMethodParamDesc(fdi, bundleId,
+ getRBDefinitionDesc())) {
+ varName = tmpVarName;
+ }
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ }
+
+ static class LinePreStringsFinder extends ASTVisitor {
+ private int position;
+ private int line;
+ private List<StringLiteral> strings;
+ private IDocument document;
+
+ public LinePreStringsFinder(int position, IDocument document)
+ throws BadLocationException {
+ this.document = document;
+ this.position = position;
+ line = document.getLineOfOffset(position);
+ strings = new ArrayList<StringLiteral>();
+ }
+
+ public List<StringLiteral> getStrings() {
+ return strings;
+ }
+
+ @Override
+ public boolean visit(StringLiteral node) {
+ try {
+ if (line == document.getLineOfOffset(node.getStartPosition())
+ && node.getStartPosition() < position) {
+ strings.add(node);
+ return true;
+ }
+ } catch (BadLocationException e) {
+ }
+ return true;
+ }
+ }
+
+ static class StringLiteralFinder extends ASTVisitor {
+ private int position;
+ private StringLiteral string;
+
+ public StringLiteralFinder(int position) {
+ this.position = position;
+ }
+
+ public StringLiteral getStringLiteral() {
+ return string;
+ }
+
+ @Override
+ public boolean visit(StringLiteral node) {
+ if (position > node.getStartPosition()
+ && position < (node.getStartPosition() + node.getLength())) {
+ string = node;
+ }
+ return true;
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.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
new file mode 100644
index 00000000..9b8639ad
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.visitor;
+
+import java.util.List;
+
+public class MethodParameterDescriptor {
+
+ private List<String> methodName;
+ private String declaringClass;
+ private boolean considerSuperclass;
+ private int position;
+
+ public MethodParameterDescriptor(List<String> methodName,
+ String declaringClass, boolean considerSuperclass, int position) {
+ super();
+ this.setMethodName(methodName);
+ this.declaringClass = declaringClass;
+ this.considerSuperclass = considerSuperclass;
+ this.position = position;
+ }
+
+ public String getDeclaringClass() {
+ return declaringClass;
+ }
+
+ public void setDeclaringClass(String declaringClass) {
+ this.declaringClass = declaringClass;
+ }
+
+ public boolean isConsiderSuperclass() {
+ return considerSuperclass;
+ }
+
+ public void setConsiderSuperclass(boolean considerSuperclass) {
+ this.considerSuperclass = considerSuperclass;
+ }
+
+ public int getPosition() {
+ return position;
+ }
+
+ public void setPosition(int position) {
+ this.position = position;
+ }
+
+ public void setMethodName(List<String> methodName) {
+ this.methodName = methodName;
+ }
+
+ public List<String> getMethodName() {
+ return methodName;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java
new file mode 100644
index 00000000..f19d95e8
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java
@@ -0,0 +1,261 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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.visitor;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import org.eclipse.babel.tapiji.tools.core.model.SLLocation;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.core.dom.ASTNode;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.FieldDeclaration;
+import org.eclipse.jdt.core.dom.IVariableBinding;
+import org.eclipse.jdt.core.dom.MethodInvocation;
+import org.eclipse.jdt.core.dom.StringLiteral;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+
+/**
+ * @author Martin
+ *
+ */
+public class ResourceAuditVisitor extends ASTVisitor implements
+ IResourceVisitor {
+
+ private List<SLLocation> constants;
+ private List<SLLocation> brokenStrings;
+ private List<SLLocation> brokenRBReferences;
+ private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>();
+ private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>();
+ private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>();
+ private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>();
+ private IFile file;
+ private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>();
+ private String projectName;
+
+ public ResourceAuditVisitor(IFile file, String projectName) {
+ constants = new ArrayList<SLLocation>();
+ brokenStrings = new ArrayList<SLLocation>();
+ brokenRBReferences = new ArrayList<SLLocation>();
+ this.file = file;
+ this.projectName = projectName;
+ }
+
+ @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;
+ }
+
+ 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 false;
+ }
+
+ public List<SLLocation> getConstantStringLiterals() {
+ return constants;
+ }
+
+ public List<SLLocation> getBrokenResourceReferences() {
+ return brokenStrings;
+ }
+
+ public List<SLLocation> getBrokenRBReferences() {
+ return this.brokenRBReferences;
+ }
+
+ public IRegion getKeyAt(Long position) {
+ IRegion reg = null;
+
+ Iterator<Long> keys = keyPositions.keySet().iterator();
+ while (keys.hasNext()) {
+ Long startPos = keys.next();
+ if (startPos > position) {
+ break;
+ }
+
+ IRegion region = keyPositions.get(startPos);
+ if (region.getOffset() <= position
+ && (region.getOffset() + region.getLength()) >= position) {
+ reg = region;
+ break;
+ }
+ }
+
+ return reg;
+ }
+
+ public String getKeyAt(IRegion region) {
+ if (bundleKeys.containsKey(region)) {
+ return bundleKeys.get(region);
+ } else {
+ return "";
+ }
+ }
+
+ public String getBundleReference(IRegion region) {
+ return bundleReferences.get(region);
+ }
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public Collection<String> getDefinedResourceBundles(int offset) {
+ Collection<String> result = new HashSet<String>();
+ for (String s : bundleReferences.values()) {
+ if (s != null) {
+ result.add(s);
+ }
+ }
+ return result;
+ }
+
+ public IRegion getRBReferenceAt(Long offset) {
+ IRegion reg = null;
+
+ Iterator<Long> keys = rbDefReferences.keySet().iterator();
+ while (keys.hasNext()) {
+ Long startPos = keys.next();
+ if (startPos > offset) {
+ break;
+ }
+
+ IRegion region = rbDefReferences.get(startPos);
+ if (region != null && region.getOffset() <= offset
+ && (region.getOffset() + region.getLength()) >= offset) {
+ reg = region;
+ break;
+ }
+ }
+
+ return reg;
+ }
+}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/.classpath b/org.eclipse.babel.tapiji.tools.rbmanager/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/.classpath
rename to org.eclipse.babel.tapiji.tools.rbmanager/.classpath
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/.project b/org.eclipse.babel.tapiji.tools.rbmanager/.project
new file mode 100644
index 00000000..c01fd6c1
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.tapiji.tools.rbmanager</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.tools.rbmanager/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.tapiji.tools.rbmanager/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.rbmanager/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..9295dece
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/META-INF/MANIFEST.MF
@@ -0,0 +1,15 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Manager
+Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.rbmanager;singleton:=true
+Bundle-Version: 0.0.2.qualifier
+Bundle-Activator: org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator
+Bundle-Vendor: GKNSINTERMETALS
+Require-Bundle: org.eclipse.core.runtime,
+ org.eclipse.core.resources;bundle-version="3.6",
+ org.eclipse.ui,
+ org.eclipse.ui.ide;bundle-version="3.6.0",
+ org.eclipse.ui.navigator;bundle-version="3.5",
+ org.eclipse.babel.tapiji.tools.core.ui;bundle-version="0.0.2"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/build.properties b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/build.properties
rename to org.eclipse.babel.tapiji.tools.rbmanager/build.properties
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/__.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/__.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/__.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/__.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/_f.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/_f.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/_f.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/_f.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ad.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ad.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ad.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ad.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ae.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ae.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ae.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ae.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/af.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/af.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/af.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/af.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ag.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ag.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ag.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/al.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/al.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/al.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/al.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/am.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/am.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/am.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/am.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ao.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ao.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ao.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ao.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/aq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/aq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/aq.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/aq.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ar.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ar.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ar.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/at.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/at.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/at.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/at.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/au.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/au.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/au.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/au.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/az.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/az.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/az.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/az.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ba.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ba.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ba.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ba.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bb.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bb.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bd.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bd.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/be.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/be.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/be.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/be.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bf.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bf.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bf.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bh.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bh.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bi.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bi.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bj.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bj.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/blank.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/blank.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/blank.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/blank.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bo.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bo.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bo.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/br.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/br.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/br.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/br.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bs.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bs.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bs.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/by.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/by.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/by.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/by.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/bz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ca.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ca.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ca.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ca.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cd.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cd.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cf.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cf.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cf.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cf.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ch.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ch.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ch.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ch.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ci.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ci.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ci.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ci.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/co.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/co.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/co.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/co.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cs.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cs.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cs.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cs.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cy.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cy.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/cz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dd.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dd.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/de.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/de.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/de.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/de.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dj.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dj.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/do.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/do.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/do.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/do.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/dz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ec.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ec.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ec.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ec.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ee.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ee.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ee.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ee.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/eg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/eg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/eh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/eh.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eh.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/er.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/er.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/er.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/er.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/es.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/es.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/es.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/es.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/et.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/et.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/et.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/et.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/eu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/eu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fi.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fi.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fj.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fj.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/fr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ga.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ga.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ga.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ga.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gb.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gb.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gd.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gd.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ge.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ge.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ge.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ge.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gh.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gh.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gq.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gq.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/gy.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gy.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ht.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ht.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ht.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ht.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/hu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/id.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/id.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/id.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/id.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ie.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ie.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ie.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ie.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/il.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/il.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/il.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/il.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/in.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/in.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/in.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/in.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/iq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/iq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/iq.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/iq.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ir.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ir.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ir.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ir.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/is.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/is.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/is.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/is.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/it.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/it.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/it.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/it.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/jm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/jm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/jo.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jo.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/jo.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jo.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/jp.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/jp.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jp.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ke.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ke.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ke.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ke.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kh.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kh.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ki.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ki.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ki.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ki.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/km.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/km.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/km.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/km.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kp.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kp.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kp.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/kz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ar.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ar.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ar.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ar.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_be.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_be.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_be.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_be.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_bg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_bg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_bg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_bg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_cz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_cz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_cz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_cz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_de.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_de.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_de.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_de.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_dk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_dk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_dk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_dk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_el.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_el.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_el.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_el.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_en.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_en.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_en.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_en.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_es.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_es.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_es.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_es.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_et.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_et.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_et.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_et.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_fi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_fi.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fi.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_fr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_fr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ga.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ga.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ga.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ga.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_hi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hi.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_hi.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hi.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_hr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_hr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_hu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_hu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_in.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_in.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_in.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_in.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_is.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_is.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_is.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_is.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_it.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_it.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_it.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_it.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_iw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_iw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_iw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_iw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ja.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ja.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ja.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ja.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ko.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ko.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ko.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ko.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_lt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_lt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_lv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_lv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_mk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_mk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ms.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ms.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ms.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ms.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_mt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_mt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_nl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_nl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_nl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_nl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_no.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_no.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_no.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_no.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_pl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_pl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_pt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_pt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ro.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ro.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ro.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ro.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ru.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ru.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_ru.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ru.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sq.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sq.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sq.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_sv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_th.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_th.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_th.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_th.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_tr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_tr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_tr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_tr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_uk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_uk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_uk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_uk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_vn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_vn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_vn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_vn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_zh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_zh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/l_zh.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_zh.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/la.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/la.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/la.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/la.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lb.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lb.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lc.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lc.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/li.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/li.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/li.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/li.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ls.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ls.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ls.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ls.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/lv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ly.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ly.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ly.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ly.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ma.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ma.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ma.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ma.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mc.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mc.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/md.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/md.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/md.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/md.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mh.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mh.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mh.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ml.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ml.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ml.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ml.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mx.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mx.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mx.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mx.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/my.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/my.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/my.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/my.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/mz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/na.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/na.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/na.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/na.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ne.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ne.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ne.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ne.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ng.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ng.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ng.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ng.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ni.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ni.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ni.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ni.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/no.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/no.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/no.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/no.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/np.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/np.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/np.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/np.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/nz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/om.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/om.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/om.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/om.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pa.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pa.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pa.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pe.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pe.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pe.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pe.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ph.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ph.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ph.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ph.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ps.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ps.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ps.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ps.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/pw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/py.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/py.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/py.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/py.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/qa.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/qa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/qa.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/qa.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ro.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ro.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ro.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ro.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ru.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ru.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ru.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ru.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/rw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/rw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/rw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/rw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sa.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sa.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sa.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sa.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sb.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sb.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sb.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sc.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sc.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sd.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sd.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sd.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/se.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/se.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/se.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/se.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/si.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/si.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/si.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/si.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sl.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sl.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sl.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/so.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/so.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/so.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/so.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/st.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/st.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/st.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/st.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/su.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/su.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/su.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/su.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sy.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sy.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/sz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/td.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/td.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/td.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/td.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tg.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tg.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tg.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/th.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/th.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/th.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/th.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tj.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tj.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tj.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/to.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/to.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/to.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/to.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tp.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tp.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tp.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tp.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tr.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tr.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tr.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tt.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tt.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tt.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tv.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tv.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tv.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/tz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ua.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ua.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ua.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ua.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ug.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ug.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ug.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ug.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/uk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uk.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/uk.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uk.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/un.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/un.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/un.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/un.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/us.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/us.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/us.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/us.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/uy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uy.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/uy.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uy.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/uz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uz.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/uz.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uz.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/va.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/va.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/va.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/va.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/vc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vc.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/vc.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vc.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ve.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ve.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ve.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ve.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/vn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vn.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/vn.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vn.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/vu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/vu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ws.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ws.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ws.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ws.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ya.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ya.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ya.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ya.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ye.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ye.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ye0.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye0.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/ye0.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye0.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/yu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/yu.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/yu.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/yu.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/za.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/za.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/za.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/za.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/zm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zm.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/zm.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zm.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/countries/zw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zw.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/countries/zw.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zw.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/expand.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/expand.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/expand.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/expand.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/expandall.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/expandall.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/expandall.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/expandall.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/fragment_flag.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragment_flag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/fragment_flag.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/fragment_flag.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/fragmentproject.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragmentproject.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/fragmentproject.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/fragmentproject.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/resourcebundle.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/resourcebundle.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/resourcebundle.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/resourcebundle.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/warning.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/warning.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/warning.gif
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/icons/warning_flag.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning_flag.gif
similarity index 100%
rename from org.eclipselabs.tapiji.tools.rbmanager/icons/warning_flag.gif
rename to org.eclipse.babel.tapiji.tools.rbmanager/icons/warning_flag.gif
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/plugin.xml b/org.eclipse.babel.tapiji.tools.rbmanager/plugin.xml
new file mode 100644
index 00000000..1d8fa9c0
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/plugin.xml
@@ -0,0 +1,197 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+ <extension
+ point="org.eclipse.ui.views">
+ <view
+ category="org.eclipse.babel.tapiji"
+ class="org.eclipse.ui.navigator.CommonNavigator"
+ icon="icons/resourcebundle.gif"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer"
+ name="Resource Bundle Explorer"
+ restorable="true">
+ </view>
+ </extension>
+ <extension
+ point="org.eclipse.ui.viewActions">
+ <viewContribution
+ id="org.eclipse.babel.tapiji.tools.rbmanager.viewContribution1"
+ targetID="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer">
+ <action
+ class="org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems.ToggleFilterActionDelegate"
+ icon="icons/warning.gif"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.activateFilter"
+ label="Filter Problematic ResourceBundles"
+ state="false"
+ style="toggle"
+ toolbarPath="additions"
+ tooltip="Filters ResourceBundles With Warnings">
+ </action>
+ </viewContribution>
+ <viewContribution
+ id="org.eclipse.babel.tapiji.tools.rbmanager.viewContribution2"
+ targetID="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer">
+ <action
+ class="org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems.ExpandAllActionDelegate"
+ icon="icons/expandall.gif"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.expandAll"
+ label="Expand All"
+ style="push"
+ toolbarPath="additions">
+ </action>
+ </viewContribution>
+ </extension>
+ <extension
+ point="org.eclipse.ui.navigator.viewer">
+ <viewerContentBinding
+ viewerId="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer">
+ <includes>
+ <contentExtension
+ pattern="org.eclipse.babel.tapiji.tools.rbmanager.resourcebundleContent">
+ </contentExtension>
+ <contentExtension
+ pattern="org.eclipse.babel.tapiji.tools.rbmanager.filter.*">
+ </contentExtension>
+ <contentExtension
+ pattern="org.eclipse.ui.navigator.resources.filters.*">
+ </contentExtension>
+ <contentExtension
+ pattern="org.eclipse.babel.tapiji.tools.rbmanager.linkHelper">
+ </contentExtension>
+ </includes>
+ </viewerContentBinding>
+ <viewerActionBinding
+ viewerId="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer">
+ <includes>
+ <actionExtension
+ pattern="org.eclipse.ui.navigator.resources.*">
+ </actionExtension>
+ </includes>
+ </viewerActionBinding>
+ <viewer
+ viewerId="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer">
+ <popupMenu>
+ <insertionPoint
+ name="group.new">
+ </insertionPoint>
+ <insertionPoint
+ name="group.open">
+ </insertionPoint>
+ <insertionPoint
+ name="group.openWith">
+ </insertionPoint>
+ <insertionPoint
+ name="group.edit">
+ </insertionPoint>
+ <insertionPoint
+ name="expand">
+ </insertionPoint>
+ <insertionPoint
+ name="group.port">
+ </insertionPoint>
+ <insertionPoint
+ name="group.reorgnize">
+ </insertionPoint>
+ <insertionPoint
+ name="group.build">
+ </insertionPoint>
+ <insertionPoint
+ name="group.search">
+ </insertionPoint>
+ <insertionPoint
+ name="additions">
+ </insertionPoint>
+ <insertionPoint
+ name="group.properties">
+ </insertionPoint>
+ </popupMenu>
+ </viewer>
+ </extension>
+ <extension
+ point="org.eclipse.ui.navigator.navigatorContent">
+ <navigatorContent
+ contentProvider="org.eclipse.babel.tapiji.tools.rbmanager.viewer.ResourceBundleContentProvider"
+ icon="icons/resourcebundle.gif"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.resourcebundleContent"
+ labelProvider="org.eclipse.babel.tapiji.tools.rbmanager.viewer.ResourceBundleLabelProvider"
+ name="Resource Bundle Content"
+ priority="high">
+ <triggerPoints>
+ <or>
+ <instanceof
+ value="org.eclipse.core.resources.IWorkspaceRoot">
+ </instanceof>
+ <instanceof
+ value="org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle">
+ </instanceof>
+ <instanceof
+ value="org.eclipse.core.resources.IContainer">
+ </instanceof>
+ <instanceof
+ value="org.eclipse.core.resources.IProject">
+ </instanceof>
+ </or>
+ </triggerPoints>
+ <possibleChildren>
+ <or>
+ <instanceof
+ value="org.eclipse.core.resources.IContainer">
+ </instanceof>
+ <instanceof
+ value="org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle">
+ </instanceof>
+ <and>
+ <instanceof
+ value="org.eclipse.core.resources.IFile">
+ </instanceof>
+ <test
+ property="org.eclipse.core.resources.extension"
+ value="properties">
+ </test>
+ </and>
+ </or></possibleChildren>
+ <actionProvider
+ class="org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.VirtualRBActionProvider"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.action.openProvider">
+ <enablement>
+ <instanceof
+ value="org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle">
+ </instanceof>
+ </enablement>
+ </actionProvider>
+ <actionProvider
+ class="org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.GeneralActionProvider"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.action.general">
+ </actionProvider>
+ </navigatorContent>
+ </extension>
+ <extension
+ point="org.eclipse.ui.navigator.navigatorContent">
+ <commonFilter
+ activeByDefault="false"
+ class="org.eclipse.babel.tapiji.tools.rbmanager.viewer.filters.ProblematicResourceBundleFilter"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.filter.ProblematicResourceBundleFiles"
+ name="Problematic Resource Bundle Files">
+ </commonFilter>
+ </extension>
+ <extension
+ point="org.eclipse.ui.navigator.linkHelper">
+ <linkHelper
+ class="org.eclipse.babel.tapiji.tools.rbmanager.viewer.LinkHelper"
+ id="org.eclipse.babel.tapiji.tools.rbmanager.linkHelper">
+ <selectionEnablement>
+ <instanceof value="org.eclipse.core.resources.IFile"/>
+ </selectionEnablement>
+ <editorInputEnablement>
+ <instanceof value="org.eclipse.ui.IFileEditorInput"/>
+ </editorInputEnablement>
+ </linkHelper>
+ </extension>
+ <extension
+ point="org.eclipse.babel.tapiji.tools.core.builderExtension">
+ <i18nAuditor
+ class="org.eclipse.babel.tapiji.tools.rbmanager.auditor.ResourceBundleAuditor">
+ </i18nAuditor>
+ </extension>
+
+</plugin>
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
new file mode 100644
index 00000000..58f1b718
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
@@ -0,0 +1,121 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager;
+
+import java.io.File;
+import java.net.URISyntaxException;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.util.OverlayIcon;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
+public class ImageUtils {
+ private static final ImageRegistry imageRegistry = new ImageRegistry();
+
+ private static final String WARNING_FLAG_IMAGE = "warning_flag.gif";
+ private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif";
+ public static final String WARNING_IMAGE = "warning.gif";
+ public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif";
+ public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif";
+ public static final String EXPAND = "expand.gif";
+ public static final String DEFAULT_LOCALICON = File.separatorChar
+ + "countries" + File.separatorChar + "_f.gif";
+ public static final String LOCATION_WITHOUT_ICON = File.separatorChar
+ + "countries" + File.separatorChar + "un.gif";
+
+ /**
+ * @return a Image from the folder 'icons'
+ * @throws URISyntaxException
+ */
+ public static Image getBaseImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ ImageDescriptor descriptor = RBManagerActivator
+ .getImageDescriptor(imageName);
+
+ if (descriptor.getImageData() != null) {
+ image = descriptor.createImage(false);
+ imageRegistry.put(imageName, image);
+ }
+ }
+
+ return image;
+ }
+
+ /**
+ * @param baseImage
+ * @return baseImage with a overlay warning-image
+ */
+ public static Image getImageWithWarning(Image baseImage) {
+ String imageWithWarningId = baseImage.toString() + ".w";
+ Image imageWithWarning = imageRegistry.get(imageWithWarningId);
+
+ if (imageWithWarning == null) {
+ Image warningImage = getBaseImage(WARNING_FLAG_IMAGE);
+ imageWithWarning = new OverlayIcon(baseImage, warningImage,
+ OverlayIcon.BOTTOM_LEFT).createImage();
+ imageRegistry.put(imageWithWarningId, imageWithWarning);
+ }
+
+ return imageWithWarning;
+ }
+
+ /**
+ *
+ * @param baseImage
+ * @return baseImage with a overlay fragment-image
+ */
+ public static Image getImageWithFragment(Image baseImage) {
+ String imageWithFragmentId = baseImage.toString() + ".f";
+ Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
+
+ if (imageWithFragment == null) {
+ Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
+ imageWithFragment = new OverlayIcon(baseImage, fragement,
+ OverlayIcon.BOTTOM_RIGHT).createImage();
+ imageRegistry.put(imageWithFragmentId, imageWithFragment);
+ }
+
+ return imageWithFragment;
+ }
+
+ /**
+ * @return a Image with a flag of the given country
+ */
+ public static Image getLocalIcon(Locale locale) {
+ String imageName;
+ Image image = null;
+
+ if (locale != null && !locale.getCountry().equals("")) {
+ imageName = File.separatorChar + "countries" + File.separatorChar
+ + locale.getCountry().toLowerCase() + ".gif";
+ image = getBaseImage(imageName);
+ } else {
+ if (locale != null) {
+ imageName = File.separatorChar + "countries"
+ + File.separatorChar + "l_"
+ + locale.getLanguage().toLowerCase() + ".gif";
+ image = getBaseImage(imageName);
+ } else {
+ imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale
+ // icon
+ image = getBaseImage(imageName);
+ }
+ }
+
+ if (image == null)
+ image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
+ return image;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
new file mode 100644
index 00000000..0b5d62a6
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class RBManagerActivator extends AbstractUIPlugin {
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.rbmanager"; //$NON-NLS-1$
+ // The shared instance
+ private static RBManagerActivator plugin;
+
+ /**
+ * The constructor
+ */
+ public RBManagerActivator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static RBManagerActivator getDefault() {
+ return plugin;
+ }
+
+ public static ImageDescriptor getImageDescriptor(String name) {
+ String path = "icons/" + name;
+
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
new file mode 100644
index 00000000..f80ac230
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.auditor;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+public class RBLocation implements ILocation {
+ private IFile file;
+ private int startPos, endPos;
+ private String language;
+ private Serializable data;
+ private ILocation sameValuePartner;
+
+ public RBLocation(IFile file, int startPos, int endPos, String language) {
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.language = language;
+ }
+
+ public RBLocation(IFile file, int startPos, int endPos, String language,
+ ILocation sameValuePartner) {
+ this(file, startPos, endPos, language);
+ this.sameValuePartner = sameValuePartner;
+ }
+
+ @Override
+ public IFile getFile() {
+ return file;
+ }
+
+ @Override
+ public int getStartPos() {
+ return startPos;
+ }
+
+ @Override
+ public int getEndPos() {
+ return endPos;
+ }
+
+ @Override
+ public String getLiteral() {
+ return language;
+ }
+
+ @Override
+ public Serializable getData() {
+ return data;
+ }
+
+ public void setData(Serializable data) {
+ this.data = data;
+ }
+
+ public ILocation getSameValuePartner() {
+ return sameValuePartner;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
new file mode 100644
index 00000000..ec32b805
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
@@ -0,0 +1,263 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.auditor;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.babel.core.configuration.ConfigurationManager;
+import org.eclipse.babel.core.configuration.IConfiguration;
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.IMessagesBundleGroup;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nRBAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.auditor.quickfix.MissingLanguageResolution;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.ui.IMarkerResolution;
+
+/**
+ *
+ */
+public class ResourceBundleAuditor extends I18nRBAuditor {
+ private static final String LANGUAGE_ATTRIBUTE = "key";
+
+ private List<ILocation> unspecifiedKeys = new LinkedList<ILocation>();
+ private Map<ILocation, ILocation> sameValues = new HashMap<ILocation, ILocation>();
+ private List<ILocation> missingLanguages = new LinkedList<ILocation>();
+ private List<String> seenRBs = new LinkedList<String>();
+
+ @Override
+ public String[] getFileEndings() {
+ return new String[] { "properties" };
+ }
+
+ @Override
+ public String getContextId() {
+ return "resourcebundle";
+ }
+
+ @Override
+ public List<ILocation> getUnspecifiedKeyReferences() {
+ return unspecifiedKeys;
+ }
+
+ @Override
+ public Map<ILocation, ILocation> getSameValuesReferences() {
+ return sameValues;
+ }
+
+ @Override
+ public List<ILocation> getMissingLanguageReferences() {
+ return missingLanguages;
+ }
+
+ /*
+ * Forgets all save rbIds in seenRB and reset all problem-lists
+ */
+ @Override
+ public void resetProblems() {
+ unspecifiedKeys = new LinkedList<ILocation>();
+ sameValues = new HashMap<ILocation, ILocation>();
+ missingLanguages = new LinkedList<ILocation>();
+ seenRBs = new LinkedList<String>();
+ }
+
+ /*
+ * Finds the corresponding ResouceBundle for the resource. Checks if the
+ * ResourceBundle is already audit and it is not already executed audit the
+ * hole ResourceBundle and save the rbId in seenRB
+ */
+ @Override
+ public void audit(IResource resource) {
+ if (!RBFileUtils.isResourceBundleFile(resource)) {
+ return;
+ }
+
+ IFile file = (IFile) resource;
+ String rbId = RBFileUtils.getCorrespondingResourceBundleId(file);
+
+ if (!seenRBs.contains(rbId)) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(file.getProject());
+ audit(rbId, rbmanager);
+ seenRBs.add(rbId);
+ } else {
+ return;
+ }
+ }
+
+ /*
+ * audits all files of a resourcebundle
+ */
+ public void audit(String rbId, ResourceBundleManager rbmanager) {
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+ IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
+ Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
+ String[] keys = bundlegroup.getMessageKeys();
+
+ for (IResource r : bundlefile) {
+ IFile f1 = (IFile) r;
+
+ for (String key : keys) {
+ // check if all keys have a value
+
+ if (auditUnspecifiedKey(f1, key, bundlegroup)) {
+ /* do nothing - all just done */
+ } else {
+ // check if a key has the same value like a key of an other
+ // properties-file
+ if (configuration.getAuditSameValue()
+ && bundlefile.size() > 1) {
+ for (IResource r2 : bundlefile) {
+ IFile f2 = (IFile) r2;
+ auditSameValues(f1, f2, key, bundlegroup);
+ }
+ }
+ }
+ }
+ }
+
+ if (configuration.getAuditMissingLanguage()) {
+ // checks if the resourcebundle supports all project-languages
+ Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
+ Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
+
+ auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
+ }
+ }
+
+ /*
+ * Audits the file if the key is not specified. If the value is null reports
+ * a problem.
+ */
+ private boolean auditUnspecifiedKey(IFile f1, String key,
+ IMessagesBundleGroup bundlegroup) {
+ if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
+ int pos = calculateKeyLine(key, f1);
+ unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /*
+ * Compares a key in different files and reports a problem, if the values
+ * are same. It doesn't compare the files if one file is the Default-file
+ */
+ private void auditSameValues(IFile f1, IFile f2, String key,
+ IMessagesBundleGroup bundlegroup) {
+ Locale l1 = RBFileUtils.getLocale(f1);
+ Locale l2 = RBFileUtils.getLocale(f2);
+
+ if (!l2.equals(l1)
+ && !(l1.toString().equals("") || l2.toString().equals(""))) {
+ IMessage message = bundlegroup.getMessage(key, l2);
+
+ if (message != null) {
+ if (bundlegroup.getMessage(key, l1).getValue()
+ .equals(message.getValue())) {
+ int pos1 = calculateKeyLine(key, f1);
+ int pos2 = calculateKeyLine(key, f2);
+ sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key),
+ new RBLocation(f2, pos2, pos2 + 1, key));
+ }
+ }
+ }
+ }
+
+ /*
+ * Checks if the resourcebundle supports all project-languages and report
+ * missing languages.
+ */
+ private void auditMissingLanguage(Set<Locale> rbLocales,
+ Set<Locale> projectLocales, ResourceBundleManager rbmanager,
+ String rbId) {
+ for (Locale pLocale : projectLocales) {
+ if (!rbLocales.contains(pLocale)) {
+ String language = pLocale != null ? pLocale.toString()
+ : ResourceBundleManager.defaultLocaleTag;
+
+ // Add Warning to default-file or a random chosen file
+ IResource representative = rbmanager.getResourceBundleFile(
+ rbId, null);
+ if (representative == null) {
+ representative = rbmanager.getRandomFile(rbId);
+ }
+ missingLanguages.add(new RBLocation((IFile) representative, 1,
+ 2, language));
+ }
+ }
+ }
+
+ /*
+ * Finds a position where the key is located or missing
+ */
+ private int calculateKeyLine(String key, IFile file) {
+ int linenumber = 1;
+ try {
+ // if (!Boolean.valueOf(System.getProperty("dirty"))) {
+ // System.setProperty("dirty", "true");
+ file.refreshLocal(IFile.DEPTH_ZERO, null);
+ InputStream is = file.getContents();
+ BufferedReader bf = new BufferedReader(new InputStreamReader(is));
+ String line;
+ while ((line = bf.readLine()) != null) {
+ if ((!line.isEmpty()) && (!line.startsWith("#"))
+ && (line.compareTo(key) > 0)) {
+ return linenumber;
+ }
+ linenumber++;
+ }
+ // System.setProperty("dirty", "false");
+ // }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return linenumber;
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+
+ switch (marker.getAttribute("cause", -1)) {
+ case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
+ Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
+ // change
+ // Name
+ resolutions.add(new MissingLanguageResolution(l));
+ break;
+ }
+
+ return resolutions;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
new file mode 100644
index 00000000..42a91d0a
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.auditor.quickfix;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.LanguageUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class MissingLanguageResolution implements IMarkerResolution2 {
+
+ private Locale language;
+
+ public MissingLanguageResolution(Locale language) {
+ this.language = language;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Add missing language '" + language + "'";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ IResource res = marker.getResource();
+ String rbId = ResourceBundleManager.getResourceBundleId(res);
+ LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId,
+ language);
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new localized properties-file with the same basename as the resourcebundle";
+ }
+
+ @Override
+ public Image getImage() {
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
new file mode 100644
index 00000000..22561cdf
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class VirtualContainer {
+ protected ResourceBundleManager rbmanager;
+ protected IContainer container;
+ protected int rbCount;
+
+ public VirtualContainer(IContainer container1, boolean countResourceBundles) {
+ this.container = container1;
+ rbmanager = ResourceBundleManager.getManager(container.getProject());
+ if (countResourceBundles) {
+ rbCount = 1;
+ new Job("count ResourceBundles") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ recount();
+ return Status.OK_STATUS;
+ }
+ }.schedule();
+ } else {
+ rbCount = 0;
+ }
+ }
+
+ protected VirtualContainer(IContainer container) {
+ this.container = container;
+ }
+
+ public VirtualContainer(IContainer container, int rbCount) {
+ this(container, false);
+ this.rbCount = rbCount;
+ }
+
+ public ResourceBundleManager getResourceBundleManager() {
+ if (rbmanager == null) {
+ rbmanager = ResourceBundleManager
+ .getManager(container.getProject());
+ }
+ return rbmanager;
+ }
+
+ public IContainer getContainer() {
+ return container;
+ }
+
+ public void setRbCounter(int rbCount) {
+ this.rbCount = rbCount;
+ }
+
+ public int getRbCount() {
+ return rbCount;
+ }
+
+ public void recount() {
+ rbCount = 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
new file mode 100644
index 00000000..fa90a287
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.resources.IContainer;
+
+public class VirtualContentManager {
+ private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>();
+ private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>();
+
+ static private VirtualContentManager singelton = null;
+
+ private VirtualContentManager() {
+ }
+
+ public static VirtualContentManager getVirtualContentManager() {
+ if (singelton == null) {
+ singelton = new VirtualContentManager();
+ }
+ return singelton;
+ }
+
+ public VirtualContainer getContainer(IContainer container) {
+ return containers.get(container);
+ }
+
+ public void addVContainer(IContainer container, VirtualContainer vContainer) {
+ containers.put(container, vContainer);
+ }
+
+ public void removeVContainer(IContainer container) {
+ vResourceBundles.remove(container);
+ }
+
+ public VirtualResourceBundle getVResourceBundles(String vRbId) {
+ return vResourceBundles.get(vRbId);
+ }
+
+ public void addVResourceBundle(String vRbId,
+ VirtualResourceBundle vResourceBundle) {
+ vResourceBundles.put(vRbId, vResourceBundle);
+ }
+
+ public void removeVResourceBundle(String vRbId) {
+ vResourceBundles.remove(vRbId);
+ }
+
+ public boolean containsVResourceBundles(String vRbId) {
+ return vResourceBundles.containsKey(vRbId);
+ }
+
+ public void reset() {
+ vResourceBundles.clear();
+ containers.clear();
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
new file mode 100644
index 00000000..1748928f
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Michael Gasser - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.core.resources.IProject;
+
+/**
+ * Representation of a project
+ *
+ */
+public class VirtualProject extends VirtualContainer {
+ private boolean isFragment;
+ private IProject hostProject;
+ private List<IProject> fragmentProjects = new LinkedList<IProject>();
+
+ // Slow
+ public VirtualProject(IProject project, boolean countResourceBundles) {
+ super(project, countResourceBundles);
+ isFragment = FragmentProjectUtils.isFragment(project);
+ if (isFragment) {
+ hostProject = FragmentProjectUtils.getFragmentHost(project);
+ } else
+ fragmentProjects = FragmentProjectUtils.getFragments(project);
+ }
+
+ /*
+ * No fragment search
+ */
+ public VirtualProject(final IProject project, boolean isFragment,
+ boolean countResourceBundles) {
+ super(project, countResourceBundles);
+ this.isFragment = isFragment;
+ // Display.getDefault().asyncExec(new Runnable() {
+ // @Override
+ // public void run() {
+ // hostProject = FragmentProjectUtils.getFragmentHost(project);
+ // }
+ // });
+ }
+
+ public Set<Locale> getProvidedLocales() {
+ return rbmanager.getProjectProvidedLocales();
+ }
+
+ public boolean isFragment() {
+ return isFragment;
+ }
+
+ public IProject getHostProject() {
+ return hostProject;
+ }
+
+ public boolean hasFragments() {
+ return !fragmentProjects.isEmpty();
+ }
+
+ public List<IProject> getFragmets() {
+ return fragmentProjects;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
new file mode 100644
index 00000000..6dfc7f76
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
@@ -0,0 +1,60 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import java.util.Collection;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IPath;
+
+public class VirtualResourceBundle {
+ private String resourcebundlename;
+ private String resourcebundleId;
+ private ResourceBundleManager rbmanager;
+
+ public VirtualResourceBundle(String rbname, String rbId,
+ ResourceBundleManager rbmanager) {
+ this.rbmanager = rbmanager;
+ resourcebundlename = rbname;
+ resourcebundleId = rbId;
+ }
+
+ public ResourceBundleManager getResourceBundleManager() {
+ return rbmanager;
+ }
+
+ public String getResourceBundleId() {
+ return resourcebundleId;
+ }
+
+ @Override
+ public String toString() {
+ return resourcebundleId;
+ }
+
+ public IPath getFullPath() {
+ return rbmanager.getRandomFile(resourcebundleId).getFullPath();
+ }
+
+ public String getName() {
+ return resourcebundlename;
+ }
+
+ public Collection<IResource> getFiles() {
+ return rbmanager.getResourceBundles(resourcebundleId);
+ }
+
+ public IFile getRandomFile() {
+ return rbmanager.getRandomFile(resourcebundleId);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
new file mode 100644
index 00000000..f59c796e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
@@ -0,0 +1,119 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.hover;
+
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseTrackAdapter;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.Widget;
+
+public class Hover {
+ private Shell hoverShell;
+ private Point hoverPosition;
+ private List<HoverInformant> informant;
+
+ public Hover(Shell parent, List<HoverInformant> informant) {
+ this.informant = informant;
+ hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
+ Display display = hoverShell.getDisplay();
+
+ GridLayout gridLayout = new GridLayout(1, false);
+ gridLayout.verticalSpacing = 2;
+ hoverShell.setLayout(gridLayout);
+
+ hoverShell.setBackground(display
+ .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ hoverShell.setForeground(display
+ .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ }
+
+ private void setHoverLocation(Shell shell, Point position) {
+ Rectangle displayBounds = shell.getDisplay().getBounds();
+ Rectangle shellBounds = shell.getBounds();
+ shellBounds.x = Math.max(
+ Math.min(position.x + 1, displayBounds.width
+ - shellBounds.width), 0);
+ shellBounds.y = Math.max(
+ Math.min(position.y + 16, displayBounds.height
+ - (shellBounds.height + 1)), 0);
+ shell.setBounds(shellBounds);
+ }
+
+ public void activateHoverHelp(final Control control) {
+
+ control.addMouseListener(new MouseAdapter() {
+ public void mouseDown(MouseEvent e) {
+ if (hoverShell != null && hoverShell.isVisible()) {
+ hoverShell.setVisible(false);
+ }
+ }
+ });
+
+ control.addMouseTrackListener(new MouseTrackAdapter() {
+ public void mouseExit(MouseEvent e) {
+ if (hoverShell != null && hoverShell.isVisible())
+ hoverShell.setVisible(false);
+ }
+
+ public void mouseHover(MouseEvent event) {
+ Point pt = new Point(event.x, event.y);
+ Widget widget = event.widget;
+ if (widget instanceof ToolBar) {
+ ToolBar w = (ToolBar) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget instanceof Table) {
+ Table w = (Table) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget instanceof Tree) {
+ Tree w = (Tree) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget == null) {
+ hoverShell.setVisible(false);
+ return;
+ }
+ hoverPosition = control.toDisplay(pt);
+
+ boolean show = false;
+ Object data = widget.getData();
+
+ for (HoverInformant hi : informant) {
+ hi.getInfoComposite(data, hoverShell);
+ if (hi.show())
+ show = true;
+ }
+
+ if (show) {
+ hoverShell.pack();
+ hoverShell.layout();
+ setHoverLocation(hoverShell, hoverPosition);
+ hoverShell.setVisible(true);
+ } else
+ hoverShell.setVisible(false);
+
+ }
+ });
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
new file mode 100644
index 00000000..71a3cd1e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
@@ -0,0 +1,20 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.hover;
+
+import org.eclipse.swt.widgets.Composite;
+
+public interface HoverInformant {
+
+ public Composite getInfoComposite(Object data, Composite parent);
+
+ public boolean show();
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
new file mode 100644
index 00000000..f8780b9c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
@@ -0,0 +1,57 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.AbstractTreeViewer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.navigator.CommonNavigator;
+import org.eclipse.ui.navigator.CommonViewer;
+import org.eclipse.ui.progress.UIJob;
+
+public class ExpandAllActionDelegate implements IViewActionDelegate {
+ private CommonViewer viewer;
+
+ @Override
+ public void run(IAction action) {
+ Object data = viewer.getControl().getData();
+
+ for (final IProject p : ((IWorkspaceRoot) data).getProjects()) {
+ UIJob job = new UIJob("expand Projects") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS);
+ return Status.OK_STATUS;
+ }
+ };
+
+ job.schedule();
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void init(IViewPart view) {
+ viewer = ((CommonNavigator) view).getCommonViewer();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
new file mode 100644
index 00000000..f0ee4d9c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems;
+
+import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.navigator.CommonNavigator;
+import org.eclipse.ui.navigator.ICommonFilterDescriptor;
+import org.eclipse.ui.navigator.INavigatorContentService;
+import org.eclipse.ui.navigator.INavigatorFilterService;
+
+public class ToggleFilterActionDelegate implements IViewActionDelegate {
+ private INavigatorFilterService filterService;
+ private boolean active;
+ private static final String[] FILTER = { RBManagerActivator.PLUGIN_ID
+ + ".filter.ProblematicResourceBundleFiles" };
+
+ @Override
+ public void run(IAction action) {
+ if (active == true) {
+ filterService.activateFilterIdsAndUpdateViewer(new String[0]);
+ active = false;
+ } else {
+ filterService.activateFilterIdsAndUpdateViewer(FILTER);
+ active = true;
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+ // Active when content change
+ }
+
+ @Override
+ public void init(IViewPart view) {
+ INavigatorContentService contentService = ((CommonNavigator) view)
+ .getCommonViewer().getNavigatorContentService();
+
+ filterService = contentService.getFilterService();
+ filterService.activateFilterIdsAndUpdateViewer(new String[0]);
+ active = false;
+ }
+
+ @SuppressWarnings("unused")
+ private String[] getActiveFilterIds() {
+ ICommonFilterDescriptor[] fds = filterService
+ .getVisibleFilterDescriptors();
+ String activeFilterIds[] = new String[fds.length];
+
+ for (int i = 0; i < fds.length; i++)
+ activeFilterIds[i] = fds[i].getId();
+
+ return activeFilterIds;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
new file mode 100644
index 00000000..722c548d
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.ui.ide.ResourceUtil;
+import org.eclipse.ui.navigator.ILinkHelper;
+
+/*
+ * Allows 'link with editor'
+ */
+public class LinkHelper implements ILinkHelper {
+
+ public static IStructuredSelection viewer;
+
+ @Override
+ public IStructuredSelection findSelection(IEditorInput anInput) {
+ IFile file = ResourceUtil.getFile(anInput);
+ if (file != null) {
+ return new StructuredSelection(file);
+ }
+ return StructuredSelection.EMPTY;
+ }
+
+ @Override
+ public void activateEditor(IWorkbenchPage aPage,
+ IStructuredSelection aSelection) {
+ if (aSelection.getFirstElement() instanceof IFile)
+ try {
+ IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
+ } catch (PartInitException e) {/**/
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
new file mode 100644
index 00000000..8867b320
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
@@ -0,0 +1,466 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.preferences.TapiJIPreferences;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContainer;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContentManager;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualProject;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.ui.progress.UIJob;
+
+/**
+ *
+ *
+ */
+public class ResourceBundleContentProvider implements ITreeContentProvider,
+ IResourceChangeListener, IPropertyChangeListener,
+ IResourceBundleChangedListener {
+ private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false;
+ private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true;
+ private StructuredViewer viewer;
+ private VirtualContentManager vcManager;
+ private UIJob refresh;
+ private IWorkspaceRoot root;
+
+ private List<IProject> listenedProjects;
+
+ /**
+ *
+ */
+ public ResourceBundleContentProvider() {
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this,
+ IResourceChangeEvent.POST_CHANGE);
+ TapiJIPreferences.addPropertyChangeListener(this);
+ vcManager = VirtualContentManager.getVirtualContentManager();
+ listenedProjects = new LinkedList<IProject>();
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+
+ @Override
+ public Object[] getChildren(final Object parentElement) {
+ Object[] children = null;
+
+ if (parentElement instanceof IWorkspaceRoot) {
+ root = (IWorkspaceRoot) parentElement;
+ try {
+ IResource[] members = ((IWorkspaceRoot) parentElement)
+ .members();
+
+ List<Object> displayedProjects = new ArrayList<Object>();
+ for (IResource r : members) {
+ if (r instanceof IProject) {
+ IProject p = (IProject) r;
+ if (FragmentProjectUtils.isFragment(r.getProject())) {
+ if (vcManager.getContainer(p) == null) {
+ vcManager.addVContainer(p, new VirtualProject(
+ p, true, false));
+ }
+ if (FRAGMENT_PROJECTS_IN_CONTENT) {
+ displayedProjects.add(r);
+ }
+ } else {
+ if (SHOW_ONLY_PROJECTS_WITH_RBS) {
+ VirtualProject vP;
+ if ((vP = (VirtualProject) vcManager
+ .getContainer(p)) == null) {
+ vP = new VirtualProject(p, false, true);
+ vcManager.addVContainer(p, vP);
+ registerResourceBundleListner(p);
+ }
+
+ if (vP.getRbCount() > 0) {
+ displayedProjects.add(p);
+ }
+ } else {
+ displayedProjects.add(p);
+ }
+ }
+ }
+ }
+
+ children = displayedProjects.toArray();
+ return children;
+ } catch (CoreException e) {
+ }
+ }
+
+ // if (parentElement instanceof IProject) {
+ // final IProject iproject = (IProject) parentElement;
+ // VirtualContainer vproject = vcManager.getContainer(iproject);
+ // if (vproject == null){
+ // vproject = new VirtualProject(iproject, true);
+ // vcManager.addVContainer(iproject, vproject);
+ // }
+ // }
+
+ if (parentElement instanceof IContainer) {
+ IContainer container = (IContainer) parentElement;
+ if (!((VirtualProject) vcManager
+ .getContainer(((IResource) parentElement).getProject()))
+ .isFragment()) {
+ try {
+ children = addChildren(container);
+ } catch (CoreException e) {/**/
+ }
+ }
+ }
+
+ if (parentElement instanceof VirtualResourceBundle) {
+ VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
+ ResourceBundleManager rbmanager = virtualrb
+ .getResourceBundleManager();
+ children = rbmanager.getResourceBundles(
+ virtualrb.getResourceBundleId()).toArray();
+ }
+
+ return children != null ? children : new Object[0];
+ }
+
+ /*
+ * Returns all ResourceBundles and sub-containers (with ResourceBundles in
+ * their subtree) of a Container
+ */
+ private Object[] addChildren(IContainer container) throws CoreException {
+ Map<String, Object> children = new HashMap<String, Object>();
+
+ VirtualProject p = (VirtualProject) vcManager.getContainer(container
+ .getProject());
+ List<IResource> members = new ArrayList<IResource>(
+ Arrays.asList(container.members()));
+
+ // finds files in the corresponding fragment-projects folder
+ if (p.hasFragments()) {
+ List<IContainer> folders = ResourceUtils.getCorrespondingFolders(
+ container, p.getFragmets());
+ for (IContainer f : folders) {
+ for (IResource r : f.members()) {
+ if (r instanceof IFile) {
+ members.add(r);
+ }
+ }
+ }
+ }
+
+ for (IResource r : members) {
+
+ if (r instanceof IFile) {
+ String resourcebundleId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) r);
+ if (resourcebundleId != null
+ && (!children.containsKey(resourcebundleId))) {
+ VirtualResourceBundle vrb;
+
+ String vRBId;
+
+ if (!p.isFragment()) {
+ vRBId = r.getProject() + "." + resourcebundleId;
+ } else {
+ vRBId = p.getHostProject() + "." + resourcebundleId;
+ }
+
+ VirtualResourceBundle vResourceBundle = vcManager
+ .getVResourceBundles(vRBId);
+ if (vResourceBundle == null) {
+ String resourcebundleName = ResourceBundleManager
+ .getResourceBundleName(r);
+ vrb = new VirtualResourceBundle(
+ resourcebundleName,
+ resourcebundleId,
+ ResourceBundleManager.getManager(r.getProject()));
+ vcManager.addVResourceBundle(vRBId, vrb);
+
+ } else {
+ vrb = vcManager.getVResourceBundles(vRBId);
+ }
+
+ children.put(resourcebundleId, vrb);
+ }
+ }
+ if (r instanceof IContainer) {
+ if (!r.isDerived()) { // Don't show the 'bin' folder
+ VirtualContainer vContainer = vcManager
+ .getContainer((IContainer) r);
+
+ if (vContainer == null) {
+ int count = RBFileUtils
+ .countRecursiveResourceBundle((IContainer) r);
+ vContainer = new VirtualContainer(container, count);
+ vcManager.addVContainer((IContainer) r, vContainer);
+ }
+
+ if (vContainer.getRbCount() != 0) {
+ // without resourcebundles
+ children.put("" + children.size(), r);
+ }
+ }
+ }
+ }
+ return children.values().toArray();
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof IContainer) {
+ return ((IContainer) element).getParent();
+ }
+ if (element instanceof IFile) {
+ String rbId = RBFileUtils
+ .getCorrespondingResourceBundleId((IFile) element);
+ return vcManager.getVResourceBundles(rbId);
+ }
+ if (element instanceof VirtualResourceBundle) {
+ Iterator<IResource> i = new HashSet<IResource>(
+ ((VirtualResourceBundle) element).getFiles()).iterator();
+ if (i.hasNext()) {
+ return i.next().getParent();
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof IWorkspaceRoot) {
+ try {
+ if (((IWorkspaceRoot) element).members().length > 0) {
+ return true;
+ }
+ } catch (CoreException e) {
+ }
+ }
+ if (element instanceof IProject) {
+ VirtualProject vProject = (VirtualProject) vcManager
+ .getContainer((IProject) element);
+ if (vProject != null && vProject.isFragment()) {
+ return false;
+ }
+ }
+ if (element instanceof IContainer) {
+ try {
+ VirtualContainer vContainer = vcManager
+ .getContainer((IContainer) element);
+ if (vContainer != null) {
+ return vContainer.getRbCount() > 0 ? true : false;
+ } else if (((IContainer) element).members().length > 0) {
+ return true;
+ }
+ } catch (CoreException e) {
+ }
+ }
+ if (element instanceof VirtualResourceBundle) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void dispose() {
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ TapiJIPreferences.removePropertyChangeListener(this);
+ vcManager.reset();
+ unregisterAllResourceBundleListner();
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ this.viewer = (StructuredViewer) viewer;
+ }
+
+ @Override
+ // TODO remove ResourceChangelistner and add ResourceBundleChangelistner
+ public void resourceChanged(final IResourceChangeEvent event) {
+
+ final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ final IResource res = delta.getResource();
+
+ if (!RBFileUtils.isResourceBundleFile(res)) {
+ return true;
+ }
+
+ switch (delta.getKind()) {
+ case IResourceDelta.REMOVED:
+ recountParenthierarchy(res.getParent());
+ break;
+ // TODO remove unused VirtualResourceBundles and
+ // VirtualContainer from vcManager
+ case IResourceDelta.ADDED:
+ checkListner(res);
+ break;
+ case IResourceDelta.CHANGED:
+ if (delta.getFlags() != IResourceDelta.MARKERS) {
+ return true;
+ }
+ break;
+ }
+
+ refresh(res);
+
+ return true;
+ }
+ };
+
+ try {
+ event.getDelta().accept(visitor);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void resourceBundleChanged(ResourceBundleChangedEvent event) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(event.getProject());
+
+ switch (event.getType()) {
+ case ResourceBundleChangedEvent.ADDED:
+ case ResourceBundleChangedEvent.DELETED:
+ IResource res = rbmanager.getRandomFile(event.getBundle());
+ IContainer hostContainer;
+
+ if (res == null) {
+ try {
+ hostContainer = event.getProject()
+ .getFile(event.getBundle()).getParent();
+ } catch (Exception e) {
+ refresh(null);
+ return;
+ }
+ } else {
+ VirtualProject vProject = (VirtualProject) vcManager
+ .getContainer(res.getProject());
+ if (vProject != null && vProject.isFragment()) {
+ IProject hostProject = vProject.getHostProject();
+ hostContainer = ResourceUtils.getCorrespondingFolders(
+ res.getParent(), hostProject);
+ } else {
+ hostContainer = res.getParent();
+ }
+ }
+
+ recountParenthierarchy(hostContainer);
+ refresh(null);
+ break;
+ }
+
+ }
+
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) {
+ vcManager.reset();
+
+ refresh(root);
+ }
+ }
+
+ // TODO problems with remove a hole ResourceBundle
+ private void recountParenthierarchy(IContainer parent) {
+ if (parent.isDerived()) {
+ return; // Don't recount the 'bin' folder
+ }
+
+ VirtualContainer vContainer = vcManager.getContainer(parent);
+ if (vContainer != null) {
+ vContainer.recount();
+ }
+
+ if ((parent instanceof IFolder)) {
+ recountParenthierarchy(parent.getParent());
+ }
+ }
+
+ private void refresh(final IResource res) {
+ if (refresh == null || refresh.getResult() != null) {
+ refresh = new UIJob("refresh viewer") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (viewer != null && !viewer.getControl().isDisposed()) {
+ if (res != null) {
+ viewer.refresh(res.getProject(), true); // refresh(res);
+ } else {
+ viewer.refresh();
+ }
+ }
+ return Status.OK_STATUS;
+ }
+ };
+ }
+ refresh.schedule();
+ }
+
+ private void registerResourceBundleListner(IProject p) {
+ listenedProjects.add(p);
+
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ rbmanager.registerResourceBundleChangeListener(rbId, this);
+ }
+ }
+
+ private void unregisterAllResourceBundleListner() {
+ for (IProject p : listenedProjects) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(p);
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ rbmanager.unregisterResourceBundleChangeListener(rbId, this);
+ }
+ }
+ }
+
+ private void checkListner(IResource res) {
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res
+ .getProject());
+ String rbId = ResourceBundleManager.getResourceBundleId(res);
+ rbmanager.registerResourceBundleChangeListener(rbId, this);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
new file mode 100644
index 00000000..97fb1372
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
@@ -0,0 +1,207 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContainer;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContentManager;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualProject;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.navigator.IDescriptionProvider;
+
+public class ResourceBundleLabelProvider extends LabelProvider implements
+ ILabelProvider, IDescriptionProvider {
+ VirtualContentManager vcManager;
+
+ public ResourceBundleLabelProvider() {
+ super();
+ vcManager = VirtualContentManager.getVirtualContentManager();
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ Image returnImage = null;
+ if (element instanceof IProject) {
+ VirtualProject p = (VirtualProject) vcManager
+ .getContainer((IProject) element);
+ if (p != null && p.isFragment()) {
+ return returnImage = ImageUtils
+ .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE);
+ } else {
+ returnImage = PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_PROJECT);
+ }
+ }
+ if ((element instanceof IContainer) && (returnImage == null)) {
+ returnImage = PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_OBJ_FOLDER);
+ }
+ if (element instanceof VirtualResourceBundle) {
+ returnImage = ImageUtils
+ .getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
+ }
+ if (element instanceof IFile) {
+ if (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;
+ }
+
+ @Override
+ public String getText(Object element) {
+
+ StringBuilder text = new StringBuilder();
+ if (element instanceof IContainer) {
+ IContainer container = (IContainer) element;
+ text.append(container.getName());
+
+ if (element instanceof IProject) {
+ VirtualContainer vproject = vcManager
+ .getContainer((IProject) element);
+ // if (vproject != null && vproject instanceof VirtualFragment)
+ // text.append("�");
+ }
+
+ VirtualContainer vContainer = vcManager.getContainer(container);
+ if (vContainer != null && vContainer.getRbCount() != 0) {
+ text.append(" [" + vContainer.getRbCount() + "]");
+ }
+
+ }
+ if (element instanceof VirtualResourceBundle) {
+ text.append(((VirtualResourceBundle) element).getName());
+ }
+ if (element instanceof IFile) {
+ if (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);
+ }
+ return text.toString();
+ }
+
+ @Override
+ public String getDescription(Object anElement) {
+ if (anElement instanceof IResource) {
+ return ((IResource) anElement).getName();
+ }
+ if (anElement instanceof VirtualResourceBundle) {
+ return ((VirtualResourceBundle) anElement).getName();
+ }
+ return null;
+ }
+
+ private boolean checkMarkers(Object element) {
+ if (element instanceof IResource) {
+ IMarker[] ms = null;
+ try {
+ if ((ms = ((IResource) element).findMarkers(
+ EditorUtils.RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE)).length > 0) {
+ return true;
+ }
+
+ if (element instanceof IContainer) {
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders(
+ (IContainer) element,
+ FragmentProjectUtils
+ .getFragments(((IContainer) element)
+ .getProject()));
+
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer) {
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = 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) {
+ }
+ }
+ 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;
+ }
+
+}
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
new file mode 100644
index 00000000..ca261701
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import java.util.Iterator;
+
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.AbstractTreeViewer;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.navigator.CommonViewer;
+
+public class ExpandAction extends Action implements IAction {
+ private CommonViewer viewer;
+
+ public ExpandAction(CommonViewer viewer) {
+ this.viewer = viewer;
+ setText("Expand Node");
+ setToolTipText("expand node");
+ setImageDescriptor(RBManagerActivator
+ .getImageDescriptor(ImageUtils.EXPAND));
+ }
+
+ @Override
+ public boolean isEnabled() {
+ IStructuredSelection sSelection = (IStructuredSelection) viewer
+ .getSelection();
+ if (sSelection.size() >= 1)
+ return true;
+ else
+ return false;
+ }
+
+ @Override
+ public void run() {
+ IStructuredSelection sSelection = (IStructuredSelection) viewer
+ .getSelection();
+ Iterator<?> it = sSelection.iterator();
+ while (it.hasNext()) {
+ viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS);
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
new file mode 100644
index 00000000..32951bf8
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
@@ -0,0 +1,56 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.Hover;
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
+import org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants.I18NProjectInformant;
+import org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants.RBMarkerInformant;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.navigator.CommonActionProvider;
+import org.eclipse.ui.navigator.CommonViewer;
+import org.eclipse.ui.navigator.ICommonActionExtensionSite;
+
+public class GeneralActionProvider extends CommonActionProvider {
+ private IAction expandAction;
+
+ public GeneralActionProvider() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void init(ICommonActionExtensionSite aSite) {
+ super.init(aSite);
+ // init Expand-Action
+ expandAction = new ExpandAction(
+ (CommonViewer) aSite.getStructuredViewer());
+
+ // activate View-Hover
+ List<HoverInformant> informants = new ArrayList<HoverInformant>();
+ informants.add(new I18NProjectInformant());
+ informants.add(new RBMarkerInformant());
+
+ Hover hover = new Hover(Display.getCurrent().getActiveShell(),
+ informants);
+ hover.activateHoverHelp(((CommonViewer) aSite.getStructuredViewer())
+ .getTree());
+ }
+
+ @Override
+ public void fillContextMenu(IMenuManager menu) {
+ menu.appendToGroup("expand", expandAction);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
new file mode 100644
index 00000000..59d24916
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IWorkbenchPage;
+
+public class OpenVRBAction extends Action {
+ private ISelectionProvider selectionProvider;
+
+ public OpenVRBAction(ISelectionProvider selectionProvider) {
+ this.selectionProvider = selectionProvider;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
+ .getSelection();
+ if (sSelection.size() == 1)
+ return true;
+ else
+ return false;
+ }
+
+ @Override
+ public void run() {
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider
+ .getSelection();
+ if (sSelection.size() == 1
+ && sSelection.getFirstElement() instanceof VirtualResourceBundle) {
+ VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection
+ .getFirstElement();
+ IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+
+ EditorUtils.openEditor(wp, vRB.getRandomFile(),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR);
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
new file mode 100644
index 00000000..94286918
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.navigator.CommonActionProvider;
+import org.eclipse.ui.navigator.ICommonActionConstants;
+import org.eclipse.ui.navigator.ICommonActionExtensionSite;
+
+/*
+ * Will be only active for VirtualResourceBundeles
+ */
+public class VirtualRBActionProvider extends CommonActionProvider {
+ private IAction openAction;
+
+ public VirtualRBActionProvider() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void init(ICommonActionExtensionSite aSite) {
+ super.init(aSite);
+ openAction = new OpenVRBAction(aSite.getViewSite()
+ .getSelectionProvider());
+ }
+
+ @Override
+ public void fillActionBars(IActionBars actionBars) {
+ actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
+ openAction);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
new file mode 100644
index 00000000..daba43ec
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
@@ -0,0 +1,232 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+
+public class I18NProjectInformant implements HoverInformant {
+ private String locales;
+ private String fragments;
+ private boolean show = false;
+
+ private Composite infoComposite;
+ private Label localeLabel;
+ private Composite localeGroup;
+ private Label fragmentsLabel;
+ private Composite fragmentsGroup;
+
+ private GridData infoData;
+ private GridData showLocalesData;
+ private GridData showFragmentsData;
+
+ @Override
+ public Composite getInfoComposite(Object data, Composite parent) {
+ show = false;
+
+ if (infoComposite == null) {
+ infoComposite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 1;
+ layout.horizontalSpacing = 0;
+ infoComposite.setLayout(layout);
+
+ infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ infoComposite.setLayoutData(infoData);
+ }
+
+ if (data instanceof IProject) {
+ addLocale(infoComposite, data);
+ addFragments(infoComposite, data);
+ }
+
+ if (show) {
+ infoData.heightHint = -1;
+ infoData.widthHint = -1;
+ } else {
+ infoData.heightHint = 0;
+ infoData.widthHint = 0;
+ }
+
+ infoComposite.layout();
+ infoComposite.pack();
+ sinkColor(infoComposite);
+
+ return infoComposite;
+ }
+
+ @Override
+ public boolean show() {
+ return show;
+ }
+
+ private void setColor(Control control) {
+ Display display = control.getParent().getDisplay();
+
+ control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ }
+
+ private void sinkColor(Composite composite) {
+ setColor(composite);
+
+ for (Control c : composite.getChildren()) {
+ setColor(c);
+ if (c instanceof Composite) {
+ sinkColor((Composite) c);
+ }
+ }
+ }
+
+ private void addLocale(Composite parent, Object data) {
+ if (localeGroup == null) {
+ localeGroup = new Composite(parent, SWT.NONE);
+ localeLabel = new Label(localeGroup, SWT.SINGLE);
+
+ showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ localeGroup.setLayoutData(showLocalesData);
+ }
+
+ locales = getProvidedLocales(data);
+
+ if (locales.length() != 0) {
+ localeLabel.setText(locales);
+ localeLabel.pack();
+ show = true;
+ // showLocalesData.heightHint = -1;
+ // showLocalesData.widthHint=-1;
+ } else {
+ localeLabel.setText("No Language Provided");
+ localeLabel.pack();
+ show = true;
+ // showLocalesData.heightHint = 0;
+ // showLocalesData.widthHint = 0;
+ }
+
+ // localeGroup.layout();
+ localeGroup.pack();
+ }
+
+ private void addFragments(Composite parent, Object data) {
+ if (fragmentsGroup == null) {
+ fragmentsGroup = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ fragmentsGroup.setLayout(layout);
+
+ showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ fragmentsGroup.setLayoutData(showFragmentsData);
+
+ Composite fragmentTitleGroup = new Composite(fragmentsGroup,
+ SWT.NONE);
+ layout = new GridLayout(2, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 5;
+ fragmentTitleGroup.setLayout(layout);
+
+ Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
+ fragmentImageLabel.setImage(ImageUtils
+ .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
+ fragmentImageLabel.pack();
+
+ Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
+ fragementTitleLabel.setText("Project Fragments:");
+ fragementTitleLabel.pack();
+ fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
+ }
+
+ fragments = getFragmentProjects(data);
+
+ if (fragments.length() != 0) {
+ fragmentsLabel.setText(fragments);
+ show = true;
+ showFragmentsData.heightHint = -1;
+ showFragmentsData.widthHint = -1;
+ fragmentsLabel.pack();
+ } else {
+ showFragmentsData.heightHint = 0;
+ showFragmentsData.widthHint = 0;
+ }
+
+ fragmentsGroup.layout();
+ fragmentsGroup.pack();
+ }
+
+ private String getProvidedLocales(Object data) {
+ if (data instanceof IProject) {
+ ResourceBundleManager rbmanger = ResourceBundleManager
+ .getManager((IProject) data);
+ Set<Locale> ls = rbmanger.getProjectProvidedLocales();
+
+ if (ls.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Provided Languages:\n");
+
+ int i = 0;
+ for (Locale l : ls) {
+ if (l != 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();
+ }
+ }
+
+ return "";
+ }
+
+ private String getFragmentProjects(Object data) {
+ if (data instanceof IProject) {
+ List<IProject> fragments = FragmentProjectUtils
+ .getFragments((IProject) data);
+ if (fragments.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+
+ int i = 0;
+ for (IProject f : fragments) {
+ sb.append(f.getName());
+ if (++i != fragments.size()) {
+ sb.append("\n");
+ }
+ }
+ return sb.toString();
+ }
+ }
+ return "";
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
new file mode 100644
index 00000000..8e2284e9
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
@@ -0,0 +1,281 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+
+public class RBMarkerInformant implements HoverInformant {
+ private int MAX_PROBLEMS = 20;
+ private boolean show = false;
+
+ private String title;
+ private String problems;
+
+ private Composite infoComposite;
+ private Composite titleGroup;
+ private Label titleLabel;
+ private Composite problemGroup;
+ private Label problemLabel;
+
+ private GridData infoData;
+ private GridData showTitleData;
+ private GridData showProblemsData;
+
+ @Override
+ public Composite getInfoComposite(Object data, Composite parent) {
+ show = false;
+
+ if (infoComposite == null) {
+ infoComposite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ infoComposite.setLayout(layout);
+
+ infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ infoComposite.setLayoutData(infoData);
+ }
+
+ if (data instanceof VirtualResourceBundle || data instanceof IResource) {
+ addTitle(infoComposite, data);
+ addProblems(infoComposite, data);
+ }
+
+ if (show) {
+ infoData.heightHint = -1;
+ infoData.widthHint = -1;
+ } else {
+ infoData.heightHint = 0;
+ infoData.widthHint = 0;
+ }
+
+ infoComposite.layout();
+ sinkColor(infoComposite);
+ infoComposite.pack();
+
+ return infoComposite;
+ }
+
+ @Override
+ public boolean show() {
+ return show;
+ }
+
+ private void setColor(Control control) {
+ Display display = control.getParent().getDisplay();
+
+ control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ }
+
+ private void sinkColor(Composite composite) {
+ setColor(composite);
+
+ for (Control c : composite.getChildren()) {
+ setColor(c);
+ if (c instanceof Composite) {
+ sinkColor((Composite) c);
+ }
+ }
+ }
+
+ private void addTitle(Composite parent, Object data) {
+ if (titleGroup == null) {
+ titleGroup = new Composite(parent, SWT.NONE);
+ titleLabel = new Label(titleGroup, SWT.SINGLE);
+
+ showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ titleGroup.setLayoutData(showTitleData);
+ }
+ title = getTitel(data);
+
+ if (title.length() != 0) {
+ titleLabel.setText(title);
+ show = true;
+ showTitleData.heightHint = -1;
+ showTitleData.widthHint = -1;
+ titleLabel.pack();
+ } else {
+ showTitleData.heightHint = 0;
+ showTitleData.widthHint = 0;
+ }
+
+ titleGroup.layout();
+ titleGroup.pack();
+ }
+
+ private void addProblems(Composite parent, Object data) {
+ if (problemGroup == null) {
+ problemGroup = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ problemGroup.setLayout(layout);
+
+ showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ problemGroup.setLayoutData(showProblemsData);
+
+ Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE);
+ layout = new GridLayout(2, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 5;
+ problemTitleGroup.setLayout(layout);
+
+ Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
+ warningImageLabel.setImage(ImageUtils
+ .getBaseImage(ImageUtils.WARNING_IMAGE));
+ warningImageLabel.pack();
+
+ Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
+ waringTitleLabel.setText("ResourceBundle-Problems:");
+ waringTitleLabel.pack();
+
+ problemLabel = new Label(problemGroup, SWT.SINGLE);
+ }
+
+ problems = getProblems(data);
+
+ if (problems.length() != 0) {
+ problemLabel.setText(problems);
+ show = true;
+ showProblemsData.heightHint = -1;
+ showProblemsData.widthHint = -1;
+ problemLabel.pack();
+ } else {
+ showProblemsData.heightHint = 0;
+ showProblemsData.widthHint = 0;
+ }
+
+ problemGroup.layout();
+ problemGroup.pack();
+ }
+
+ private String getTitel(Object data) {
+ if (data instanceof IFile) {
+ return ((IResource) data).getFullPath().toString();
+ }
+ if (data instanceof VirtualResourceBundle) {
+ return ((VirtualResourceBundle) data).getResourceBundleId();
+ }
+
+ return "";
+ }
+
+ private String getProblems(Object data) {
+ IMarker[] ms = null;
+
+ if (data instanceof IResource) {
+ IResource res = (IResource) data;
+ try {
+ if (res.exists()) {
+ ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ } else {
+ ms = new IMarker[0];
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ if (data instanceof IContainer) {
+ // add problem of same folder in the fragment-project
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders((IContainer) res,
+ FragmentProjectUtils.getFragments(res
+ .getProject()));
+
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer) {
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+
+ ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
+
+ if (data instanceof VirtualResourceBundle) {
+ VirtualResourceBundle vRB = (VirtualResourceBundle) data;
+
+ ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
+ IMarker[] file_ms;
+
+ Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB
+ .getResourceBundleId());
+ if (!rBundles.isEmpty()) {
+ for (IResource r : rBundles) {
+ try {
+ file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID,
+ false, IResource.DEPTH_INFINITE);
+ if (ms != null) {
+ ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils
+ .concatMarkerArray(ms, file_ms);
+ } else {
+ ms = file_ms;
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ int count = 0;
+
+ if (ms != null && ms.length != 0) {
+ for (IMarker m : ms) {
+ try {
+ sb.append(m.getAttribute(IMarker.MESSAGE));
+ sb.append("\n");
+ count++;
+ if (count == MAX_PROBLEMS && ms.length - count != 0) {
+ sb.append(" ... and ");
+ sb.append(ms.length - count);
+ sb.append(" other problems");
+ break;
+ }
+ } catch (CoreException e) {
+ }
+ ;
+ }
+ return sb.toString();
+ }
+
+ return "";
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
new file mode 100644
index 00000000..efb8810b
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.filters;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+public class ProblematicResourceBundleFilter extends ViewerFilter {
+
+ /**
+ * Shows only IContainer and VirtualResourcebundles with all his
+ * properties-files, which have RB_Marker.
+ */
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (element instanceof IFile) {
+ return true;
+ }
+ if (element instanceof VirtualResourceBundle) {
+ for (IResource f : ((VirtualResourceBundle) element).getFiles()) {
+ if (RBFileUtils.hasResourceBundleMarker(f)) {
+ return true;
+ }
+ }
+ }
+ if (element instanceof IContainer) {
+ try {
+ IMarker[] ms = null;
+ if ((ms = ((IContainer) element).findMarkers(
+ EditorUtils.RB_MARKER_ID, true,
+ IResource.DEPTH_INFINITE)).length > 0) {
+ return true;
+ }
+
+ List<IContainer> fragmentContainer = ResourceUtils
+ .getCorrespondingFolders((IContainer) element,
+ FragmentProjectUtils
+ .getFragments(((IContainer) element)
+ .getProject()));
+
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer) {
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(
+ EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = 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) {
+ }
+ }
+ return false;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rbe/.classpath b/org.eclipse.babel.tapiji.translator.rbe/.classpath
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rbe/.classpath
rename to org.eclipse.babel.tapiji.translator.rbe/.classpath
diff --git a/org.eclipse.babel.tapiji.translator.rbe/.project b/org.eclipse.babel.tapiji.translator.rbe/.project
new file mode 100644
index 00000000..6a4f6577
--- /dev/null
+++ b/org.eclipse.babel.tapiji.translator.rbe/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.babel.tapiji.translator.rbe</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs
rename to org.eclipse.babel.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs
diff --git a/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..b35fd66e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF
@@ -0,0 +1,8 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: ResourceBundleEditorAPI
+Bundle-SymbolicName: org.eclipse.babel.tapiji.translator.rbe
+Bundle-Version: 0.0.2.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.babel.tapiji.translator.rbe.babel.bundle
+Require-Bundle: org.eclipse.jface;bundle-version="3.6.2"
diff --git a/org.eclipselabs.tapiji.translator.rbe/build.properties b/org.eclipse.babel.tapiji.translator.rbe/build.properties
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rbe/build.properties
rename to org.eclipse.babel.tapiji.translator.rbe/build.properties
diff --git a/org.eclipselabs.tapiji.translator.rbe/epl-v10.html b/org.eclipse.babel.tapiji.translator.rbe/epl-v10.html
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rbe/epl-v10.html
rename to org.eclipse.babel.tapiji.translator.rbe/epl-v10.html
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
new file mode 100644
index 00000000..cdf73236
--- /dev/null
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java
@@ -0,0 +1,17 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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:
+ * Matthias Lettmayer - created interface to select a key in an editor (fixed issue 59)
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+public interface IMessagesEditor {
+ String getSelectedKey();
+
+ void setSelectedKey(String key);
+}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/.project b/org.eclipselabs.tapiji.tools.core.ui/.project
deleted file mode 100644
index a0f892f4..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.tools.core.ui</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF
deleted file mode 100644
index 3d0b91f9..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,35 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Ui
-Bundle-SymbolicName: org.eclipselabs.tapiji.tools.core.ui;singleton:=true
-Bundle-Version: 1.0.0.qualifier
-Bundle-Activator: org.eclipselabs.tapiji.tools.core.ui.Activator
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.jdt.ui;bundle-version="3.6.2",
- org.eclipselabs.tapiji.tools.core;bundle-version="0.0.2";visibility:=reexport,
- org.eclipse.ui.ide;bundle-version="3.6.2",
- org.eclipse.jface.text;bundle-version="3.6.1",
- org.eclipse.jdt.core;bundle-version="3.6.2",
- org.eclipse.core.resources;bundle-version="3.6.1",
- org.eclipse.ui.editors
-Bundle-ActivationPolicy: lazy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Export-Package: org.eclipselabs.tapiji.tools.core.ui,
- org.eclipselabs.tapiji.tools.core.ui.decorators,
- org.eclipselabs.tapiji.tools.core.ui.dialogs,
- org.eclipselabs.tapiji.tools.core.ui.filters,
- org.eclipselabs.tapiji.tools.core.ui.markers,
- org.eclipselabs.tapiji.tools.core.ui.menus,
- org.eclipselabs.tapiji.tools.core.ui.prefrences,
- org.eclipselabs.tapiji.tools.core.ui.quickfix,
- org.eclipselabs.tapiji.tools.core.ui.views.messagesview,
- org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd,
- org.eclipselabs.tapiji.tools.core.ui.widgets,
- org.eclipselabs.tapiji.tools.core.ui.widgets.event,
- org.eclipselabs.tapiji.tools.core.ui.widgets.filter,
- org.eclipselabs.tapiji.tools.core.ui.widgets.listener,
- org.eclipselabs.tapiji.tools.core.ui.widgets.provider,
- org.eclipselabs.tapiji.tools.core.ui.widgets.sorter
-Import-Package: org.eclipse.core.filebuffers,
- org.eclipse.ui.texteditor
diff --git a/org.eclipselabs.tapiji.tools.core.ui/build.properties b/org.eclipselabs.tapiji.tools.core.ui/build.properties
deleted file mode 100644
index 6f20375d..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/build.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- plugin.xml
diff --git a/org.eclipselabs.tapiji.tools.core.ui/plugin.xml b/org.eclipselabs.tapiji.tools.core.ui/plugin.xml
deleted file mode 100644
index 4c9083cc..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/plugin.xml
+++ /dev/null
@@ -1,125 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.views">
- <category
- id="org.eclipselabs.tapiji"
- name="Internationalization">
- </category>
- <view
- category="org.eclipselabs.tapiji"
- class="org.eclipselabs.tapiji.tools.core.ui.views.messagesview.MessagesView"
- icon="icons/resourcebundle.gif"
- id="org.eclipselabs.tapiji.tools.core.views.MessagesView"
- name="Resource-Bundle">
- </view>
- </extension>
- <extension
- point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension
- targetID="org.eclipse.jdt.ui.JavaPerspective">
- <view
- id="org.eclipselabs.tapiji.tools.core.views.MessagesView"
- ratio="0.5"
- relationship="right"
- relative="org.eclipse.ui.views.TaskList">
- </view>
- </perspectiveExtension>
- </extension>
- <extension
- point="org.eclipse.ui.menus">
- <menuContribution
- locationURI="popup:org.eclipse.ui.popup.any?before=additions">
- <menu
- id="org.eclipselabs.tapiji.tools.core.ui.menus.Internationalization"
- label="Internationalization"
- tooltip="Java Internationalization assistance">
- </menu>
- </menuContribution>
- <menuContribution
- locationURI="popup:org.eclipselabs.tapiji.tools.core.ui.menus.Internationalization?after=additions">
- <dynamic
- class="org.eclipselabs.tapiji.tools.core.ui.menus.InternationalizationMenu"
- id="org.eclipselabs.tapiji.tools.core.ui.menus.ExcludeResource">
- </dynamic>
- </menuContribution>
- </extension>
- <extension
- point="org.eclipse.ui.ide.markerResolution">
- <markerResolutionGenerator
- class="org.eclipselabs.tapiji.tools.core.builder.ViolationResolutionGenerator"
- markerType="org.eclipselabs.tapiji.tools.core.StringLiteralAuditMarker">
- </markerResolutionGenerator>
- <markerResolutionGenerator
- class="org.eclipselabs.tapiji.tools.core.builder.ViolationResolutionGenerator"
- markerType="org.eclipselabs.tapiji.tools.core.ResourceBundleAuditMarker">
- </markerResolutionGenerator>
- </extension>
- <extension
- point="org.eclipse.jdt.ui.javaElementFilters">
- <filter
- class="org.eclipselabs.tapiji.tools.core.ui.filters.PropertiesFileFilter"
- description="Filters only resource bundles"
- enabled="false"
- id="ResourceBundleFilter"
- name="ResourceBundleFilter">
- </filter>
- </extension>
- <extension
- point="org.eclipse.ui.decorators">
- <decorator
- adaptable="true"
- class="org.eclipselabs.tapiji.tools.core.ui.decorators.ExcludedResource"
- id="org.eclipselabs.tapiji.tools.core.decorators.ExcludedResource"
- label="Resource is excluded from Internationalization"
- lightweight="false"
- state="true">
- <enablement>
- <and>
- <objectClass
- name="org.eclipse.core.resources.IResource">
- </objectClass>
- <or>
- <objectClass
- name="org.eclipse.core.resources.IFolder">
- </objectClass>
- <objectClass
- name="org.eclipse.core.resources.IFile">
- </objectClass>
- </or>
- </and>
- </enablement>
- </decorator>
- </extension>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- class="org.eclipselabs.tapiji.tools.core.ui.prefrences.TapiHomePreferencePage"
- id="org.eclipselabs.tapiji.tools.core.TapiJIGeneralPrefPage"
- name="TapiJI">
- </page>
- <page
- category="org.eclipselabs.tapiji.tools.core.TapiJIGeneralPrefPage"
- class="org.eclipselabs.tapiji.tools.core.ui.prefrences.FilePreferencePage"
- id="org.eclipselabs.tapiji.tools.core.FilePrefPage"
- name="File Settings">
- </page>
- <page
- category="org.eclipselabs.tapiji.tools.core.TapiJIGeneralPrefPage"
- class="org.eclipselabs.tapiji.tools.core.ui.prefrences.BuilderPreferencePage"
- id="org.eclipselabs.tapiji.tools.core.BuilderPrefPage"
- name="Builder Settings">
- </page>
- </extension>
-
- <extension
- point="org.eclipse.ui.editors.markerUpdaters">
- <updater
- class="org.eclipselabs.tapiji.tools.core.ui.markers.MarkerUpdater"
- id="org.eclipselabs.tapiji.tools.core.ui.MarkerUpdater"
- markerType="org.eclipse.core.resources.problemmarker">
- </updater>
- </extension>
-
-</plugin>
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java
deleted file mode 100644
index 59f26760..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui;
-
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipselabs.tapiji.tools.core.ui"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java
deleted file mode 100644
index e0b12ca0..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.decorators;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.DecorationOverlayIcon;
-import org.eclipse.jface.viewers.IDecoration;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipselabs.tapiji.tools.core.model.IResourceExclusionListener;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceExclusionEvent;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-
-
-public class ExcludedResource implements ILabelDecorator,
- IResourceExclusionListener {
-
- private static final String ENTRY_SUFFIX = "[no i18n]";
- private static final Image OVERLAY_IMAGE_ON =
- ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
- private static final Image OVERLAY_IMAGE_OFF =
- ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
- private final List<ILabelProviderListener> label_provider_listener =
- new ArrayList<ILabelProviderListener> ();
-
- public boolean decorate(Object element) {
- boolean needsDecoration = false;
- if (element instanceof IFolder ||
- element instanceof IFile) {
- IResource resource = (IResource) element;
- if (!InternationalizationNature.hasNature(resource.getProject()))
- return false;
- try {
- ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
- if (!manager.isResourceExclusionListenerRegistered(this))
- manager.registerResourceExclusionListener(this);
- if (ResourceBundleManager.isResourceExcluded(resource)) {
- needsDecoration = true;
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
- return needsDecoration;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- label_provider_listener.add(listener);
- }
-
- @Override
- public void dispose() {
- ResourceBundleManager.unregisterResourceExclusionListenerFromAllManagers (this);
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- label_provider_listener.remove(listener);
- }
-
- @Override
- public void exclusionChanged(ResourceExclusionEvent event) {
- LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(this, event.getChangedResources().toArray());
- for (ILabelProviderListener l : label_provider_listener)
- l.labelProviderChanged(labelEvent);
- }
-
- @Override
- public Image decorateImage(Image image, Object element) {
- if (decorate(element)) {
- DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(image,
- Activator.getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
- IDecoration.TOP_RIGHT);
- return overlayIcon.createImage();
- } else {
- return image;
- }
- }
-
- @Override
- public String decorateText(String text, Object element) {
- if (decorate(element)) {
- return text + " " + ENTRY_SUFFIX;
- } else
- return text;
- }
-
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
deleted file mode 100644
index 1ff6136d..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
+++ /dev/null
@@ -1,153 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.LocaleUtils;
-
-
-public class AddLanguageDialoge extends Dialog{
- private Locale locale;
- private Shell shell;
-
- private Text titelText;
- private Text descriptionText;
- private Combo cmbLanguage;
- private Text language;
- private Text country;
- private Text variant;
-
-
-
-
- public AddLanguageDialoge(Shell parentShell){
- super(parentShell);
- shell = parentShell;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND);
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- GridLayout layout = new GridLayout(1,true);
- dialogArea.setLayout(layout);
-
- initDescription(titelArea);
- initCombo(dialogArea);
- initTextArea(dialogArea);
-
- titelArea.pack();
- dialogArea.pack();
- parent.pack();
-
- return dialogArea;
- }
-
- private void initDescription(Composite titelArea) {
- titelArea.setEnabled(false);
- titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, 1, 1));
- titelArea.setLayout(new GridLayout(1, true));
- titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
-
- titelText = new Text(titelArea, SWT.LEFT);
- titelText.setFont(new Font(shell.getDisplay(),shell.getFont().getFontData()[0].getName(), 11, SWT.BOLD));
- titelText.setText("Please, specify the desired language");
-
- descriptionText = new Text(titelArea, SWT.WRAP);
- descriptionText.setLayoutData(new GridData(450, 60)); //TODO improve
- descriptionText.setText("Note: " +
- "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. "+
- "If the locale is just provided of a ResourceBundle, no new file will be created.");
- }
-
- private void initCombo(Composite dialogArea) {
- cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN);
- cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
-
- final Locale[] locales = Locale.getAvailableLocales();
- final Set<Locale> localeSet = new HashSet<Locale>();
- List<String> localeNames = new LinkedList<String>();
-
- for (Locale l : locales){
- localeNames.add(l.getDisplayName());
- localeSet.add(l);
- }
-
- Collections.sort(localeNames);
-
- String[] s= new String[localeNames.size()];
- cmbLanguage.setItems(localeNames.toArray(s));
- cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0);
-
- cmbLanguage.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selectIndex = ((Combo)e.getSource()).getSelectionIndex();
- if (!cmbLanguage.getItem(selectIndex).equals(ResourceBundleManager.defaultLocaleTag)){
- Locale l = LocaleUtils.getLocaleByDisplayName(localeSet, cmbLanguage.getItem(selectIndex));
-
- language.setText(l.getLanguage());
- country.setText(l.getCountry());
- variant.setText(l.getVariant());
- }else {
- language.setText("");
- country.setText("");
- variant.setText("");
- }
- }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // TODO Auto-generated method stub
- }
- });
- }
-
- private void initTextArea(Composite dialogArea) {
- final Group group = new Group (dialogArea, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
- group.setLayout(new GridLayout(3, true));
- group.setText("Locale");
-
- Label languageLabel = new Label(group, SWT.SINGLE);
- languageLabel.setText("Language");
- Label countryLabel = new Label(group, SWT.SINGLE);
- countryLabel.setText("Country");
- Label variantLabel = new Label(group, SWT.SINGLE);
- variantLabel.setText("Variant");
-
- language = new Text(group, SWT.SINGLE);
- country = new Text(group, SWT.SINGLE);
- variant = new Text(group, SWT.SINGLE);
- }
-
- @Override
- protected void okPressed() {
- locale = new Locale(language.getText(), country.getText(), variant.getText());
-
- super.okPressed();
- }
-
- public Locale getSelectedLanguage() {
- return locale;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
deleted file mode 100644
index 499fff0d..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-public class CreatePatternDialoge extends Dialog{
- private String pattern;
- private Text patternText;
-
-
- public CreatePatternDialoge(Shell shell) {
- this(shell,"");
- }
-
- public CreatePatternDialoge(Shell shell, String pattern) {
- super(shell);
- this.pattern = pattern;
-// setShellStyle(SWT.RESIZE);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, true));
- composite.setLayoutData(new GridData(SWT.FILL,SWT.TOP, false, false));
-
- Label descriptionLabel = new Label(composite, SWT.NONE);
- descriptionLabel.setText("Enter a regular expression:");
-
- patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
- GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
- gData.widthHint = 400;
- gData.heightHint = 60;
- patternText.setLayoutData(gData);
- patternText.setText(pattern);
-
-
-
- return composite;
- }
-
- @Override
- protected void okPressed() {
- pattern = patternText.getText();
-
- super.okPressed();
- }
-
- public String getPattern(){
- return pattern;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
deleted file mode 100644
index f2cd09da..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
+++ /dev/null
@@ -1,377 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.LocaleUtils;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-
-
-public class CreateResourceBundleEntryDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
-
- private ResourceBundleManager manager;
- private Collection<String> availableBundles;
-
- private Text txtKey;
- private Combo cmbRB;
- private Text txtDefaultText;
- private Combo cmbLanguage;
-
- private Button okButton;
- private Button cancelButton;
-
- /*** Dialog Model ***/
- String selectedRB = "";
- String selectedLocale = "";
- String selectedKey = "";
- String selectedDefaultText = "";
-
- /*** MODIFY LISTENER ***/
- ModifyListener rbModifyListener;
-
- public CreateResourceBundleEntryDialog(Shell parentShell,
- ResourceBundleManager manager,
- String preselectedKey,
- String preselectedMessage,
- String preselectedBundle,
- String preselectedLocale) {
- super(parentShell);
- this.manager = manager;
- this.availableBundles = manager.getResourceBundleNames();
- this.selectedKey = preselectedKey != null ? preselectedKey.trim() : preselectedKey;
- this.selectedDefaultText = preselectedMessage;
- this.selectedRB = preselectedBundle;
- this.selectedLocale = preselectedLocale;
- }
-
- 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;
-
- 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();
- }
-
- 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);
- int index = 0;
- int iSel = -1;
- for (Locale l : manager.getProvidedLocales(selectedBundle)) {
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (displayName.equals(selectedLocale))
- iSel = index;
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- if (index == iSel)
- cmbLanguage.select(iSel);
- index++;
- }
-
- if (locales.size() > 0) {
- cmbLanguage.select(0);
- selectedLocale = cmbLanguage.getText();
- }
-
- cmbLanguage.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedLocale = cmbLanguage.getText();
- validate();
- }
- });
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructRBSection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource Bundle");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Specify the key of the new resource as well as the Resource-Bundle in\n" +
- "which the resource" +
- "should be added.\n");
-
- // Schl�ssel
- final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblKey.setLayoutData(lblKeyGrid);
- lblKey.setText("Key:");
-
- txtKey = new Text (group, SWT.BORDER);
- txtKey.setText(selectedKey);
- txtKey.setEditable(selectedKey.trim().length() == 0 || selectedKey.indexOf("[Platzhalter]")>=0);
- 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
-
- // Insert new Resource-Bundle reference
- Locale locale = LocaleUtils.getLocaleByDisplayName( manager.getProvidedLocales(selectedRB), selectedLocale); // new Locale(""); // retrieve locale
-
- try {
- manager.addResourceBundleEntry (selectedRB, selectedKey, locale, selectedDefaultText);
- } catch (ResourceBundleException e) {
- Logger.logError(e);
- }
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Create Resource-Bundle entry");
- }
-
- @Override
- public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("New Resource-Bundle entry");
- this.setMessage("Please, specify details about the new Resource-Bundle entry");
- }
-
- protected void validate () {
- // Check Resource-Bundle ids
- boolean keyValid = false;
- boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey);
- boolean rbValid = false;
- boolean textValid = false;
- boolean localeValid = LocaleUtils.containsLocaleByDisplayName(manager.getProvidedLocales(selectedRB), selectedLocale);
-
- for (String rbId : this.availableBundles) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
-
- if (!manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
-
- if (selectedDefaultText.trim().length() > 0)
- textValid = true;
-
- // print Validation summary
- String errorMessage = null;
- if (selectedKey.trim().length() == 0)
- errorMessage = "No resource key specified.";
- else if (! keyValidChar)
- errorMessage = "The specified resource key contains invalid characters.";
- else if (! keyValid)
- errorMessage = "The specified resource key is already existing.";
- else if (! rbValid)
- errorMessage = "The specified Resource-Bundle does not exist.";
- else if (! localeValid)
- errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
- else if (! textValid)
- errorMessage = "No default translation specified.";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
-
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
- close();
- }
- });
-
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
deleted file mode 100644
index f07a9d12..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
+++ /dev/null
@@ -1,114 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ListDialog;
-
-
-public class FragmentProjectSelectionDialog extends ListDialog{
- private IProject hostproject;
- private List<IProject> allProjects;
-
-
- public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, List<IProject> fragmentprojects){
- super(parent);
- this.hostproject = hostproject;
- this.allProjects = new ArrayList<IProject>(fragmentprojects);
- allProjects.add(0,hostproject);
-
- init();
- }
-
- private void init() {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following plug-ins:");
- this.setTitle("Project Selector");
- this.setContentProvider(new IProjectContentProvider());
- this.setLabelProvider(new IProjectLabelProvider());
-
- this.setInput(allProjects);
- }
-
- public IProject getSelectedProject() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (IProject) selection[0];
- return null;
- }
-
-
- //private classes--------------------------------------------------------
- class IProjectContentProvider implements IStructuredContentProvider {
-
- @Override
- public Object[] getElements(Object inputElement) {
- List<IProject> resources = (List<IProject>) inputElement;
- return resources.toArray();
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
- }
-
- }
-
- class IProjectLabelProvider implements ILabelProvider {
-
- @Override
- public Image getImage(Object element) {
- return PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJ_PROJECT);
- }
-
- @Override
- public String getText(Object element) {
- IProject p = ((IProject) element);
- String text = p.getName();
- if (p.equals(hostproject)) text += " [host project]";
- else text += " [fragment project]";
- return text;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
deleted file mode 100644
index c95c74b7..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
+++ /dev/null
@@ -1,130 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-public class GenerateBundleAccessorDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
-
- private Text bundleAccessor;
- private Text packageName;
-
- public GenerateBundleAccessorDialog(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructBASection (dialogArea);
- //constructDefaultSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructBASection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource Bundle");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
-
- // Schl�ssel
- final Label lblBA = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblBAGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblBA.setLayoutData(lblBAGrid);
- lblBA.setText("Class-Name:");
-
- bundleAccessor = new Text (group, SWT.BORDER);
- bundleAccessor.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-
- // Resource-Bundle
- final Label lblPkg = new Label (group, SWT.NONE);
- lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblPkg.setText("Package:");
-
- packageName = new Text (group, SWT.BORDER);
- packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- }
-
- protected void initContent () {
- bundleAccessor.setText("BundleAccessor");
- packageName.setText("a.b");
- }
-
- /*
- protected void constructDefaultSection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1));
- group.setText("Basis-Text");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
-
- // Text
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 80;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Text:");
-
- txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER);
- txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
-
- // Sprache
- final Label lblLanguage = new Label (group, SWT.NONE);
- lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblLanguage.setText("Sprache (Land):");
-
- cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- } */
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Create Resource-Bundle Accessor");
- }
-
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
deleted file mode 100644
index 73982065..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
+++ /dev/null
@@ -1,424 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.ResourceSelector;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
-
-
-public class QueryResourceBundleEntryDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
- private static int SEARCH_FULLTEXT = 0;
- private static int SEARCH_KEY = 1;
-
- private ResourceBundleManager manager;
- private Collection<String> availableBundles;
- private int searchOption = SEARCH_FULLTEXT;
- private String resourceBundle = "";
-
- private Combo cmbRB;
-
- private Text txtKey;
- private Button btSearchText;
- private Button btSearchKey;
- private Combo cmbLanguage;
- private ResourceSelector resourceSelector;
- private Text txtPreviewText;
-
- private Button okButton;
- private Button cancelButton;
-
- /*** DIALOG MODEL ***/
- private String selectedRB = "";
- private String preselectedRB = "";
- private Locale selectedLocale = null;
- private String selectedKey = "";
-
-
- public QueryResourceBundleEntryDialog(Shell parentShell, ResourceBundleManager manager, String bundleName) {
- super(parentShell);
- this.manager = manager;
- // init available resource bundles
- this.availableBundles = manager.getResourceBundleNames();
- this.preselectedRB = bundleName;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructSearchSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initContent() {
- // init available resource bundles
- cmbRB.removeAll();
- int i = 0;
- for (String bundle : availableBundles) {
- cmbRB.add(bundle);
- if (bundle.equals(preselectedRB)) {
- cmbRB.select(i);
- cmbRB.setEnabled(false);
- }
- i++;
- }
-
- if (availableBundles.size() > 0) {
- if (preselectedRB.trim().length() == 0) {
- cmbRB.select(0);
- cmbRB.setEnabled(true);
- }
- }
-
- cmbRB.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
- });
-
- // init available translations
- //updateAvailableLanguages();
-
- // init resource selector
- updateResourceSelector();
-
- // update search options
- updateSearchOptions();
- }
-
- protected void updateResourceSelector () {
- resourceBundle = cmbRB.getText();
- resourceSelector.setResourceBundle(resourceBundle);
- }
-
- protected void updateSearchOptions () {
- searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT);
-// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
-// lblLanguage.setEnabled(cmbLanguage.getEnabled());
-
- // update ResourceSelector
- resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS);
- }
-
- protected void updateAvailableLanguages () {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- for (Locale l : locales) {
- String displayName = l.getDisplayName();
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- }
-
-// if (locales.size() > 0) {
-// cmbLanguage.select(0);
- updateSelectedLocale();
-// }
- }
-
- protected void updateSelectedLocale () {
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- Iterator<Locale> it = locales.iterator();
- String selectedLocale = cmbLanguage.getText();
- while (it.hasNext()) {
- Locale l = it.next();
- if (l.getDisplayName().equals(selectedLocale)) {
- resourceSelector.setDisplayLocale(l);
- break;
- }
- }
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructSearchSection (Composite parent) {
- final Group group = new Group (parent, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource selection");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
- // TODO export as help text
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
- infoGrid.heightHint = 70;
- infoLabel.setLayoutData(infoGrid);
- infoLabel.setText("Select the resource that needs to be refrenced. This is achieved in two\n" +
- "steps. First select the Resource-Bundle in which the resource is located. \n" +
- "In a last step you need to choose the required resource.");
-
- // Resource-Bundle
- final Label lblRB = new Label (group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblRB.setText("Resource-Bundle:");
-
- cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- cmbRB.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- });
-
- // Search-Options
- final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT);
- spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- Composite searchOptions = new Composite(group, SWT.NONE);
- searchOptions.setLayout(new GridLayout (2, true));
-
- btSearchText = new Button (searchOptions, SWT.RADIO);
- btSearchText.setText("Full-text");
- btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
- btSearchText.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
-
- btSearchKey = new Button (searchOptions, SWT.RADIO);
- btSearchKey.setText("Key");
- btSearchKey.setSelection(searchOption == SEARCH_KEY);
- btSearchKey.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
-
- // Sprache
-// lblLanguage = new Label (group, SWT.NONE);
-// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
-// lblLanguage.setText("Language (Country):");
-//
-// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
-// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-// cmbLanguage.addSelectionListener(new SelectionListener () {
-//
-// @Override
-// public void widgetDefaultSelected(SelectionEvent e) {
-// updateSelectedLocale();
-// }
-//
-// @Override
-// public void widgetSelected(SelectionEvent e) {
-// updateSelectedLocale();
-// }
-//
-// });
-// cmbLanguage.addModifyListener(new ModifyListener() {
-// @Override
-// public void modifyText(ModifyEvent e) {
-// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText());
-// validate();
-// }
-// });
-
- // Filter
- final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblKey.setLayoutData(lblKeyGrid);
- lblKey.setText("Filter:");
-
- txtKey = new Text (group, SWT.BORDER);
- txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-
- // Add selector for property keys
- final Label lblKeys = new Label (group, SWT.NONE);
- lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1));
- lblKeys.setText("Resource:");
-
- resourceSelector = new ResourceSelector (group, SWT.NONE, manager, cmbRB.getText(), searchOption, null, true);
- GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
- resourceSelectionData.heightHint = 150;
- resourceSelectionData.widthHint = 400;
- resourceSelector.setLayoutData(resourceSelectionData);
- resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() {
-
- @Override
- public void selectionChanged(ResourceSelectionEvent e) {
- selectedKey = e.getSelectedKey();
- updatePreviewLabel(e.getSelectionSummary());
- validate();
- }
- });
-
-// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL);
-// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1));
-
- // Preview
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 120;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Preview:");
-
- txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- txtPreviewText.setEditable(false);
- GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1);
- txtPreviewText.setLayoutData(lblTextGrid2);
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Insert Resource-Bundle-Reference");
- }
-
- @Override
- public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("Reference a Resource");
- this.setMessage("Please, specify details about the required Resource-Bundle reference");
- }
-
- protected void updatePreviewLabel (String previewText) {
- txtPreviewText.setText(previewText);
- }
-
- protected void validate () {
- // Check Resource-Bundle ids
- boolean rbValid = false;
- boolean localeValid = false;
- boolean keyValid = false;
-
- for (String rbId : this.availableBundles) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
-
- if (selectedLocale != null)
- localeValid = true;
-
- if (manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
-
- // print Validation summary
- String errorMessage = null;
- if (! rbValid)
- errorMessage = "The specified Resource-Bundle does not exist";
-// else if (! localeValid)
-// errorMessage = "The specified Locale does not exist for the selecte Resource-Bundle";
- else if (! keyValid)
- errorMessage = "No resource selected";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
-
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
- close();
- }
- });
-
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
- }
-
- public String getSelectedResourceBundle () {
- return selectedRB;
- }
-
- public String getSelectedResource () {
- return selectedKey;
- }
-
- public Locale getSelectedLocale () {
- return selectedLocale;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
deleted file mode 100644
index 3a638f0d..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ListDialog;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-
-
-public class RemoveLanguageDialoge extends ListDialog{
- private IProject project;
-
-
- public RemoveLanguageDialoge(IProject project, Shell shell) {
- super(shell);
- this.project=project;
-
- initDialog();
- }
-
- protected void initDialog () {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following languages to delete:");
- this.setTitle("Language Selector");
- this.setContentProvider(new RBContentProvider());
- this.setLabelProvider(new RBLabelProvider());
-
- this.setInput(ResourceBundleManager.getManager(project).getProjectProvidedLocales());
- }
-
- public Locale getSelectedLanguage() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (Locale) selection[0];
- return null;
- }
-
-
- //private classes-------------------------------------------------------------------------------------
- class RBContentProvider implements IStructuredContentProvider {
-
- @Override
- public Object[] getElements(Object inputElement) {
- Set<Locale> resources = (Set<Locale>) inputElement;
- return resources.toArray();
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- class RBLabelProvider implements ILabelProvider {
-
- @Override
- public Image getImage(Object element) {
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- }
-
- @Override
- public String getText(Object element) {
- Locale l = ((Locale) element);
- String text = l.getDisplayName();
- if (text==null || text.equals("")) text="default";
- else text += " - "+l.getLanguage()+" "+l.getCountry()+" "+l.getVariant();
- return text;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
deleted file mode 100644
index 99ef6c33..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
+++ /dev/null
@@ -1,423 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.ResourceSelector;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
-
-
-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 ResourceBundleManager manager;
- private Collection<String> availableBundles;
- 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, ResourceBundleManager manager, String bundleName) {
- super(parentShell);
- this.manager = manager;
- // init available resource bundles
- this.availableBundles = manager.getResourceBundleNames();
- this.preselectedRB = bundleName;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructSearchSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initContent() {
- // init available resource bundles
- cmbRB.removeAll();
- int i = 0;
- for (String bundle : availableBundles) {
- cmbRB.add(bundle);
- if (bundle.equals(preselectedRB)) {
- cmbRB.select(i);
- cmbRB.setEnabled(false);
- }
- i++;
- }
-
- if (availableBundles.size() > 0) {
- if (preselectedRB.trim().length() == 0) {
- cmbRB.select(0);
- cmbRB.setEnabled(true);
- }
- }
-
- cmbRB.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
- });
-
- // init available translations
- //updateAvailableLanguages();
-
- // init resource selector
- updateResourceSelector();
-
- // update search options
- updateSearchOptions();
- }
-
- protected void updateResourceSelector () {
- resourceBundle = cmbRB.getText();
- resourceSelector.setResourceBundle(resourceBundle);
- }
-
- protected void updateSearchOptions () {
- searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT);
-// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
-// lblLanguage.setEnabled(cmbLanguage.getEnabled());
-
- // update ResourceSelector
- resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS);
- }
-
- protected void updateAvailableLanguages () {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- for (Locale l : locales) {
- String displayName = l.getDisplayName();
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- }
-
-// if (locales.size() > 0) {
-// cmbLanguage.select(0);
- updateSelectedLocale();
-// }
- }
-
- protected void updateSelectedLocale () {
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- Iterator<Locale> it = locales.iterator();
- String selectedLocale = cmbLanguage.getText();
- while (it.hasNext()) {
- Locale l = it.next();
- if (l.getDisplayName().equals(selectedLocale)) {
- resourceSelector.setDisplayLocale(l);
- break;
- }
- }
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructSearchSection (Composite parent) {
- final Group group = new Group (parent, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource selection");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
- // TODO export as help text
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
- infoGrid.heightHint = 70;
- infoLabel.setLayoutData(infoGrid);
- infoLabel.setText("Select the resource that needs to be refrenced. This is 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, manager, cmbRB.getText(), searchOption, null, true);
- GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
- resourceSelectionData.heightHint = 150;
- resourceSelectionData.widthHint = 400;
- resourceSelector.setLayoutData(resourceSelectionData);
- resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() {
-
- @Override
- public void selectionChanged(ResourceSelectionEvent e) {
- selectedKey = e.getSelectedKey();
- updatePreviewLabel(e.getSelectionSummary());
- validate();
- }
- });
-
-// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL);
-// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1));
-
- // Preview
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 120;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Preview:");
-
- txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- txtPreviewText.setEditable(false);
- GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1);
- txtPreviewText.setLayoutData(lblTextGrid2);
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Select Resource-Bundle entry");
- }
-
- @Override
- public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("Select a Resource-Bundle entry");
- this.setMessage("Please, select a resource of a particular Resource-Bundle");
- }
-
- protected void updatePreviewLabel (String previewText) {
- txtPreviewText.setText(previewText);
- }
-
- protected void validate () {
- // Check Resource-Bundle ids
- boolean rbValid = false;
- boolean localeValid = false;
- boolean keyValid = false;
-
- for (String rbId : this.availableBundles) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
-
- if (selectedLocale != null)
- localeValid = true;
-
- if (manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
-
- // print Validation summary
- String errorMessage = null;
- if (! rbValid)
- errorMessage = "The specified Resource-Bundle does not exist";
-// else if (! localeValid)
-// errorMessage = "The specified Locale does not exist for the selecte Resource-Bundle";
- else if (! keyValid)
- errorMessage = "No resource selected";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
-
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
- close();
- }
- });
-
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
- }
-
- public String getSelectedResourceBundle () {
- return selectedRB;
- }
-
- public String getSelectedResource () {
- return selectedKey;
- }
-
- public Locale getSelectedLocale () {
- return selectedLocale;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
deleted file mode 100644
index 890ceb3a..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.dialogs;
-
-import java.util.List;
-
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ListDialog;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-
-
-public class ResourceBundleSelectionDialog extends ListDialog {
-
- private IProject project;
-
- public ResourceBundleSelectionDialog(Shell parent, IProject project) {
- super(parent);
- this.project = project;
-
- initDialog ();
- }
-
- protected void initDialog () {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following Resource-Bundle to open:");
- this.setTitle("Resource-Bundle Selector");
- this.setContentProvider(new RBContentProvider());
- this.setLabelProvider(new RBLabelProvider());
- this.setBlockOnOpen(true);
-
- if (project != null)
- this.setInput(RBManager.getInstance(project).getMessagesBundleGroupNames());
- else
- this.setInput(RBManager.getAllMessagesBundleGroupNames());
- }
-
- public String getSelectedBundleId () {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (String) selection[0];
- return null;
- }
-
- class RBContentProvider implements IStructuredContentProvider {
-
- @Override
- public Object[] getElements(Object inputElement) {
- List<String> resources = (List<String>) inputElement;
- return resources.toArray();
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- class RBLabelProvider implements ILabelProvider {
-
- @Override
- public Image getImage(Object element) {
- // TODO Auto-generated method stub
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- }
-
- @Override
- public String getText(Object element) {
- // TODO Auto-generated method stub
- return ((String) element);
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
deleted file mode 100644
index cf92e76f..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.filters;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-
-public class PropertiesFileFilter extends ViewerFilter {
-
- private boolean debugEnabled = true;
-
- public PropertiesFileFilter() {
-
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (debugEnabled)
- return true;
-
- if (element.getClass().getSimpleName().equals("CompilationUnit"))
- return false;
-
- if (!(element instanceof IFile))
- return true;
-
- IFile file = (IFile) element;
-
- return file.getFileExtension().equalsIgnoreCase("properties");
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/MarkerUpdater.java
deleted file mode 100644
index 57a3697f..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/MarkerUpdater.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.markers;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.ui.texteditor.IMarkerUpdater;
-import org.eclipselabs.tapiji.tools.core.Logger;
-
-public class MarkerUpdater implements IMarkerUpdater {
-
- @Override
- public String getMarkerType() {
- return "org.eclipse.core.resources.problemmarker";
- }
-
- @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;
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java
deleted file mode 100644
index 8d6e57cd..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.markers;
-
-public class StringLiterals {
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java
deleted file mode 100644
index 3f6493fd..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java
+++ /dev/null
@@ -1,373 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.menus;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.MenuAdapter;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.AddLanguageDialoge;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.FragmentProjectSelectionDialog;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.GenerateBundleAccessorDialog;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.RemoveLanguageDialoge;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.core.util.LanguageUtils;
-
-
-public class InternationalizationMenu extends ContributionItem {
- private boolean excludeMode = true;
- private boolean internationalizationEnabled = false;
-
- private MenuItem mnuToggleInt;
- private MenuItem excludeResource;
- private MenuItem addLanguage;
- private MenuItem removeLanguage;
-
- public InternationalizationMenu() {}
-
- public InternationalizationMenu(String id) {
- super(id);
- }
-
- @Override
- public void fill(Menu menu, int index) {
- if (getSelectedProjects().size() == 0 ||
- !projectsSupported())
- return;
-
- // Toggle Internatinalization
- mnuToggleInt = new MenuItem (menu, SWT.PUSH);
- mnuToggleInt.addSelectionListener(new SelectionAdapter () {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runToggleInt();
- }
-
- });
-
- // Exclude Resource
- excludeResource = new MenuItem (menu, SWT.PUSH);
- excludeResource.addSelectionListener(new SelectionAdapter () {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runExclude();
- }
-
- });
-
- new MenuItem(menu, SWT.SEPARATOR);
-
- // Add Language
- addLanguage = new MenuItem(menu, SWT.PUSH);
- addLanguage.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runAddLanguage();
- }
-
- });
-
- // Remove Language
- removeLanguage = new MenuItem(menu, SWT.PUSH);
- removeLanguage.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runRemoveLanguage();
- }
-
- });
-
- menu.addMenuListener(new MenuAdapter () {
- public void menuShown (MenuEvent e) {
- updateStateToggleInt (mnuToggleInt);
- //updateStateGenRBAccessor (generateAccessor);
- updateStateExclude (excludeResource);
- updateStateAddLanguage (addLanguage);
- updateStateRemoveLanguage (removeLanguage);
- }
- });
- }
-
- protected void runGenRBAccessor () {
- GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(Display.getDefault().getActiveShell());
- if (dlg.open() != InputDialog.OK)
- return;
- }
-
- protected void updateStateGenRBAccessor (MenuItem menuItem) {
- Collection<IPackageFragment> frags = getSelectedPackageFragments();
- menuItem.setEnabled(frags.size() > 0);
- }
-
- protected void updateStateToggleInt (MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean enabled = projects.size() > 0;
- menuItem.setEnabled(enabled);
- setVisible(enabled);
- internationalizationEnabled = InternationalizationNature.hasNature(projects.iterator().next());
- //menuItem.setSelection(enabled && internationalizationEnabled);
-
- if (internationalizationEnabled)
- menuItem.setText("Disable Internationalization");
- else
- menuItem.setText("Enable Internationalization");
- }
-
- private Collection<IPackageFragment> getSelectedPackageFragments () {
- Collection<IPackageFragment> frags = new HashSet<IPackageFragment> ();
- IWorkbenchWindow window =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection ();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IPackageFragment) {
- IPackageFragment frag = (IPackageFragment) elem;
- if (!frag.isReadOnly())
- frags.add (frag);
- }
- }
- }
- return frags;
- }
-
- private Collection<IProject> getSelectedProjects () {
- Collection<IProject> projects = new HashSet<IProject> ();
- IWorkbenchWindow window =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection ();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (!(elem instanceof IResource)) {
- if (!(elem instanceof IAdaptable))
- continue;
- elem = ((IAdaptable) elem).getAdapter (IResource.class);
- if (!(elem instanceof IResource))
- continue;
- }
- if (!(elem instanceof IProject)) {
- elem = ((IResource) elem).getProject();
- if (!(elem instanceof IProject))
- continue;
- }
- if (((IProject)elem).isAccessible())
- projects.add ((IProject)elem);
-
- }
- }
- return projects;
- }
-
- protected boolean projectsSupported() {
- Collection<IProject> projects = getSelectedProjects ();
- for (IProject project : projects) {
- if (!InternationalizationNature.supportsNature(project))
- return false;
- }
-
- return true;
- }
-
- protected void runToggleInt () {
- Collection<IProject> projects = getSelectedProjects ();
- for (IProject project : projects) {
- toggleNature (project);
- }
- }
-
- private void toggleNature (IProject project) {
- if (InternationalizationNature.hasNature (project)) {
- InternationalizationNature.removeNature (project);
- } else {
- InternationalizationNature.addNature (project);
- }
- }
- protected void updateStateExclude (MenuItem menuItem) {
- Collection<IResource> resources = getSelectedResources();
- menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled);
- ResourceBundleManager manager = null;
- excludeMode = false;
-
- for (IResource res : resources) {
- if (manager == null || (manager.getProject() != res.getProject()))
- manager = ResourceBundleManager.getManager(res.getProject());
- try {
- if (!ResourceBundleManager.isResourceExcluded(res)) {
- excludeMode = true;
- }
- } catch (Exception e) { }
- }
-
- if (!excludeMode)
- menuItem.setText("Include Resource");
- else
- menuItem.setText("Exclude Resource");
- }
-
- private Collection<IResource> getSelectedResources () {
- Collection<IResource> resources = new HashSet<IResource> ();
- IWorkbenchWindow window =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection ();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IProject)
- continue;
-
- if (elem instanceof IResource) {
- resources.add ((IResource)elem);
- } else if (elem instanceof IJavaElement) {
- resources.add (((IJavaElement)elem).getResource());
- }
- }
- }
- return resources;
- }
-
- protected void runExclude () {
- final Collection<IResource> selectedResources = getSelectedResources ();
-
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
-
- ResourceBundleManager manager = null;
- pm.beginTask("Including resources to Internationalization", selectedResources.size());
-
- for (IResource res : selectedResources) {
- if (manager == null || (manager.getProject() != res.getProject()))
- manager = ResourceBundleManager.getManager(res.getProject());
- if (excludeMode)
- manager.excludeResource(res, pm);
- else
- manager.includeResource(res, pm);
- pm.worked(1);
- }
- pm.done();
- }
- });
- } catch (Exception e) {}
- }
-
- protected void updateStateAddLanguage(MenuItem menuItem){
- Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles=false;
- for (IProject p : projects){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
- }
-
- menuItem.setText("Add Language To Project");
- menuItem.setEnabled(projects.size() > 0 && hasResourceBundles);
- }
-
- protected void runAddLanguage() {
- AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(Display.getCurrent()));
- if (dialog.open() == InputDialog.OK) {
- final Locale locale = dialog.getSelectedLanguage();
-
- Collection<IProject> selectedProjects = getSelectedProjects();
- for (IProject project : selectedProjects){
- //check if project is fragmentproject and continue working with the hostproject, if host not member of selectedProjects
- if (FragmentProjectUtils.isFragment(project)){
- IProject host = FragmentProjectUtils.getFragmentHost(project);
- if (!selectedProjects.contains(host))
- project = host;
- else
- continue;
- }
-
- List<IProject> fragments = FragmentProjectUtils.getFragments(project);
-
- if (!fragments.isEmpty()) {
- FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog(
- Display.getCurrent().getActiveShell(), project,
- fragments);
-
- if (fragmentDialog.open() == InputDialog.OK)
- project = fragmentDialog.getSelectedProject();
- }
-
- final IProject selectedProject = project;
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- LanguageUtils.addLanguageToProject(selectedProject, locale);
- }
-
- });
-
- }
- }
- }
-
-
- protected void updateStateRemoveLanguage(MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles=false;
- if (projects.size() == 1){
- IProject project = projects.iterator().next();
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(project);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
- }
- menuItem.setText("Remove Language From Project");
- menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*&& more than one common languages contained*/);
- }
-
- protected void runRemoveLanguage() {
- final IProject project = getSelectedProjects().iterator().next();
- RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, new Shell(Display.getCurrent()));
-
-
- if (dialog.open() == InputDialog.OK) {
- final Locale locale = dialog.getSelectedLanguage();
- if (locale != null) {
- if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirm", "Do you really want remove all properties-files for "+locale.getDisplayName()+"?"))
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- LanguageUtils.removeLanguageFromProject(project, locale);
- }
- });
-
- }
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
deleted file mode 100644
index e43aef21..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.prefrences;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences;
-
-public class BuilderPreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
- private static final int INDENT = 20;
-
- private Button checkSameValueButton;
- private Button checkMissingValueButton;
- private Button checkMissingLanguageButton;
-
- private Button rbAuditButton;
-
- private Button sourceAuditButton;
-
-
- @Override
- public void init(IWorkbench workbench) {
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- @Override
- protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite composite = new Composite(parent, SWT.SHADOW_OUT);
-
- composite.setLayout(new GridLayout(1,false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
-
- Composite field = createComposite(parent, 0, 10);
- Label descriptionLabel = new Label(composite, SWT.NONE);
- descriptionLabel.setText("Select types of reported problems:");
-
- field = createComposite(composite, 0, 0);
- sourceAuditButton = new Button(field, SWT.CHECK);
- sourceAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RESOURCE));
- sourceAuditButton.setText("Check source code for non externalizated Strings");
-
- field = createComposite(composite, 0, 0);
- rbAuditButton = new Button(field, SWT.CHECK);
- rbAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
- rbAuditButton.setText("Check ResourceBundles on the following problems:");
- rbAuditButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- setRBAudits();
- }
- });
-
- field = createComposite(composite, INDENT, 0);
- checkMissingValueButton = new Button(field, SWT.CHECK);
- checkMissingValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
- checkMissingValueButton.setText("Missing translation for a key");
-
- field = createComposite(composite, INDENT, 0);
- checkSameValueButton = new Button(field, SWT.CHECK);
- checkSameValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
- checkSameValueButton.setText("Same translations for one key in diffrent languages");
-
- field = createComposite(composite, INDENT, 0);
- checkMissingLanguageButton = new Button(field, SWT.CHECK);
- checkMissingLanguageButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
- checkMissingLanguageButton.setText("Missing languages in a ResourceBundle");
-
- setRBAudits();
-
- composite.pack();
-
- return composite;
- }
-
- @Override
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
-
- sourceAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE));
- rbAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RB));
- checkMissingValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
- checkSameValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
- checkMissingLanguageButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
- }
-
- @Override
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
-
- prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE, sourceAuditButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, checkMissingValueButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE, checkSameValueButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, checkMissingLanguageButton.getSelection());
-
- return super.performOk();
- }
-
- private Composite createComposite(Composite parent, int marginWidth, int marginHeight) {
- Composite composite = new Composite(parent, SWT.NONE);
-
- GridLayout indentLayout = new GridLayout(1, false);
- indentLayout.marginWidth = marginWidth;
- indentLayout.marginHeight = marginHeight;
- indentLayout.verticalSpacing = 0;
- composite.setLayout(indentLayout);
-
- return composite;
- }
-
- protected void setRBAudits() {
- boolean selected = rbAuditButton.getSelection();
- checkMissingValueButton.setEnabled(selected);
- checkSameValueButton.setEnabled(selected);
- checkMissingLanguageButton.setEnabled(selected);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/FilePreferencePage.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
deleted file mode 100644
index ff6c1cbe..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
+++ /dev/null
@@ -1,192 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.prefrences;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.model.preferences.CheckItem;
-import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreatePatternDialoge;
-
-public class FilePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- private Table table;
- protected Object dialoge;
-
- private Button editPatternButton;
- private Button removePatternButton;
-
- @Override
- public void init(IWorkbench workbench) {
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- @Override
- protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite composite = new Composite(parent, SWT.SHADOW_OUT);
-
- composite.setLayout(new GridLayout(2,false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
-
- Label descriptionLabel = new Label(composite, SWT.WRAP);
- GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false);
- descriptionData.horizontalSpan=2;
- descriptionLabel.setLayoutData(descriptionData);
- descriptionLabel.setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files");
-
- table = new Table (composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- table.setLayoutData(data);
-
- table.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0){
- editPatternButton.setEnabled(true);
- removePatternButton.setEnabled(true);
- }else{
- editPatternButton.setEnabled(false);
- removePatternButton.setEnabled(false);
- }
- }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
- List<CheckItem> patternItems = TapiJIPreferences.getNonRbPatternAsList();
- for (CheckItem s : patternItems){
- s.toTableItem(table);
- }
-
- Composite sitebar = new Composite(composite, SWT.NONE);
- sitebar.setLayout(new GridLayout(1,false));
- sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
-
- Button addPatternButton = new Button(sitebar, SWT.NONE);
- addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- addPatternButton.setText("Add Pattern");
- addPatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseDown(MouseEvent e) {
- String pattern = "^.*/<BASENAME>"+"((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?"+ "\\.properties$";
- CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(),pattern);
- if (dialog.open() == InputDialog.OK) {
- pattern = dialog.getPattern();
-
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(pattern);
- item.setChecked(true);
- }
- }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
- editPatternButton = new Button(sitebar, SWT.NONE);
- editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- editPatternButton.setText("Edit");
- editPatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseDown(MouseEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0){
- String pattern = selection[0].getText();
-
- CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(), pattern);
- if (dialog.open() == InputDialog.OK) {
- pattern = dialog.getPattern();
- TableItem item = selection[0];
- item.setText(pattern);
- }
- }
- }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
-
- removePatternButton = new Button(sitebar, SWT.NONE);
- removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- removePatternButton.setText("Remove");
- removePatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseDown(MouseEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0)
- table.remove(table.indexOf(selection[0]));
- }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
- composite.pack();
-
- return composite;
- }
-
- @Override
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
-
- table.removeAll();
-
- List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs.getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
- for (CheckItem s : patterns){
- s.toTableItem(table);
- }
- }
-
- @Override
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
- List<CheckItem> patterns =new LinkedList<CheckItem>();
- for (TableItem i : table.getItems()){
- patterns.add(new CheckItem(i.getText(), i.getChecked()));
- }
-
- prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns));
-
- return super.performOk();
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
deleted file mode 100644
index 42450adf..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.prefrences;
-
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class TapiHomePreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
-
- @Override
- public void init(IWorkbench workbench) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected Control createContents(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1,true));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Label description = new Label(composite, SWT.WRAP);
- description.setText("See sub-pages for settings.");
-
- return parent;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
deleted file mode 100644
index aad8e719..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-
-
-public class CreateResourceBundleEntry implements IMarkerResolution2 {
-
- private String key;
- private String bundleId;
-
- public CreateResourceBundleEntry (String key, ResourceBundleManager manager, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
- }
-
- @Override
- public String getDescription() {
- return "Creates a new Resource-Bundle entry for the property-key '" + key + "'";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Create Resource-Bundle entry for '" + key + "'";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell(),
- ResourceBundleManager.getManager(resource.getProject()),
- key != null ? key : "",
- "",
- bundleId,
- "");
- if (dialog.open() != InputDialog.OK)
- return;
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- (new StringLiteralAuditor()).buildResource(resource, null);
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java
deleted file mode 100644
index b2d18efa..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java
+++ /dev/null
@@ -1,513 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.views.messagesview;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Scale;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.model.view.MessagesViewState;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-
-
-public class MessagesView extends ViewPart implements IResourceBundleChangedListener {
-
- /**
- * The ID of the view as specified by the extension.
- */
- public static final String ID = "org.eclipselabs.tapiji.tools.core.views.MessagesView";
-
- // View State
- private IMemento memento;
- 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());
-
- }
- 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;
- }
-
- 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) {}
- }
- 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();
- }
-
- protected void redrawTreeViewer () {
- parent.setRedraw(false);
- treeViewer.dispose();
- try {
- initMessagesTree(parent);
- makeActions();
- contributeToActionBars();
- hookContextMenu();
- } catch (Exception e) {
- Logger.logError(e);
- }
- parent.setRedraw(true);
- parent.layout(true);
- treeViewer.layout(true);
- refreshSearchbarState();
- }
-
- /*** 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");
- }
- langAction.setChecked(visibleLocales.contains(locale));
- visibleLocaleActions.add(langAction);
- }
- }
-
- 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();
- }
- }
- }
- };
-
- 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().isEmpty());
-
- 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) {
- 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().isEmpty()));
- 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);
- }
-
- @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);
- this.memento = 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();
- }
- } 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) {}
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
deleted file mode 100644
index b86f66c2..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.views.messagesview;
-
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
-
-
-public class ResourceBundleEntry extends ContributionItem implements
- ISelectionChangedListener {
-
- private PropertyKeySelectionTree parentView;
- private boolean legalSelection = false;
-
- // Menu-Items
- private MenuItem addItem;
- private MenuItem editItem;
- private MenuItem removeItem;
-
- public ResourceBundleEntry() {
- }
-
- public ResourceBundleEntry(PropertyKeySelectionTree 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 editing the currently selected entry
- editItem = new MenuItem(menu, SWT.NONE, index + 1);
- editItem.setText("Edit");
- editItem.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.editSelectedItem();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
-
- // MenuItem for deleting the currently selected entry
- removeItem = new MenuItem(menu, SWT.NONE, index + 2);
- removeItem.setText("Remove");
- removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
- .createImage());
- removeItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.deleteSelectedItems();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
- enableMenuItems();
- }
- }
-
- protected void enableMenuItems() {
- try {
- editItem.setEnabled(legalSelection);
- removeItem.setEnabled(legalSelection);
- } catch (Exception e) {
- // silent catch
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- legalSelection = !event.getSelection().isEmpty();
- // enableMenuItems ();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
deleted file mode 100644
index 9729bfc8..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
+++ /dev/null
@@ -1,143 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.MessagesBundleFactory;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-public class KeyTreeItemDropTarget extends DropTargetAdapter {
- private final TreeViewer target;
-
- public KeyTreeItemDropTarget (TreeViewer viewer) {
- super();
- this.target = viewer;
- }
-
- public void dragEnter (DropTargetEvent event) {
-// if (((DropTarget)event.getSource()).getControl() instanceof Tree)
-// event.detail = DND.DROP_MOVE;
- }
-
- private void addBundleEntries (final String keyPrefix, // new prefix
- final IKeyTreeNode children,
- final IMessagesBundleGroup bundleGroup) {
-
- try {
- String oldKey = children.getMessageKey();
- String key = children.getName();
- String newKey = keyPrefix + "." + key;
-
- IMessage[] messages = bundleGroup.getMessages(oldKey);
- for (IMessage message : messages) {
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(message.getLocale());
- IMessage m = MessagesBundleFactory.createMessage(newKey, message.getLocale());
- m.setText(message.getValue());
- m.setComment(message.getComment());
- messagesBundle.addMessage(m);
- }
-
- if (messages.length == 0 ) {
- bundleGroup.addMessages(newKey);
- }
-
- for (IKeyTreeNode childs : children.getChildren()) {
- addBundleEntries(keyPrefix+"."+key, childs, bundleGroup);
- }
-
- } catch (Exception e) { Logger.logError(e); }
-
- }
-
- private void remBundleEntries(IKeyTreeNode children, IMessagesBundleGroup group) {
- String key = children.getMessageKey();
-
- group.removeMessages(key);
-
- for (IKeyTreeNode childs : children.getChildren()) {
- remBundleEntries(childs, group);
- }
- }
-
- public void drop (final DropTargetEvent event) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- try {
-
- if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
- String newKeyPrefix = "";
- String newName = "";
-
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item).getData();
- newKeyPrefix = targetTreeNode.getMessageKey();
- newName = targetTreeNode.getName();
- }
-
- String message = (String)event.data;
- String oldKey = message.replaceAll("\"", "");
-
- String[] keyArr = (oldKey).split("\\.");
- String key = keyArr[keyArr.length-1];
-
- // old key is new key, only possible if copy operation, otherwise key gets deleted
- if (oldKey.equals(newKeyPrefix + "." + key) && event.detail == DND.DROP_MOVE)
- return;
-
- // prevent cycle loop if drop parent into child node
- if (newKeyPrefix.contains(oldKey) && event.detail == DND.DROP_MOVE)
- return;
-
- ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target.getContentProvider();
- IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target.getInput();
-
- IKeyTreeNode childrenTreeNode = keyTree.getChild(oldKey);
-
- IMessagesBundleGroup bundleGroup = contentProvider.getBundle();
-
- DirtyHack.setFireEnabled(false);
- DirtyHack.setEditorModificationEnabled(false); // editor won't get dirty
-
- // Adopt and add new bundle entries
- addBundleEntries(newKeyPrefix, childrenTreeNode, bundleGroup);
-
- if (event.detail == DND.DROP_MOVE) {
- remBundleEntries(childrenTreeNode, bundleGroup);
- }
-
- // Store changes
- RBManager manager = RBManager.getInstance(((MessagesBundleGroup) bundleGroup).getProjectName());
-
- manager.writeToFile(bundleGroup);
- manager.fireEditorChanged(); // refresh the View
-
- target.refresh();
- } else {
- event.detail = DND.DROP_NONE;
- }
-
- } catch (Exception e) { Logger.logError(e); }
- finally {
- DirtyHack.setFireEnabled(true);
- DirtyHack.setEditorModificationEnabled(true);
- }
- }
- });
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
deleted file mode 100644
index 5bb6d5cd..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-public class KeyTreeItemTransfer extends ByteArrayTransfer {
-
- private static final String KEY_TREE_ITEM = "keyTreeItem";
-
- private static final int TYPEID = registerType(KEY_TREE_ITEM);
-
- private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer();
-
- public static KeyTreeItemTransfer getInstance() {
- return transfer;
- }
-
- public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
- DND.error(DND.ERROR_INVALID_DATA);
- }
- IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream oOut = new ObjectOutputStream(out);
- for (int i = 0, length = terms.length; i < length; i++) {
- oOut.writeObject(terms[i]);
- }
- byte[] buffer = out.toByteArray();
- oOut.close();
-
- super.javaToNative(buffer, transferData);
- } catch (IOException e) {
- Logger.logError(e);
- }
- }
-
- public Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
-
- byte[] buffer;
- try {
- buffer = (byte[]) super.nativeToJava(transferData);
- } catch (Exception e) {
- Logger.logError(e);
- buffer = null;
- }
- if (buffer == null)
- return null;
-
- List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>();
- try {
- ByteArrayInputStream in = new ByteArrayInputStream(buffer);
- ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
- IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
- terms.add(newTerm);
- //}
- readIn.close();
- } catch (Exception ex) {
- Logger.logError(ex);
- return null;
- }
- return terms.toArray(new IKeyTreeNode[terms.size()]);
- }
-
- return null;
- }
-
- protected String[] getTypeNames() {
- return new String[] { KEY_TREE_ITEM };
- }
-
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
-
- boolean checkType(Object object) {
- if (object == null || !(object instanceof IKeyTreeNode[])
- || ((IKeyTreeNode[]) object).length == 0) {
- return false;
- }
- IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object;
- for (int i = 0; i < myTypes.length; i++) {
- if (myTypes[i] == null) {
- return false;
- }
- }
- return true;
- }
-
- protected boolean validate(Object object) {
- return checkType(object);
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
deleted file mode 100644
index dfbed204..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-public class MessagesDragSource implements DragSourceListener {
-
- private final TreeViewer source;
- private String bundleId;
-
- public MessagesDragSource (TreeViewer sourceView, String bundleId) {
- source = sourceView;
- this.bundleId = bundleId;
- }
-
- @Override
- public void dragFinished(DragSourceEvent event) {
-
- }
-
- @Override
- public void dragSetData(DragSourceEvent event) {
- IKeyTreeNode selectionObject = (IKeyTreeNode)
- ((IStructuredSelection)source.getSelection()).toList().get(0);
-
- String key = selectionObject.getMessageKey();
-
- // TODO Solve the problem that its not possible to retrieve the editor position of the drop event
-
-// event.data = "(new ResourceBundle(\"" + bundleId + "\")).getString(\"" + key + "\")";
- event.data = "\"" + key + "\"";
- }
-
- @Override
- public void dragStart(DragSourceEvent event) {
- event.doit = !source.getSelection().isEmpty();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
deleted file mode 100644
index 57a65ef5..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-public class MessagesDropTarget extends DropTargetAdapter {
- private final TreeViewer target;
- private final ResourceBundleManager manager;
- private String bundleName;
-
- public MessagesDropTarget (TreeViewer viewer, ResourceBundleManager manager, String bundleName) {
- super();
- target = viewer;
- this.manager = manager;
- this.bundleName = bundleName;
- }
-
- public void dragEnter (DropTargetEvent event) {
- }
-
- public void drop (DropTargetEvent event) {
- if (event.detail != DND.DROP_COPY)
- return;
-
- if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
- //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
- newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item).getData()).getMessageKey();
- }
-
- String message = (String)event.data;
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell(),
- manager,
- newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "",
- message,
- bundleName,
- ""
- );
- if (dialog.open() != InputDialog.OK)
- return;
- } else
- event.detail = DND.DROP_NONE;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
deleted file mode 100644
index d7b7d04a..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets;
-
-
-public class MVTextTransfer {
-
- private MVTextTransfer () {
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
deleted file mode 100644
index 2f94f3af..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
+++ /dev/null
@@ -1,682 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.KeyTreeFactory;
-import org.eclipse.babel.editor.api.MessagesBundleFactory;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.model.view.SortInfo;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
-import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource;
-import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.ExactMatcher;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-public class PropertyKeySelectionTree extends Composite implements IResourceBundleChangedListener {
-
- private final int KEY_COLUMN_WEIGHT = 1;
- private final int LOCALE_COLUMN_WEIGHT = 1;
-
- private ResourceBundleManager manager;
- private String resourceBundle;
- private List<Locale> visibleLocales = new ArrayList<Locale>();
- private boolean editable;
-
- 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;
-
- public PropertyKeySelectionTree(IViewSite viewSite, IWorkbenchPartSite site, Composite parent, int style,
- String projectName, String resources, List<Locale> locales) {
- super(parent, style);
- this.site = site;
- resourceBundle = resources;
-
- if (resourceBundle != null && resourceBundle.trim().length() > 0) {
- manager = ResourceBundleManager.getManager(projectName);
- 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(manager.getResourceBundle(resourceBundle), visibleLocales,
- manager, 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(manager.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();
-
- // update content provider
- contentProvider.setLocales(visibleLocales);
- contentProvider.setBundleGroup(manager.getResourceBundle(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>();
- sortInfo = new SortInfo();
- visibleLocales.clear();
- if (resourceBundle != null) {
- for (Locale l : manager.getProvidedLocales(resourceBundle)) {
- if (l == null) {
- locSorted.put("Default", null);
- } else {
- locSorted.put(l.getDisplayName(uiLocale), l);
- }
- }
- }
-
- for (String lString : locSorted.keySet()) {
- visibleLocales.add(locSorted.get(lString));
- }
- sortInfo.setVisibleLocales(visibleLocales);
- }
-
- protected void constructWidget() {
- basicLayout = new TreeColumnLayout();
- this.setLayout(basicLayout);
-
- treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
- Tree tree = treeViewer.getTree();
-
- if (resourceBundle != null) {
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // create tree-columns
- constructTreeColumns(tree);
- } else {
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
- }
-
- makeActions();
- hookDoubleClickAction();
-
- // register messages table as selection provider
- site.setSelectionProvider(treeViewer);
- }
-
- protected void constructTreeColumns(Tree tree) {
- tree.removeAll();
- //tree.getColumns().length;
-
- // construct key-column
- keyColumn = new TreeColumn(tree, SWT.NONE);
- keyColumn.setText("Key");
- keyColumn.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(keyColumn, new ColumnWeightData(KEY_COLUMN_WEIGHT));
-
- if (visibleLocales != null) {
- for (final Locale l : visibleLocales) {
- TreeColumn col = new TreeColumn(tree, SWT.NONE);
-
- // Add editing support to this table column
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
-
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- boolean writeToFile = true;
-
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- String activeKey = vkti.getMessageKey();
-
- if (activeKey != null) {
- IMessagesBundleGroup bundleGroup = manager.getResourceBundle(resourceBundle);
- IMessage entry = bundleGroup.getMessage(activeKey, l);
-
- if (entry == null || !value.equals(entry.getValue())) {
- String comment = null;
- if (entry != null) {
- comment = entry.getComment();
- }
-
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(l);
-
- DirtyHack.setFireEnabled(false);
-
- IMessage message = messagesBundle.getMessage(activeKey);
- if (message == null) {
- IMessage newMessage = MessagesBundleFactory.createMessage(activeKey, l);
- newMessage.setText(String.valueOf(value));
- newMessage.setComment(comment);
- messagesBundle.addMessage(newMessage);
-
- } else {
- message.setText(String.valueOf(value));
- message.setComment(comment);
- }
-
- RBManager.getInstance(manager.getProject()).writeToFile(messagesBundle);
-
- setTreeStructure();
-
- DirtyHack.setFireEnabled(true);
-
- }
- }
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, visibleLocales.indexOf(l) + 1);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer.getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
-
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(uiLocale);
-
- col.setText(displayName);
- col.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
- });
- basicLayout.setColumnData(col, new ColumnWeightData(LOCALE_COLUMN_WEIGHT));
- }
- }
- }
-
- protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sortInfo.setVisibleLocales(visibleLocales);
- sorter.setSortInfo(sortInfo);
- treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
- setTreeStructure();
- treeViewer.refresh();
- }
-
- @Override
- public boolean setFocus() {
- return treeViewer.getControl().setFocus();
- }
-
- /*** DRAG AND DROP ***/
- protected void hookDragAndDrop() {
- //KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource (treeViewer);
- KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
- MessagesDragSource source = new MessagesDragSource(treeViewer, this.resourceBundle);
- MessagesDropTarget target = new MessagesDropTarget(treeViewer, manager, 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();
- if (manager != null) {
- RBManager.getInstance(manager.getProject()).addMessagesEditorListener(editorListener);
- }
-
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
-
- public void keyPressed(KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
- }
-
- protected void unregisterListeners() {
- if (manager != null) {
- RBManager.getInstance(manager.getProject()).removeMessagesEditorListener(editorListener);
- }
- treeViewer.removeSelectionChangedListener(selectionChangedListener);
- }
-
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- selectionChangedListener = listener;
- }
-
- @Override
- public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
- if (event.getType() != ResourceBundleChangedEvent.MODIFIED
- || !event.getBundle().equals(this.getResourceBundle()))
- return;
-
- if (Display.getCurrent() != null) {
- refreshViewer(event, true);
- return;
- }
-
- Display.getDefault().asyncExec(new Runnable() {
-
- public void run() {
- refreshViewer(event, true);
- }
- });
- }
-
- private void refreshViewer(ResourceBundleChangedEvent event, boolean computeVisibleLocales) {
- //manager.loadResourceBundle(resourceBundle);
- if (computeVisibleLocales) {
- refreshContent(event);
- }
-
- // Display.getDefault().asyncExec(new Runnable() {
- // public void run() {
- treeViewer.refresh();
- // }
- // });
- }
-
- public StructuredViewer getViewer() {
- return this.treeViewer;
- }
-
- public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat : TreeType.Tree;
- labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
- // WTF?
- treeType = treeType.equals(TreeType.Tree) && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
- treeViewer.refresh();
- }
-
- public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- sortInfo.setVisibleLocales(visibleLocales);
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
- treeViewer.refresh();
- }
- }
-
- public String getSearchString() {
- return matcher.getPattern();
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public ResourceBundleManager getManager() {
- return this.manager;
- }
-
- public String getResourceBundle() {
- return resourceBundle;
- }
-
- public void editSelectedItem() {
- EditorUtils.openEditor(site.getPage(), manager.getRandomFile(resourceBundle),
- EditorUtils.RESOURCE_BUNDLE_EDITOR);
- }
-
- public void deleteSelectedItems() {
- List<String> keys = new ArrayList<String>();
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- addKeysToRemove((IKeyTreeNode)elem, keys);
- }
- }
- }
-
- try {
- manager.removeResourceBundleEntry(getResourceBundle(), keys);
- } catch (Exception ex) {
- Logger.logError(ex);
- }
- }
-
- private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
- keys.add(node.getMessageKey());
- for (IKeyTreeNode ktn : node.getChildren()) {
- addKeysToRemove(ktn, keys);
- }
- }
-
- public void addNewItem() {
- //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
-
- 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) {
- newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
- break;
- }
- }
- }
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(Display.getDefault()
- .getActiveShell(), manager, newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]"
- : "", "", getResourceBundle(), "");
- if (dialog.open() != InputDialog.OK)
- return;
- }
-
- public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- private class MessagesEditorListener implements IMessagesEditorListener {
- @Override
- public void onSave() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
-
- @Override
- public void onModify() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
-
- @Override
- public void onResourceChanged(IMessagesBundle bundle) {
- // TODO Auto-generated method stub
-
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
deleted file mode 100644
index 544d52bf..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
+++ /dev/null
@@ -1,233 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.editor.api.KeyTreeFactory;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-
-public class ResourceSelector extends Composite {
-
- public static final int DISPLAY_KEYS = 0;
- public static final int DISPLAY_TEXT = 1;
-
- private Locale displayLocale;
- private int displayMode;
- private String resourceBundle;
- private ResourceBundleManager manager;
- private boolean showTree;
-
- private TreeViewer viewer;
- private TreeColumnLayout basicLayout;
- private TreeColumn entries;
- private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>();
-
- // Viewer model
- private TreeType treeType = TreeType.Tree;
- private StyledCellLabelProvider labelProvider;
-
- public ResourceSelector(Composite parent,
- int style,
- ResourceBundleManager manager,
- String resourceBundle,
- int displayMode,
- Locale displayLocale,
- boolean showTree) {
- super(parent, style);
- this.manager = manager;
- this.resourceBundle = resourceBundle;
- this.displayMode = displayMode;
- this.displayLocale = displayLocale;
- this.showTree = showTree;
- this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
-
- initLayout (this);
- initViewer (this);
-
- updateViewer (true);
- }
-
- protected void updateContentProvider (IMessagesBundleGroup group) {
- // define input of treeviewer
- if (!showTree || displayMode == DISPLAY_TEXT) {
- treeType = TreeType.Flat;
- }
-
- IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle));
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setBundleGroup(manager.getResourceBundle(resourceBundle));
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
- if (viewer.getInput() == null) {
- viewer.setUseHashlookup(true);
- }
-
-// viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
- org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer.getExpandedTreePaths();
- viewer.setInput(model);
- viewer.refresh();
- viewer.setExpandedTreePaths(expandedTreePaths);
- }
-
- protected void updateViewer (boolean updateContent) {
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
-
- if (group == null)
- return;
-
- if (displayMode == DISPLAY_TEXT) {
- labelProvider = new ValueKeyTreeLabelProvider(group.getMessagesBundle(displayLocale));
- treeType = TreeType.Flat;
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
- } else {
- labelProvider = new ResKeyTreeLabelProvider(null);
- treeType = TreeType.Tree;
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
- }
-
- viewer.setLabelProvider(labelProvider);
- if (updateContent)
- updateContentProvider(group);
- }
-
- protected void initLayout (Composite parent) {
- basicLayout = new TreeColumnLayout();
- parent.setLayout(basicLayout);
- }
-
- protected void initViewer (Composite parent) {
- viewer = new TreeViewer (parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
- Tree table = viewer.getTree();
-
- // Init table-columns
- entries = new TreeColumn (table, SWT.NONE);
- basicLayout.setColumnData(entries, new ColumnWeightData(1));
-
- viewer.setContentProvider(new ResKeyTreeContentProvider());
- viewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection = event.getSelection();
- String selectionSummary = "";
- String selectedKey = "";
-
- if (selection instanceof IStructuredSelection) {
- Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection).iterator();
- if (itSel.hasNext()) {
- IKeyTreeNode selItem = itSel.next();
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
- selectedKey = selItem.getMessageKey();
-
- if (group == null)
- return;
- Iterator<Locale> itLocales = manager.getProvidedLocales(resourceBundle).iterator();
- while (itLocales.hasNext()) {
- Locale l = itLocales.next();
- try {
- selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayLanguage()) + ":\n";
- selectionSummary += "\t" + group.getMessagesBundle(l).getMessage(selItem.getMessageKey()).getValue() + "\n";
- } catch (Exception e) {}
- }
- }
- }
-
- // construct ResourceSelectionEvent
- ResourceSelectionEvent e = new ResourceSelectionEvent(selectedKey, selectionSummary);
- fireSelectionChanged(e);
- }
- });
-
- // we need this to keep the tree expanded
- viewer.setComparer(new IElementComparer() {
-
- @Override
- public int hashCode(Object element) {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((toString() == null) ? 0 : toString().hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object a, Object b) {
- if (a == b) {
- return true;
- }
- if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
- IKeyTreeNode nodeA = (IKeyTreeNode) a;
- IKeyTreeNode nodeB = (IKeyTreeNode) b;
- return nodeA.equals(nodeB);
- }
- return false;
- }
- });
- }
-
- public Locale getDisplayLocale() {
- return displayLocale;
- }
-
- public void setDisplayLocale(Locale displayLocale) {
- this.displayLocale = displayLocale;
- updateViewer(false);
- }
-
- public int getDisplayMode() {
- return displayMode;
- }
-
- public void setDisplayMode(int displayMode) {
- this.displayMode = displayMode;
- updateViewer(true);
- }
-
- public void setResourceBundle(String resourceBundle) {
- this.resourceBundle = resourceBundle;
- updateViewer(true);
- }
-
- public String getResourceBundle() {
- return resourceBundle;
- }
-
- public void addSelectionChangedListener (IResourceSelectionListener l) {
- listeners.add(l);
- }
-
- public void removeSelectionChangedListener (IResourceSelectionListener l) {
- listeners.remove(l);
- }
-
- private void fireSelectionChanged (ResourceSelectionEvent event) {
- Iterator<IResourceSelectionListener> itResList = listeners.iterator();
- while (itResList.hasNext()) {
- itResList.next().selectionChanged(event);
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
deleted file mode 100644
index 349c385c..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.event;
-
-public class ResourceSelectionEvent {
-
- private String selectionSummary;
- private String selectedKey;
-
- public ResourceSelectionEvent (String selectedKey, String selectionSummary) {
- this.setSelectionSummary(selectionSummary);
- this.setSelectedKey(selectedKey);
- }
-
- public void setSelectedKey (String key) {
- selectedKey = key;
- }
-
- public void setSelectionSummary(String selectionSummary) {
- this.selectionSummary = selectionSummary;
- }
-
- public String getSelectionSummary() {
- return selectionSummary;
- }
-
- public String getSelectedKey() {
- return selectedKey;
- }
-
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
deleted file mode 100644
index 6d83fc3c..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-public class ExactMatcher extends ViewerFilter {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public String getPattern () {
- return pattern;
- }
-
- public void setPattern (String p) {
- boolean filtering = matcher != null;
- if (p != null && p.trim().length() > 0) {
- pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
- if (!filtering)
- viewer.addFilter(this);
- else
- viewer.refresh();
- } else {
- pattern = "";
- matcher = null;
- if (filtering) {
- viewer.removeFilter(this);
- }
- }
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = matcher.match(vEle.getMessageKey());
-
- if (selected) {
- int start = -1;
- while ((start = vEle.getMessageKey().toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- filterInfo.addKeyOccurrence(start, pattern.length());
- }
- filterInfo.setFoundInKey(selected);
- filterInfo.setFoundInKey(true);
- } else
- filterInfo.setFoundInKey(false);
-
- // Iterate translations
- for (Locale l : vEle.getLocales()) {
- String value = vEle.getValue(l);
- if (matcher.match(value)) {
- filterInfo.addFoundInLocale(l);
- filterInfo.addSimilarity(l, 1d);
- int start = -1;
- while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- filterInfo.addFoundInLocaleRange(l, start, pattern.length());
- }
- selected = true;
- }
- }
-
- vEle.setInfo(filterInfo);
- return selected;
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
deleted file mode 100644
index a21e5c17..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.jface.text.Region;
-
-public class FilterInfo {
-
- private boolean foundInKey;
- private List<Locale> foundInLocales = new ArrayList<Locale> ();
- private List<Region> keyOccurrences = new ArrayList<Region> ();
- private Double keySimilarity;
- private Map<Locale, List<Region>> occurrences = new HashMap<Locale, List<Region>>();
- private Map<Locale, Double> localeSimilarity = new HashMap<Locale, Double>();
-
- public FilterInfo() {
-
- }
-
- public void setKeySimilarity (Double similarity) {
- keySimilarity = similarity;
- }
-
- public Double getKeySimilarity () {
- return keySimilarity;
- }
-
- public void addSimilarity (Locale l, Double similarity) {
- localeSimilarity.put (l, similarity);
- }
-
- public Double getSimilarityLevel (Locale l) {
- return localeSimilarity.get(l);
- }
-
- public void setFoundInKey(boolean foundInKey) {
- this.foundInKey = foundInKey;
- }
-
- public boolean isFoundInKey() {
- return foundInKey;
- }
-
- public void addFoundInLocale (Locale loc) {
- foundInLocales.add(loc);
- }
-
- public void removeFoundInLocale (Locale loc) {
- foundInLocales.remove(loc);
- }
-
- public void clearFoundInLocale () {
- foundInLocales.clear();
- }
-
- public boolean hasFoundInLocale (Locale l) {
- return foundInLocales.contains(l);
- }
-
- public List<Region> getFoundInLocaleRanges (Locale locale) {
- List<Region> reg = occurrences.get(locale);
- return (reg == null ? new ArrayList<Region>() : reg);
- }
-
- public void addFoundInLocaleRange (Locale locale, int start, int length) {
- List<Region> regions = occurrences.get(locale);
- if (regions == null)
- regions = new ArrayList<Region>();
- regions.add(new Region(start, length));
- occurrences.put(locale, regions);
- }
-
- public List<Region> getKeyOccurrences () {
- return keyOccurrences;
- }
-
- public void addKeyOccurrence (int start, int length) {
- keyOccurrences.add(new Region (start, length));
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
deleted file mode 100644
index 227a2ba0..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.Locale;
-
-import org.eclipse.babel.editor.api.AnalyzerFactory;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-
-public class FuzzyMatcher extends ExactMatcher {
-
- protected ILevenshteinDistanceAnalyzer lvda;
- protected float minimumSimilarity = 0.75f;
-
- public FuzzyMatcher(StructuredViewer viewer) {
- super(viewer);
- lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();;
- }
-
- public double getMinimumSimilarity () {
- return minimumSimilarity;
- }
-
- public void setMinimumSimilarity (float similarity) {
- this.minimumSimilarity = similarity;
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- boolean exactMatch = super.select(viewer, parentElement, element);
- boolean match = exactMatch;
-
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
-
- for (Locale l : vkti.getLocales()) {
- String value = vkti.getValue(l);
- if (filterInfo.hasFoundInLocale(l))
- continue;
- double dist = lvda.analyse(value, getPattern());
- if (dist >= minimumSimilarity) {
- filterInfo.addFoundInLocale(l);
- filterInfo.addSimilarity(l, dist);
- match = true;
- filterInfo.addFoundInLocaleRange(l, 0, value.length());
- }
- }
-
- vkti.setInfo(filterInfo);
- return match;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
deleted file mode 100644
index d48ea0e9..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
+++ /dev/null
@@ -1,441 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.Vector;
-
-/**
- * A string pattern matcher, suppporting "*" and "?" wildcards.
- */
-public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
- throw new IllegalArgumentException();
- }
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
- if (end < 0 || start >= end) {
- return null;
- }
- if (fLength == 0) {
- return new Position(start, start);
- }
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
- return null;
- }
- return new Position(x, x + fLength);
- }
-
- int segCount = fSegments.length;
- if (segCount == 0) {
- return new Position(start, end);
- }
-
- int curPos = start;
- int matchStart = -1;
- int i;
- for (i = 0; i < segCount && curPos < end; ++i) {
- String current = fSegments[i];
- int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0) {
- return null;
- }
- if (i == 0) {
- matchStart = nextMatch;
- }
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
- return null;
- }
- return new Position(matchStart, curPos);
- }
-
- /**
- * match the given <code>text</code> with the pattern
- * @return true if matched otherwise false
- * @param text a String object
- */
- public boolean match(String text) {
- if(text == null) {
- return false;
- }
- return match(text, 0, text.length());
- }
-
- /**
- * Given the starting (inclusive) and the ending (exclusive) positions in the
- * <code>text</code>, determine if the given substring matches with aPattern
- * @return true if the specified portion of the text matches the pattern
- * @param text a String object that contains the substring to match
- * @param start marks the starting position (inclusive) of the substring
- * @param end marks the ending index (exclusive) of the substring
- */
- public boolean match(String text, int start, int end) {
- if (null == text) {
- throw new IllegalArgumentException();
- }
-
- if (start > end) {
- return false;
- }
-
- if (fIgnoreWildCards) {
- return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
- }
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
- return true;
- }
- if (start == end) {
- return fLength == 0;
- }
- if (fLength == 0) {
- return start == end;
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
-
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
- return false;
- }
- int i = 0;
- String current = fSegments[i];
- int segLength = current.length();
-
- /* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos = tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar)
- && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current = fSegments[i];
- int currentMatch;
- int k = current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch = textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- } else {
- currentMatch = regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- }
- tCurPos = currentMatch + current.length();
- i++;
- }
-
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen = current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount;
- }
-
- /**
- * This method parses the given pattern into segments seperated by wildcard '*' characters.
- * Since wildcards are not being used in this case, the pattern consists of a single segment.
- */
- private void parseNoWildCards() {
- fSegments = new String[1];
- fSegments[0] = fPattern;
- fBound = fLength;
- }
-
- /**
- * Parses the given pattern into segments seperated by wildcard '*' characters.
- * @param p, a String object that is a simple regular expression with '*' and/or '?'
- */
- private void parseWildCards() {
- if (fPattern.startsWith("*")) { //$NON-NLS-1$
- fHasLeadingStar = true;
- }
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * @param text a simple regular expression that may only contain '?'(s)
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a simple regular expression that may contains '?'
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int regExpPosIn(String text, int start, int end, String p) {
- int plen = p.length();
-
- int max = end - plen;
- for (int i = start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- *
- * @return boolean
- * @param text a String to match
- * @param start int that indicates the starting index of match, inclusive
- * @param end</code> int that indicates the ending index of match, exclusive
- * @param p String, String, a simple regular expression that may contain '?'
- * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
- */
- protected boolean regExpRegionMatches(String text, int tStart, String p,
- int pStart, int plen) {
- while (plen-- > 0) {
- char tchar = text.charAt(tStart++);
- char pchar = p.charAt(pStart++);
-
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar) {
- continue;
- }
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character
- .toUpperCase(pchar)) {
- continue;
- }
- // comparing after converting to upper case doesn't handle all cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character
- .toLowerCase(pchar)) {
- continue;
- }
- }
- return false;
- }
- return true;
- }
-
- /**
- * @param text the string to match
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a pattern string that has no wildcard
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int textPosIn(String text, int start, int end, String p) {
-
- int plen = p.length();
- int max = end - plen;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(p, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
- return i;
- }
- }
-
- return -1;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
deleted file mode 100644
index 7cb6f96d..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.listener;
-
-import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-
-public interface IResourceSelectionListener {
-
- public void selectionChanged (ResourceSelectionEvent e);
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
deleted file mode 100644
index 62d1aa3b..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
+++ /dev/null
@@ -1,166 +0,0 @@
- /*
-+ * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
- *
- * This file is part of Essiembre ResourceBundle Editor.
- *
- * Essiembre ResourceBundle Editor is free software; you can redistribute it
- * and/or modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * Essiembre ResourceBundle Editor is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Essiembre ResourceBundle Editor; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307 USA
- */
-package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
-
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.util.FontUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-/**
- * Label provider for key tree viewer.
- * @author Pascal Essiembre ([email protected])
- * @version $Author: nl_carnage $ $Revision: 1.11 $ $Date: 2007/09/11 16:11:09 $
- */
-public class KeyTreeLabelProvider
- extends StyledCellLabelProvider /*implements IFontProvider, IColorProvider*/ {
-
- private static final int KEY_DEFAULT = 1 << 1;
- private static final int KEY_COMMENTED = 1 << 2;
- private static final int KEY_NOT = 1 << 3;
- private static final int WARNING = 1 << 4;
- private static final int WARNING_GREY = 1 << 5;
-
- /** Registry instead of UIUtils one for image not keyed by file name. */
- private static ImageRegistry imageRegistry = new ImageRegistry();
-
- private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY);
-
- /** Group font. */
- private Font groupFontKey = FontUtils.createFont(SWT.BOLD);
- private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
-
-
- /**
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- IKeyTreeNode treeItem = ((IKeyTreeNode) element);
-
- int iconFlags = 0;
-
- // Figure out background icon
- if (treeItem.getMessagesBundleGroup() != null &&
- treeItem.getMessagesBundleGroup().isKey(treeItem.getMessageKey())) {
- iconFlags += KEY_DEFAULT;
- } else {
- iconFlags += KEY_NOT;
- }
-
- return generateImage(iconFlags);
- }
-
- /**
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- return ((IKeyTreeNode) element).getName();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
- */
- public void dispose() {
- groupFontKey.dispose();
- groupFontNoKey.dispose();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- IKeyTreeNode item = (IKeyTreeNode) element;
- if (item.getChildren().length > 0 && item.getMessagesBundleGroup() != null) {
- if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) {
- return groupFontKey;
- }
- return groupFontNoKey;
- }
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- IKeyTreeNode treeItem = (IKeyTreeNode) element;
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- // TODO Auto-generated method stub
- return null;
- }
-
- /**
- * Generates an image based on icon flags.
- * @param iconFlags
- * @return generated image
- */
- private Image generateImage(int iconFlags) {
- Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
- if (image == null) {
- // Figure background image
- if ((iconFlags & KEY_COMMENTED) != 0) {
- image = getRegistryImage("keyCommented.gif"); //$NON-NLS-1$
- } else if ((iconFlags & KEY_NOT) != 0) {
- image = getRegistryImage("key.gif"); //$NON-NLS-1$
- } else {
- image = getRegistryImage("key.gif"); //$NON-NLS-1$
- }
-
- }
- return image;
- }
-
-
- private Image getRegistryImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-
- @Override
- public void update(ViewerCell cell) {
- cell.setBackground(getBackground(cell.getElement()));
- cell.setFont(getFont(cell.getElement()));
- cell.setForeground(getForeground(cell.getElement()));
-
- cell.setText(getText(cell.getElement()));
- cell.setImage(getImage(cell.getElement()));
- super.update(cell);
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
deleted file mode 100644
index b718f1c7..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
-
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.swt.graphics.Image;
-
-public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements ITableLabelProvider {
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- return super.getText(element);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
deleted file mode 100644
index aff4bb5b..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
+++ /dev/null
@@ -1,251 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.KeyTreeFactory;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-
-
-public class ResKeyTreeContentProvider implements ITreeContentProvider {
-
- private IAbstractKeyTreeModel keyTreeModel;
- private Viewer viewer;
-
- private TreeType treeType = TreeType.Tree;
-
- /** Represents empty objects. */
- private static Object[] EMPTY_ARRAY = new Object[0];
- /** Viewer this provided act upon. */
- protected TreeViewer treeViewer;
-
- private IMessagesBundleGroup bundle;
- private List<Locale> locales;
- private ResourceBundleManager manager;
- private String bundleId;
-
-
- public ResKeyTreeContentProvider (IMessagesBundleGroup iBundleGroup, List<Locale> locales,
- ResourceBundleManager manager, String bundleId, TreeType treeType) {
- this.bundle = iBundleGroup;
- this.locales = locales;
- this.manager = manager;
- this.bundleId = bundleId;
- this.treeType = treeType;
- }
-
- public void setBundleGroup (IMessagesBundleGroup iBundleGroup) {
- this.bundle = iBundleGroup;
- }
-
- public ResKeyTreeContentProvider() {
- locales = new ArrayList<Locale>();
- }
-
- public void setLocales (List<Locale> locales) {
- this.locales = locales;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- // brauche sie als VKTI
-// if(parentElement instanceof IAbstractKeyTreeModel) {
-// IAbstractKeyTreeModel model = (IAbstractKeyTreeModel) parentElement;
-// return convertKTItoVKTI(model.getRootNodes());
-// } else if (parentElement instanceof IValuedKeyTreeNode) { // convert because we hold the children as IKeyTreeNodes
-// return convertKTItoVKTI(((IValuedKeyTreeNode) parentElement).getChildren());
-// }
- //new code
- 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];
- }
- //new code
-// return EMPTY_ARRAY;
- }
-
- protected Object[] convertKTItoVKTI (Object[] children) {
- Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>();
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(bundle.getProjectName()).getMessagesBundleGroup(bundle.getResourceBundleId());
-
- for (Object o : children) {
- if (o instanceof IValuedKeyTreeNode)
- items.add((IValuedKeyTreeNode)o);
- else {
- IKeyTreeNode kti = (IKeyTreeNode) o;
- IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(kti.getParent(), kti.getName(), kti.getMessageKey(), messagesBundleGroup);
-
- for (IKeyTreeNode k : kti.getChildren()) {
- vkti.addChild(k);
- }
-
- // init translations
- for (Locale l : locales) {
- try {
- IMessage message = messagesBundleGroup.getMessagesBundle(l).getMessage(kti.getMessageKey());
- if (message != null) {
- vkti.addValue(l, message.getValue());
- }
- } catch (Exception e) {}
- }
- items.add(vkti);
- }
- }
-
- return items.toArray();
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
-// return getChildren(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) {
-// Object[] parent = new Object[1];
-//
-// if(element instanceof IKeyTreeNode) {
-// return ((IKeyTreeNode) element).getParent();
-// }
-//
-// if (parent[0] == null)
-// return null;
-//
-// Object[] result = convertKTItoVKTI(parent);
-// if (result.length > 0)
-// return result[0];
-// else
-// return null;
-
- // new code
- IKeyTreeNode node = (IKeyTreeNode) element;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getParent(node);
- case Flat:
- return keyTreeModel;
- default:
- // Should not happen
- return null;
- }
- // new code
- }
-
- /**
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
-// return countChildren(element) > 0;
-
- // new code
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0;
- case Flat:
- return false;
- default:
- // Should not happen
- return false;
- }
- // new code
- }
-
- 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(manager.getProject()).getMessagesBundleGroup(bundle.getResourceBundleId());
- }
-
- public ResourceBundleManager getManager() {
- return manager;
- }
-
- 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.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
deleted file mode 100644
index 6efb6817..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
+++ /dev/null
@@ -1,153 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FilterInfo;
-import org.eclipselabs.tapiji.tools.core.util.FontUtils;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-
-public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider {
-
- private List<Locale> locales;
- private boolean searchEnabled = false;
-
- /*** COLORS ***/
- private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
- private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
- private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
-
- /*** FONTS ***/
- private Font bold = FontUtils.createFont(SWT.BOLD);
- private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
-
- public ResKeyTreeLabelProvider (List<Locale> locales) {
- this.locales = locales;
- }
-
- //@Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 0) {
- IKeyTreeNode kti = (IKeyTreeNode) element;
- IMessage[] be = kti.getMessagesBundleGroup().getMessages(kti.getMessageKey());
- boolean incomplete = false;
-
- if (be.length != kti.getMessagesBundleGroup().getMessagesBundleCount())
- incomplete = true;
- else {
- for (IMessage b : be) {
- if (b.getValue() == null || b.getValue().trim().length() == 0) {
- incomplete = true;
- break;
- }
- }
- }
-
- if (incomplete)
- return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
- else
- return ImageUtils.getImage(ImageUtils.ICON_RESOURCE);
- }
- return null;
- }
-
- //@Override
- public String getColumnText(Object element, int columnIndex) {
- if (columnIndex == 0)
- return super.getText(element);
-
- if (columnIndex <= locales.size()) {
- IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
- String entry = item.getValue(locales.get(columnIndex-1));
- if (entry != null) {
- return entry;
- }
- }
- return "";
- }
-
- public void setSearchEnabled (boolean enabled) {
- this.searchEnabled = enabled;
- }
-
- public boolean isSearchEnabled () {
- return this.searchEnabled;
- }
-
- public void setLocales(List<Locale> visibleLocales) {
- locales = visibleLocales;
- }
-
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
- boolean matching = false;
-
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
-
- if (vkti.getInfo() == null)
- return false;
-
- FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
-
- if (columnIndex == 0) {
- matching = filterInfo.isFoundInKey();
- } else {
- matching = filterInfo.hasFoundInLocale(locales.get(columnIndex-1));
- }
- }
-
- return matching;
- }
-
- protected boolean isSearchEnabled (Object element) {
- return (element instanceof IValuedKeyTreeNode && searchEnabled );
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
-
- if (isSearchEnabled(element)) {
- if (isMatchingToPattern(element, columnIndex) ) {
- List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode)element).getInfo();
-
- if (columnIndex > 0) {
- for (Region reg : filterInfo.getFoundInLocaleRanges(locales.get(columnIndex-1))) {
- styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
- }
- } else {
- // check if the pattern has been found within the key section
- if (filterInfo.isFoundInKey()) {
- for (Region reg : filterInfo.getKeyOccurrences()) {
- StyleRange sr = new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD);
- styleRanges.add(sr);
- }
- }
- }
- cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
- } else {
- cell.setForeground(gray);
- }
- } else if (columnIndex == 0)
- super.update(cell);
-
- cell.setImage(this.getColumnImage(element, columnIndex));
- cell.setText(this.getColumnText(element, columnIndex));
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
deleted file mode 100644
index 1241bab4..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
-
-import org.eclipse.jface.viewers.ITableColorProvider;
-import org.eclipse.jface.viewers.ITableFontProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
- ITableColorProvider, ITableFontProvider {
-
- private IMessagesBundle locale;
-
- public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) {
- this.locale = iBundle;
- }
-
- //@Override
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- //@Override
- public String getColumnText(Object element, int columnIndex) {
- try {
- IKeyTreeNode item = (IKeyTreeNode) element;
- IMessage entry = locale.getMessage(item.getMessageKey());
- if (entry != null) {
- String value = entry.getValue();
- if (value.length() > 40)
- value = value.substring(0, 39) + "...";
- }
- } catch (Exception e) {
- }
- return "";
- }
-
- @Override
- public Color getBackground(Object element, int columnIndex) {
- return null;//return new Color(Display.getDefault(), 255, 0, 0);
- }
-
- @Override
- public Color getForeground(Object element, int columnIndex) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Font getFont(Object element, int columnIndex) {
- return null; //UIUtils.createFont(SWT.BOLD);
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
- cell.setImage(this.getColumnImage(element, columnIndex));
- cell.setText(this.getColumnText(element, columnIndex));
-
- super.update(cell);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
deleted file mode 100644
index 0650b1d7..00000000
--- a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.ui.widgets.sorter;
-
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipselabs.tapiji.tools.core.model.view.SortInfo;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-public class ValuedKeyTreeItemSorter extends ViewerSorter {
-
- private StructuredViewer viewer;
- private SortInfo sortInfo;
-
- public ValuedKeyTreeItemSorter (StructuredViewer viewer,
- SortInfo sortInfo) {
- this.viewer = viewer;
- this.sortInfo = sortInfo;
- }
-
- public StructuredViewer getViewer() {
- return viewer;
- }
-
- public void setViewer(StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public SortInfo getSortInfo() {
- return sortInfo;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- this.sortInfo = sortInfo;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- try {
- if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode))
- return super.compare(viewer, e1, e2);
- IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
- IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
-
- int result = 0;
-
- if (sortInfo == null)
- return 0;
-
- if (sortInfo.getColIdx() == 0)
- result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
- else {
- Locale loc = sortInfo.getVisibleLocales().get(sortInfo.getColIdx()-1);
- result = (comp1.getValue(loc) == null ? "" : comp1.getValue(loc))
- .compareTo((comp2.getValue(loc) == null ? "" : comp2.getValue(loc)));
- }
-
- return result * (sortInfo.isDESC() ? -1 : 1);
- } catch (Exception e) {
- return 0;
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/.project b/org.eclipselabs.tapiji.tools.core/.project
deleted file mode 100644
index cbf1d6df..00000000
--- a/org.eclipselabs.tapiji.tools.core/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.tools.core</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF
deleted file mode 100644
index d7708e9b..00000000
--- a/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,37 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: TapiJI Tools
-Bundle-SymbolicName: org.eclipselabs.tapiji.tools.core;singleton:=true
-Bundle-Version: 0.0.2.qualifier
-Bundle-Activator: org.eclipselabs.tapiji.tools.core.Activator
-Bundle-Vendor: Vienna University of Technology
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.jdt.ui;bundle-version="3.5.2",
- org.eclipse.ui.ide,
- org.eclipse.jdt.core;bundle-version="3.5.2",
- org.eclipse.core.resources,
- org.eclipse.jface.text;bundle-version="3.5.2",
- org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.2",
- org.eclipse.babel.editor;bundle-version="0.8.0";visibility:=reexport
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Bundle-ActivationPolicy: lazy
-Import-Package: org.eclipse.core.filebuffers,
- org.eclipse.core.resources,
- org.eclipse.jdt.core,
- org.eclipse.jdt.core.dom,
- org.eclipse.jface.text,
- org.eclipse.jface.text.contentassist,
- org.eclipse.ui.ide,
- org.eclipse.ui.texteditor
-Export-Package: org.eclipselabs.tapiji.tools.core,
- org.eclipselabs.tapiji.tools.core.builder,
- org.eclipselabs.tapiji.tools.core.builder.analyzer,
- org.eclipselabs.tapiji.tools.core.builder.quickfix,
- org.eclipselabs.tapiji.tools.core.extensions,
- org.eclipselabs.tapiji.tools.core.model,
- org.eclipselabs.tapiji.tools.core.model.exception,
- org.eclipselabs.tapiji.tools.core.model.manager,
- org.eclipselabs.tapiji.tools.core.model.preferences,
- org.eclipselabs.tapiji.tools.core.model.view,
- org.eclipselabs.tapiji.tools.core.util
diff --git a/org.eclipselabs.tapiji.tools.core/plugin.xml b/org.eclipselabs.tapiji.tools.core/plugin.xml
deleted file mode 100644
index 0e682620..00000000
--- a/org.eclipselabs.tapiji.tools.core/plugin.xml
+++ /dev/null
@@ -1,121 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension-point id="org.eclipselabs.tapiji.tools.core.builderExtension" name="BuilderExtension" schema="schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd"/>
-
-
- <extension
- id="I18NBuilder"
- point="org.eclipse.core.resources.builders">
- <builder hasNature="true">
- <run class="org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor" />
- </builder>
- </extension>
-
- <extension
- id="org.eclipselabs.tapiji.tools.core.nature"
- name="Internationalization Nature"
- point="org.eclipse.core.resources.natures">
- <runtime>
- <run class="org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature" />
- </runtime>
- <builder id="org.eclipselabs.tapiji.tools.core.I18NBuilder" />
-<!-- <requires-nature id="org.eclipse.jdt.core.javanature"/> -->
- </extension>
-
- <extension
- id="StringLiteralAuditMarker"
- name="String Literal Audit Marker"
- point="org.eclipse.core.resources.markers">
- <super
- type="org.eclipse.core.resources.problemmarker">
- </super>
- <super
- type="org.eclipse.core.resources.textmarker">
- </super>
- <persistent
- value="true">
- </persistent>
- <attribute
- name="stringLiteral">
- </attribute>
- <attribute
- name="violation">
- </attribute>
- <attribute
- name="context">
- </attribute>
- <attribute
- name="cause">
- </attribute>
- <attribute
- name="key">
- </attribute>
- <attribute
- name="location">
- </attribute>
- <attribute
- name="bundleName">
- </attribute>
- <attribute
- name="bundleStart">
- </attribute>
- <attribute
- name="bundleEnd">
- </attribute>
- </extension>
- <extension
- id="ResourceBundleAuditMarker"
- name="Resource-Bundle Audit Marker"
- point="org.eclipse.core.resources.markers">
- <super
- type="org.eclipse.core.resources.problemmarker">
- </super>
- <super
- type="org.eclipse.core.resources.textmarker">
- </super>
- <persistent
- value="true">
- </persistent>
- <attribute
- name="stringLiteral">
- </attribute>
- <attribute
- name="violation">
- </attribute>
- <attribute
- name="context">
- </attribute>
- <attribute
- name="cause">
- </attribute>
- <attribute
- name="key">
- </attribute>
- <attribute
- name="location">
- </attribute>
- <attribute
- name="language">
- </attribute>
- <attribute
- name="bundleLine">
- </attribute>
- <attribute
- name="problemPartner">
- </attribute>
- </extension>
- <extension
- point="org.eclipse.core.runtime.preferences">
- <initializer
- class="org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferenceInitializer">
- </initializer>
- </extension>
- <extension
- point="org.eclipse.babel.core.babelConfiguration">
- <IConfiguration
- class="org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences">
- </IConfiguration>
- </extension>
-
-</plugin>
diff --git a/org.eclipselabs.tapiji.tools.core/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd b/org.eclipselabs.tapiji.tools.core/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd
deleted file mode 100644
index d348d874..00000000
--- a/org.eclipselabs.tapiji.tools.core/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="org.eclipselabs.tapiji.tools.core" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appinfo>
- <meta.schema plugin="org.eclipselabs.tapiji.tools.core" id="builderExtension" name="BuilderExtension"/>
- </appinfo>
- <documentation>
- The TapiJI core plug-in does not contribute any coding assistances into the source code editor. Analogically, it does not provide logic for finding Internationalization problems within sources resources. Moreover, it offers a platform for contributing source code analysis and problem resolution proposals for Internationalization problems in a uniform way. For this purpose, the TapiJI core plug-in provides the extension point org.eclipselabs.tapiji.tools.core.builderExtension that allows other plug-ins to register Internationalization related coding assistances. This concept realizes a loose coupling between basic Internationalization functionality and coding dialect specific help. Once the TapiJI core plug-in is installed, it allows an arbitrary number of extensions to provide their own assistances based on the TapiJI Tools suite.
- </documentation>
- </annotation>
-
- <element name="extension">
- <annotation>
- <appinfo>
- <meta.element />
- </appinfo>
- </annotation>
- <complexType>
- <choice minOccurs="0" maxOccurs="unbounded">
- <element ref="i18nAuditor"/>
- </choice>
- <attribute name="point" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="id" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="name" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- <appinfo>
- <meta.attribute translatable="true"/>
- </appinfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <element name="i18nAuditor">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- <appinfo>
- <meta.attribute kind="java" basedOn="org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor:"/>
- </appinfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <annotation>
- <appinfo>
- <meta.section type="since"/>
- </appinfo>
- <documentation>
- 0.0.1
- </documentation>
- </annotation>
-
- <annotation>
- <appinfo>
- <meta.section type="examples"/>
- </appinfo>
- <documentation>
- The following example demonstrates registration of Java Programming dialect specific Internationalization assistance.
-
-<pre>
-<extension point="org.eclipselabs.tapiji.tools.core.builderExtension">
- <i18nResourceAuditor
- class="auditor.JavaResourceAuditor">
- </i18nResourceAuditor>
-</extension>
-</pre>
- </documentation>
- </annotation>
-
- <annotation>
- <appinfo>
- <meta.section type="apiinfo"/>
- </appinfo>
- <documentation>
- Extending plug-ins need to extend the abstract class <strong>org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor</strong>.
-
-<pre>
-package org.eclipselabs.tapiji.tools.core.extensions;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-/**
- * Auditor class for finding I18N problems within source code resources. The
- * objects audit method is called for a particular resource. Found errors are
- * stored within the object's internal data structure and can be queried with
- * the help of problem categorized getter methods.
- */
-public abstract class I18nResourceAuditor {
- /**
- * Audits a project resource for I18N problems. This method is triggered
- * during the project's build process.
- *
- * @param resource
- * The project resource
- */
- public abstract void audit(IResource resource);
-
- /**
- * Returns a list of supported file endings.
- *
- * @return The supported file endings
- */
- public abstract String[] getFileEndings();
-
- /**
- * Returns the list of found need-to-translate string literals. Each list
- * entry describes the textual position on which this type of error has been
- * detected.
- *
- * @return The list of need-to-translate string literal positions
- */
- public abstract List<ILocation> getConstantStringLiterals();
-
- /**
- * Returns the list of broken Resource-Bundle references. Each list entry
- * describes the textual position on which this type of error has been
- * detected.
- *
- * @return The list of positions of broken Resource-Bundle references
- */
- public abstract List<ILocation> getBrokenResourceReferences();
-
- /**
- * Returns the list of broken references to Resource-Bundle entries. Each
- * list entry describes the textual position on which this type of error has
- * been detected
- *
- * @return The list of positions of broken references to locale-sensitive
- * resources
- */
- public abstract List<ILocation> getBrokenBundleReferences();
-
- /**
- * Returns a characterizing identifier of the implemented auditing
- * functionality. The specified identifier is used for discriminating
- * registered builder extensions.
- *
- * @return The String id of the implemented auditing functionality
- */
- public abstract String getContextId();
-
- /**
- * Returns a list of quick fixes of a reported Internationalization problem.
- *
- * @param marker
- * The warning marker of the Internationalization problem
- * @param cause
- * The problem type
- * @return The list of marker resolution proposals
- */
- public abstract List<IMarkerResolution> getMarkerResolutions(
- IMarker marker);
-
- /**
- * Checks if the provided resource auditor is responsible for a particular
- * resource.
- *
- * @param resource
- * The resource reference
- * @return True if the resource auditor is responsible for the referenced
- * resource
- */
- public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
- }
-}
-
-</pre>
- </documentation>
- </annotation>
-
- <annotation>
- <appinfo>
- <meta.section type="implementation"/>
- </appinfo>
- <documentation>
- <ul>
- <li>Java Internationalization help: <span style="font-family:monospace">org.eclipselabs.tapiji.tools.java</span></li>
- <li>JSF Internaization help: <span style="font-family:monospace">org.eclipselabs.tapiji.tools.jsf</span></li>
-</ul>
- </documentation>
- </annotation>
-
- <annotation>
- <appinfo>
- <meta.section type="copyright"/>
- </appinfo>
- <documentation>
- Copyright (c) 2011 Stefan Strobl and Martin Reiterer 2011. All rights reserved.
- </documentation>
- </annotation>
-
-</schema>
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Activator.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Activator.java
deleted file mode 100644
index ae587f38..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Activator.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package org.eclipselabs.tapiji.tools.core;
-
-import java.text.MessageFormat;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.osgi.framework.BundleContext;
-
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipselabs.tapiji.tools.core";
-
- // The builder extension id
- public static final String BUILDER_EXTENSION_ID = "org.eclipselabs.tapiji.tools.core.builderExtension";
-
- // The shared instance
- private static Activator plugin;
-
- //Resource bundle.
- private ResourceBundle resourceBundle;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- 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 {
- // save state of ResourceBundleManager
- ResourceBundleManager.saveManagerState();
-
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- if (path.indexOf("icons/") < 0)
- path = "icons/" + path;
-
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @return localized string corresponding to key
- */
- public static String getString(String key) {
- ResourceBundle bundle =
- Activator.getDefault().getResourceBundle();
- try {
- return (bundle != null) ? bundle.getString(key) : key;
- } catch (MissingResourceException e) {
- return key;
- }
- }
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1) {
- return MessageFormat.format(getString(key), new String[]{arg1});
- }
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime first argument to replace in key value
- * @param arg2 runtime second argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1, String arg2) {
- return MessageFormat.format(
- getString(key), new String[]{arg1, arg2});
- }
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime argument to replace in key value
- * @param arg2 runtime second argument to replace in key value
- * @param arg3 runtime third argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(
- String key, String arg1, String arg2, String arg3) {
- return MessageFormat.format(
- getString(key), new String[]{arg1, arg2, arg3});
- }
-
- /**
- * Returns the plugin's resource bundle.
- * @return resource bundle
- */
- protected ResourceBundle getResourceBundle() {
- return resourceBundle;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Logger.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Logger.java
deleted file mode 100644
index c6660809..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Logger.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.eclipselabs.tapiji.tools.core;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-public class Logger {
-
- public static void logInfo (String message) {
- log(IStatus.INFO, IStatus.OK, message, null);
- }
-
- public static void logError (Throwable exception) {
- logError("Unexpected Exception", exception);
- }
-
- public static void logError(String message, Throwable exception) {
- log(IStatus.ERROR, IStatus.OK, message, exception);
- }
-
- public static void log(int severity, int code, String message, Throwable exception) {
- log(createStatus(severity, code, message, exception));
- }
-
- public static IStatus createStatus(int severity, int code, String message, Throwable exception) {
- return new Status(severity, Activator.PLUGIN_ID, code, message, exception);
- }
-
- public static void log(IStatus status) {
- Activator.getDefault().getLog().log(status);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/BuilderPropertyChangeListener.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
deleted file mode 100644
index c259653b..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-
-
-public class BuilderPropertyChangeListener implements IPropertyChangeListener {
-
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getNewValue().equals(true) && isTapiPropertyp(event))
- rebuild();
-
- if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN))
- rebuild();
-
- if (event.getNewValue().equals(false)){
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)){
- removeProperty(EditorUtils.MARKER_ID, -1);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)){
- removeProperty(EditorUtils.RB_MARKER_ID, -1);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)){
- removeProperty(EditorUtils.RB_MARKER_ID, IMarkerConstants.CAUSE_UNSPEZIFIED_KEY);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)){
- removeProperty(EditorUtils.RB_MARKER_ID, IMarkerConstants.CAUSE_SAME_VALUE);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)){
- removeProperty(EditorUtils.RB_MARKER_ID, IMarkerConstants.CAUSE_MISSING_LANGUAGE);
- }
- }
-
- }
-
- private boolean isTapiPropertyp(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 removeProperty(final String markertpye, 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(markertpye, 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(markertpye, true, IResource.DEPTH_INFINITE);
- }
- }
- } catch (CoreException e) {
- }
- }
- });
- }
-
- private void rebuild(){
- final IWorkspace workspace = ResourcesPlugin.getWorkspace();
-
- new Job ("Audit source files") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- for (IResource res : workspace.getRoot().members()){
- final IProject p = (IProject) res;
- try {
- p.build ( StringLiteralAuditor.FULL_BUILD,
- StringLiteralAuditor.BUILDER_ID,
- null,
- monitor);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
-
- }.schedule();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java
deleted file mode 100644
index 85287854..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java
+++ /dev/null
@@ -1,134 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.Logger;
-
-
-public class InternationalizationNature implements IProjectNature {
-
- private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
- private IProject project;
-
- @Override
- public void configure() throws CoreException {
- StringLiteralAuditor.addBuilderToProject(project);
- new Job ("Audit source files") {
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- project.build ( StringLiteralAuditor.FULL_BUILD,
- StringLiteralAuditor.BUILDER_ID,
- null,
- monitor);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
-
- }.schedule();
- }
-
- @Override
- public void deconfigure() throws CoreException {
- StringLiteralAuditor.removeBuilderFromProject(project);
- }
-
- @Override
- public IProject getProject() {
- return project;
- }
-
- @Override
- public void setProject(IProject project) {
- this.project = project;
- }
-
- public static void addNature(IProject project) {
- if (!project.isOpen())
- return;
-
- IProjectDescription description = null;
-
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String> ();
- newIds.addAll (Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf (NATURE_ID);
- if (index != -1)
- return;
-
- // Add the nature
- newIds.add (NATURE_ID);
- description.setNatureIds (newIds.toArray (new String[newIds.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public static boolean supportsNature (IProject project) {
- return project.isOpen();
- }
-
- public static boolean hasNature (IProject project) {
- try {
- return project.isOpen () && project.hasNature(NATURE_ID);
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
- }
-
- public static void removeNature (IProject project) {
- if (!project.isOpen())
- return;
-
- IProjectDescription description = null;
-
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String> ();
- newIds.addAll (Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf (NATURE_ID);
- if (index == -1)
- return;
-
- // remove the nature
- newIds.remove (NATURE_ID);
- description.setNatureIds (newIds.toArray (new String[newIds.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java
deleted file mode 100644
index b9b1d367..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java
+++ /dev/null
@@ -1,458 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.configuration.IConfiguration;
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.builder.analyzer.RBAuditor;
-import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceFinder;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nRBAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-
-
-public class StringLiteralAuditor extends IncrementalProjectBuilder{
-
- public static final String BUILDER_ID = Activator.PLUGIN_ID
- + ".I18NBuilder";
-
- private static I18nAuditor[] resourceAuditors;
- private static Set<String> supportedFileEndings;
- private static IPropertyChangeListener listner;
-
-
- static {
- List<I18nAuditor> auditors = new ArrayList<I18nAuditor>();
- supportedFileEndings = new HashSet<String>();
-
- // init default auditors
- auditors.add(new RBAuditor());
-
- // lookup registered auditor extensions
- IConfigurationElement[] config = Platform.getExtensionRegistry()
- .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID);
-
- try {
- for (IConfigurationElement e : config) {
- I18nAuditor a = (I18nAuditor) e.createExecutableExtension("class");
- auditors.add(a);
- supportedFileEndings.addAll(Arrays.asList(a.getFileEndings()));
- }
- } catch (CoreException ex) {
- Logger.logError(ex);
- }
-
- resourceAuditors = auditors.toArray(new I18nAuditor[auditors.size()]);
-
- listner = new BuilderPropertyChangeListener();
- TapiJIPreferences.addPropertyChangeListener(listner);
- }
-
- public StringLiteralAuditor() {
- }
-
- public static I18nAuditor getI18nAuditorByContext(String contextId)
- throws NoSuchResourceAuditorException {
- for (I18nAuditor auditor : resourceAuditors) {
- if (auditor.getContextId().equals(contextId))
- return auditor;
- }
- throw new NoSuchResourceAuditorException();
- }
-
- private Set<String> getSupportedFileExt() {
- return supportedFileEndings;
- }
-
- 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() {
- public void run(IProgressMonitor monitor) throws CoreException {
- if (kind == FULL_BUILD) {
- fullBuild(monitor);
- } else {
- // only perform audit if the resource delta is not empty
- IResourceDelta resDelta = getDelta(getProject());
-
- if (resDelta == null)
- return;
-
- if (resDelta.getAffectedChildren() == null)
- return;
-
- incrementalBuild(monitor, resDelta);
- }
- }
- },
- monitor);
-
- return null;
- }
-
- private void incrementalBuild(IProgressMonitor monitor,
- IResourceDelta resDelta) throws CoreException {
- try {
- // inspect resource delta
- ResourceFinder csrav = new ResourceFinder(getSupportedFileExt());
- resDelta.accept(csrav);
- auditResources(csrav.getResources(), monitor, getProject());
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public void buildResource(IResource resource, IProgressMonitor monitor) {
- if (isResourceAuditable(resource, getSupportedFileExt())) {
- List<IResource> resources = new ArrayList<IResource>();
- resources.add(resource);
- // TODO: create instance of progressmonitor and hand it over to
- // auditResources
- try {
- auditResources(resources, monitor, getProject());
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
- }
-
- public void buildProject(IProgressMonitor monitor, IProject proj) {
- try {
- ResourceFinder csrav = new ResourceFinder(getSupportedFileExt());
- proj.accept(csrav);
- auditResources(csrav.getResources(), monitor, proj);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- private void fullBuild(IProgressMonitor monitor) {
- buildProject(monitor, getProject());
- }
-
- private void auditResources(List<IResource> resources,
- IProgressMonitor monitor, IProject project) {
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
-
- int work = resources.size();
- int actWork = 0;
- if (monitor == null) {
- monitor = new NullProgressMonitor();
- }
-
- monitor.beginTask("Audit resource file for Internationalization problems",
- work);
-
- for (IResource resource : resources) {
- monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- if (!EditorUtils.deleteAuditMarkersForResource(resource))
- continue;
-
- if (ResourceBundleManager.isResourceExcluded(resource))
- continue;
-
- if (!resource.exists())
- continue;
-
- for (I18nAuditor ra : resourceAuditors) {
- if (ra instanceof I18nResourceAuditor && !(configuration.getAuditResource()))
- continue;
- if (ra instanceof I18nRBAuditor && !(configuration.getAuditRb()))
- continue;
-
- try {
- if (monitor.isCanceled()) {
- monitor.done();
- break;
- }
-
- if (ra.isResourceOfType(resource)) {
- ra.audit(resource);
- }
- } catch (Exception e) {
- Logger.logError("Error during auditing '" + resource.getFullPath() + "'", e);
- }
- }
-
- if (monitor != null)
- monitor.worked(1);
- }
-
- for (I18nAuditor a : resourceAuditors) {
- if (a instanceof I18nResourceAuditor){
- handleI18NAuditorMarkers((I18nResourceAuditor)a);
- }
- if (a instanceof I18nRBAuditor){
- handleI18NAuditorMarkers((I18nRBAuditor)a);
- ((I18nRBAuditor)a).resetProblems();
- }
- }
-
- monitor.done();
- }
-
- private void handleI18NAuditorMarkers(I18nResourceAuditor ra){
- try {
- for (ILocation problem : ra.getConstantStringLiterals()) {
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
- new String[] { problem
- .getLiteral() }),
- problem,
- IMarkerConstants.CAUSE_CONSTANT_LITERAL,
- "", (ILocation) problem.getData(),
- ra.getContextId());
- }
-
- // Report all broken Resource-Bundle references
- for (ILocation brokenLiteral : ra
- .getBrokenResourceReferences()) {
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
- new String[] {
- brokenLiteral
- .getLiteral(),
- ((ILocation) brokenLiteral
- .getData())
- .getLiteral() }),
- brokenLiteral,
- IMarkerConstants.CAUSE_BROKEN_REFERENCE,
- brokenLiteral.getLiteral(),
- (ILocation) brokenLiteral.getData(),
- ra.getContextId());
- }
-
- // Report all broken definitions to Resource-Bundle
- // references
- for (ILocation brokenLiteral : ra
- .getBrokenBundleReferences()) {
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
- new String[] { brokenLiteral
- .getLiteral() }),
- brokenLiteral,
- IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
- brokenLiteral.getLiteral(),
- (ILocation) brokenLiteral.getData(),
- ra.getContextId());
- }
- } catch (Exception e) {
- Logger.logError("Exception during reporting of Internationalization errors", e);
- }
- }
-
- private void handleI18NAuditorMarkers(I18nRBAuditor ra){
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
- try {
- //Report all unspecified keys
- if (configuration.getAuditMissingValue())
- for (ILocation problem : ra.getUnspecifiedKeyReferences()) {
- EditorUtils.reportToRBMarker(
- EditorUtils.getFormattedMessage(
- EditorUtils.MESSAGE_UNSPECIFIED_KEYS,
- new String[] {problem.getLiteral(), problem.getFile().getName()}),
- problem,
- IMarkerConstants.CAUSE_UNSPEZIFIED_KEY,
- problem.getLiteral(),"",
- (ILocation) problem.getData(),
- ra.getContextId());
- }
-
- //Report all same values
- if(configuration.getAuditSameValue()){
- Map<ILocation,ILocation> sameValues = ra.getSameValuesReferences();
- for (ILocation problem : sameValues.keySet()) {
- EditorUtils.reportToRBMarker(
- EditorUtils.getFormattedMessage(
- EditorUtils.MESSAGE_SAME_VALUE,
- new String[] {problem.getFile().getName(),
- sameValues.get(problem).getFile().getName(),
- problem.getLiteral()}),
- problem,
- IMarkerConstants.CAUSE_SAME_VALUE,
- problem.getLiteral(),
- sameValues.get(problem).getFile().getName(),
- (ILocation) problem.getData(),
- ra.getContextId());
- }
- }
- // Report all missing languages
- if (configuration.getAuditMissingLanguage())
- for (ILocation problem : ra.getMissingLanguageReferences()) {
- EditorUtils.reportToRBMarker(
- EditorUtils.getFormattedMessage(
- EditorUtils.MESSAGE_MISSING_LANGUAGE,
- new String[] {RBFileUtils.getCorrespondingResourceBundleId(problem.getFile()),
- problem.getLiteral()}),
- problem,
- IMarkerConstants.CAUSE_MISSING_LANGUAGE,
- problem.getLiteral(),"",
- (ILocation) problem.getData(),
- ra.getContextId());
- }
- } catch (Exception e) {
- Logger.logError("Exception during reporting of Internationalization errors", e);
- }
- }
-
-
-
- @SuppressWarnings("unused")
- private void setProgress(IProgressMonitor monitor, int progress)
- throws InterruptedException {
- monitor.worked(progress);
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- if (isInterrupted())
- throw new InterruptedException();
- }
-
- @Override
- protected void clean(IProgressMonitor monitor) throws CoreException {
- // TODO Auto-generated method stub
- super.clean(monitor);
- }
-
- public static void addBuilderToProject(IProject project) {
- Logger.logInfo("Internationalization-Builder registered for '" + project.getName() + "'");
-
- // Only for open projects
- if (!project.isOpen())
- return;
-
- IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // Check if the builder is already associated to the specified project
- ICommand[] commands = description.getBuildSpec();
- for (ICommand command : commands) {
- if (command.getBuilderName().equals(BUILDER_ID))
- return;
- }
-
- // Associate the builder with the project
- ICommand builderCmd = description.newCommand();
- builderCmd.setBuilderName(BUILDER_ID);
- List<ICommand> newCommands = new ArrayList<ICommand>();
- newCommands.addAll(Arrays.asList(commands));
- newCommands.add(builderCmd);
- description.setBuildSpec((ICommand[]) newCommands
- .toArray(new ICommand[newCommands.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public static void removeBuilderFromProject(IProject project) {
- // Only for open projects
- if (!project.isOpen())
- return;
-
- try {
- project.deleteMarkers(EditorUtils.MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- project.deleteMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- } catch (CoreException e1) {
- Logger.logError(e1);
- }
-
- IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // remove builder from project
- int idx = -1;
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; i++) {
- if (commands[i].getBuilderName().equals(BUILDER_ID)) {
- idx = i;
- break;
- }
- }
- if (idx == -1)
- return;
-
- List<ICommand> newCommands = new ArrayList<ICommand>();
- newCommands.addAll(Arrays.asList(commands));
- newCommands.remove(idx);
- description.setBuildSpec((ICommand[]) newCommands
- .toArray(new ICommand[newCommands.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
-
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
deleted file mode 100644
index a460cf2f..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolutionGenerator2;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor;
-import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-
-public class ViolationResolutionGenerator implements
- IMarkerResolutionGenerator2 {
-
- @Override
- public boolean hasResolutions(IMarker marker) {
- return true;
- }
-
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
-
- EditorUtils.updateMarker(marker);
-
- String contextId = marker.getAttribute("context", "");
-
- // find resolution generator for the given context
- try {
- I18nAuditor auditor = StringLiteralAuditor
- .getI18nAuditorByContext(contextId);
- List<IMarkerResolution> resolutions = auditor
- .getMarkerResolutions(marker);
- return resolutions
- .toArray(new IMarkerResolution[resolutions.size()]);
- } catch (NoSuchResourceAuditorException e) {
- }
-
- return new IMarkerResolution[0];
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java
deleted file mode 100644
index 047d4a31..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder.analyzer;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-
-
-public class RBAuditor extends I18nResourceAuditor {
-
- @Override
- public void audit(IResource resource) {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- ResourceBundleManager.getManager(resource.getProject()).addBundleResource (resource);
- }
- }
-
- @Override
- public String[] getFileEndings() {
- return new String [] { "properties" };
- }
-
- @Override
- public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public String getContextId() {
- return "resource_bundle";
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
deleted file mode 100644
index c4bb4677..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder.analyzer;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-
-
-public class ResourceBundleDetectionVisitor implements IResourceVisitor,
- IResourceDeltaVisitor {
-
- private ResourceBundleManager manager = null;
-
- public ResourceBundleDetectionVisitor(ResourceBundleManager manager) {
- this.manager = manager;
- }
-
- @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))
- manager.addBundleResource(resource);
- return false;
- } else
- return true;
- } catch (Exception e) {
- return false;
- }
- }
-
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
-
- if (RBFileUtils.isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
-
- return true;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java
deleted file mode 100644
index 98e0af7b..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder.analyzer;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
-
-
-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 (StringLiteralAuditor.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.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
deleted file mode 100644
index ccfbf69e..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
+++ /dev/null
@@ -1,172 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder.quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.wizard.IWizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.wizards.IWizardDescriptor;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import org.eclipselabs.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
-
-public class CreateResourceBundle implements IMarkerResolution2 {
-
- private IResource resource;
- private int start;
- private int end;
- private String key;
- private boolean jsfContext;
- private final String newBunldeWizard = "com.essiembre.eclipse.rbe.ui.wizards.ResourceBundleWizard";
-
- public CreateResourceBundle(String key, IResource resource, int start, int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key, ResourceBundleManager.getManager( resource.getProject() ));
- this.resource = resource;
- this.start = start;
- this.end = end;
- this.jsfContext = jsfContext;
- }
-
- @Override
- public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
- }
-
- @Override
- public void run(IMarker marker) {
- runAction();
- }
-
- protected void runAction () {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
- if (!(wizard instanceof IResourceBundleWizard))
- return;
-
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length-1];
- String packageName = "";
-
- rbw.setBundleId(rbName);
-
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
-
- for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr.getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
-
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
-
- rbw.setDefaultPath (pathName);
-
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- (new StringLiteralAuditor()).buildProject(null, resource.getProject());
- (new StringLiteralAuditor()).buildResource(resource, null);
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- if (document.get().charAt(start-1) == '"' && document.get().charAt(start) != '"') {
- start --;
- end ++;
- }
- if (document.get().charAt(end+1) == '"' && document.get().charAt(end) != '"')
- end ++;
-
- document.replace(start, end-start,
- "\"" +
- (packageName.equals("") ? "" : packageName + ".") + rbName +
- "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- }
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java
deleted file mode 100644
index 85d59483..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.builder.quickfix;
-
-import java.util.Set;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-
-public class IncludeResource implements IMarkerResolution2 {
-
- private String bundleName;
- private Set<IResource> bundleResources;
-
- public IncludeResource (String bundleName, Set<IResource> bundleResources) {
- this.bundleResources = bundleResources;
- this.bundleName = bundleName;
- }
-
- @Override
- public String getDescription() {
- return "The Resource-Bundle with id '" + bundleName + "' has been " +
- "excluded from Internationalization. Based on this fact, no internationalization " +
- "supoort is provided for this Resource-Bundle. Performing this action, internationalization " +
- "support for '" + bundleName + "' will be enabled";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Include excluded Resource-Bundle '" + bundleName + "'";
- }
-
- @Override
- public void run(final IMarker marker) {
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(marker.getResource().getProject());
- pm.beginTask("Including resources to Internationalization", bundleResources.size());
- for (IResource resource : bundleResources) {
- manager.includeResource(resource, pm);
- pm.worked(1);
- }
- pm.done();
- }
- });
- } catch (Exception e) {}
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nAuditor.java
deleted file mode 100644
index d6d6d6c4..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nAuditor.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.extensions;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-public abstract class I18nAuditor {
-
- /**
- * Audits a project resource for I18N problems. This method is triggered
- * during the project's build process.
- *
- * @param resource
- * The project resource
- */
- public abstract void audit(IResource resource);
-
- /**
- * Returns a characterizing identifier of the implemented auditing
- * functionality. The specified identifier is used for discriminating
- * registered builder extensions.
- *
- * @return The String id of the implemented auditing functionality
- */
- public abstract String getContextId();
-
- /**
- * Returns a list of supported file endings.
- *
- * @return The supported file endings
- */
- public abstract String[] getFileEndings();
-
-
- /**
- * Returns a list of quick fixes of a reported Internationalization problem.
- *
- * @param marker
- * The warning marker of the Internationalization problem
- * @param cause
- * The problem type
- * @return The list of marker resolution proposals
- */
- public abstract List<IMarkerResolution> getMarkerResolutions(
- IMarker marker);
-
- /**
- * Checks if the provided resource auditor is responsible for a particular
- * resource.
- *
- * @param resource
- * The resource reference
- * @return True if the resource auditor is responsible for the referenced
- * resource
- */
- public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nRBAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nRBAuditor.java
deleted file mode 100644
index fbdc852d..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nRBAuditor.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.extensions;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- *
- *
- */
-public abstract class I18nRBAuditor extends I18nAuditor{
-
- /**
- * Mark the end of a audit and reset all problemlists
- */
- public abstract void resetProblems();
-
- /**
- * Returns the list of missing keys or no specified Resource-Bundle-key
- * refernces. Each list entry describes the textual position on which this
- * type of error has been detected.
- * @return The list of positions of no specified RB-key refernces
- */
- public abstract List<ILocation> getUnspecifiedKeyReferences();
-
- /**
- * Returns the list of same Resource-Bundle-value refernces. Each list entry
- * describes the textual position on which this type of error has been
- * detected.
- * @return The list of positions of same RB-value refernces
- */
- public abstract Map<ILocation, ILocation> getSameValuesReferences();
-
- /**
- * Returns the list of missing Resource-Bundle-languages compared with the
- * Resource-Bundles of the hole project. Each list entry describes the
- * textual position on which this type of error has been detected.
- * @return
- */
- public abstract List<ILocation> getMissingLanguageReferences();
-
-
- //public abstract List<ILocation> getUnusedKeyReferences();
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java
deleted file mode 100644
index 6dddcc32..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.extensions;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-/**
- * Auditor class for finding I18N problems within source code resources. The
- * objects audit method is called for a particular resource. Found errors are
- * stored within the object's internal data structure and can be queried with
- * the help of problem categorized getter methods.
- */
-public abstract class I18nResourceAuditor extends I18nAuditor{
- /**
- * Audits a project resource for I18N problems. This method is triggered
- * during the project's build process.
- *
- * @param resource
- * The project resource
- */
- public abstract void audit(IResource resource);
-
- /**
- * Returns a list of supported file endings.
- *
- * @return The supported file endings
- */
- public abstract String[] getFileEndings();
-
- /**
- * Returns the list of found need-to-translate string literals. Each list
- * entry describes the textual position on which this type of error has been
- * detected.
- *
- * @return The list of need-to-translate string literal positions
- */
- public abstract List<ILocation> getConstantStringLiterals();
-
- /**
- * Returns the list of broken Resource-Bundle references. Each list entry
- * describes the textual position on which this type of error has been
- * detected.
- *
- * @return The list of positions of broken Resource-Bundle references
- */
- public abstract List<ILocation> getBrokenResourceReferences();
-
- /**
- * Returns the list of broken references to Resource-Bundle entries. Each
- * list entry describes the textual position on which this type of error has
- * been detected
- *
- * @return The list of positions of broken references to locale-sensitive
- * resources
- */
- public abstract List<ILocation> getBrokenBundleReferences();
-
- /**
- * Returns a characterizing identifier of the implemented auditing
- * functionality. The specified identifier is used for discriminating
- * registered builder extensions.
- *
- * @return The String id of the implemented auditing functionality
- */
- public abstract String getContextId();
-
- /**
- * Returns a list of quick fixes of a reported Internationalization problem.
- *
- * @param marker
- * The warning marker of the Internationalization problem
- * @param cause
- * The problem type
- * @return The list of marker resolution proposals
- */
- public abstract List<IMarkerResolution> getMarkerResolutions(
- IMarker marker);
-
- /**
- * Checks if the provided resource auditor is responsible for a particular
- * resource.
- *
- * @param resource
- * The resource reference
- * @return True if the resource auditor is responsible for the referenced
- * resource
- */
- public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java
deleted file mode 100644
index 7d567598..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.extensions;
-
-import java.io.Serializable;
-
-import org.eclipse.core.resources.IFile;
-
-/**
- * Describes a text fragment within a source resource.
- *
- * @author Martin Reiterer
- */
-public interface ILocation {
-
- /**
- * Returns the source resource's physical location.
- *
- * @return The file within the text fragment is located
- */
- public IFile getFile();
-
- /**
- * Returns the position of the text fragments starting character.
- *
- * @return The position of the first character
- */
- public int getStartPos();
-
- /**
- * Returns the position of the text fragments last character.
- *
- * @return The position of the last character
- */
- public int getEndPos();
-
- /**
- * Returns the text fragment.
- *
- * @return The text fragment
- */
- public String getLiteral();
-
- /**
- * Returns additional metadata. The type and content of this property is not
- * specified and can be used to marshal additional data for the computation
- * of resolution proposals.
- *
- * @return The metadata associated with the text fragment
- */
- public Serializable getData();
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java
deleted file mode 100644
index 03dd6535..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.extensions;
-
-public interface IMarkerConstants {
- public static final int CAUSE_BROKEN_REFERENCE = 0;
- public static final int CAUSE_CONSTANT_LITERAL = 1;
- public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
-
- public static final int CAUSE_UNSPEZIFIED_KEY = 3;
- public static final int CAUSE_SAME_VALUE = 4;
- public static final int CAUSE_MISSING_LANGUAGE = 5;
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java
deleted file mode 100644
index 576d65af..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model;
-
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-
-public interface IResourceBundleChangedListener {
-
- public void resourceBundleChanged (ResourceBundleChangedEvent event);
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java
deleted file mode 100644
index 8fda62ba..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model;
-
-public interface IResourceDescriptor {
-
- public void setProjectName (String projName);
-
- public void setRelativePath (String relPath);
-
- public void setAbsolutePath (String absPath);
-
- public void setBundleId (String bundleId);
-
- public String getProjectName ();
-
- public String getRelativePath ();
-
- public String getAbsolutePath ();
-
- public String getBundleId ();
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java
deleted file mode 100644
index 881cacb5..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model;
-
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceExclusionEvent;
-
-public interface IResourceExclusionListener {
-
- public void exclusionChanged(ResourceExclusionEvent event);
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java
deleted file mode 100644
index 32fc17f9..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model;
-
-import org.eclipse.core.resources.IResource;
-
-public class ResourceDescriptor implements IResourceDescriptor {
-
- private String projectName;
- private String relativePath;
- private String absolutePath;
- private String bundleId;
-
- public ResourceDescriptor (IResource resource) {
- projectName = resource.getProject().getName();
- relativePath = resource.getProjectRelativePath().toString();
- absolutePath = resource.getRawLocation().toString();
- }
-
- public ResourceDescriptor() {
- }
-
- @Override
- public String getAbsolutePath() {
- return absolutePath;
- }
-
- @Override
- public String getProjectName() {
- return projectName;
- }
-
- @Override
- public String getRelativePath() {
- return relativePath;
- }
-
- @Override
- public int hashCode() {
- return projectName.hashCode() + relativePath.hashCode();
- }
-
- @Override
- public boolean equals(Object other) {
- if (!(other instanceof ResourceDescriptor))
- return false;
-
- return absolutePath.equals(absolutePath);
- }
-
- @Override
- public void setAbsolutePath(String absPath) {
- this.absolutePath = absPath;
- }
-
- @Override
- public void setProjectName(String projName) {
- this.projectName = projName;
- }
-
- @Override
- public void setRelativePath(String relPath) {
- this.relativePath = relPath;
- }
-
- @Override
- public String getBundleId() {
- return this.bundleId;
- }
-
- @Override
- public void setBundleId(String bundleId) {
- this.bundleId = bundleId;
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java
deleted file mode 100644
index cb633c54..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model;
-
-import java.io.Serializable;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-
-
-public class SLLocation implements Serializable, ILocation {
-
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
-
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
- public IFile getFile() {
- return file;
- }
- public void setFile(IFile file) {
- this.file = file;
- }
- public int getStartPos() {
- return startPos;
- }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
- public int getEndPos() {
- return endPos;
- }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
- public String getLiteral() {
- return literal;
- }
- public Serializable getData () {
- return data;
- }
- public void setData (Serializable data) {
- this.data = data;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
deleted file mode 100644
index 08f79a7e..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.exception;
-
-public class NoSuchResourceAuditorException extends Exception {
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java
deleted file mode 100644
index 93b43daf..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.exception;
-
-public class ResourceBundleException extends Exception {
-
- private static final long serialVersionUID = -2039182473628481126L;
-
- public ResourceBundleException (String msg) {
- super (msg);
- }
-
- public ResourceBundleException () {
- super();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/RBChangeListner.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/RBChangeListner.java
deleted file mode 100644
index 4433a825..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/RBChangeListner.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.manager;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-
-public class RBChangeListner implements IResourceChangeListener {
-
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- try {
- event.getDelta().accept(new IResourceDeltaVisitor() {
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
- if (RBFileUtils.isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
- return true;
- }
- });
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
deleted file mode 100644
index 73d90d42..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.manager;
-
-import org.eclipse.core.resources.IProject;
-
-public class ResourceBundleChangedEvent {
-
- public final static int ADDED = 0;
- public final static int DELETED = 1;
- public final static int MODIFIED = 2;
- public final static int EXCLUDED = 3;
- public final static int INCLUDED = 4;
-
- private IProject project;
- private String bundle = "";
- private int type = -1;
-
- public ResourceBundleChangedEvent (int type, String bundle, IProject project) {
- this.type = type;
- this.bundle = bundle;
- this.project = project;
- }
-
- public IProject getProject() {
- return project;
- }
-
- public void setProject(IProject project) {
- this.project = project;
- }
-
- public String getBundle() {
- return bundle;
- }
-
- public void setBundle(String bundle) {
- this.bundle = bundle;
- }
-
- public int getType() {
- return type;
- }
-
- public void setType(int type) {
- this.type = type;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java
deleted file mode 100644
index c275308e..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.manager;
-
-public class ResourceBundleDetector {
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java
deleted file mode 100644
index b8daf33d..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java
+++ /dev/null
@@ -1,773 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.manager;
-
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.MessagesBundleFactory;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.XMLMemento;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
-import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceBundleDetectionVisitor;
-import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipselabs.tapiji.tools.core.model.IResourceDescriptor;
-import org.eclipselabs.tapiji.tools.core.model.IResourceExclusionListener;
-import org.eclipselabs.tapiji.tools.core.model.ResourceDescriptor;
-import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.tools.core.util.FileUtils;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-
-public class ResourceBundleManager {
-
- public static String defaultLocaleTag = "[default]"; // TODO externalize
-
- /*** CONFIG SECTION ***/
- private static boolean checkResourceExclusionRoot = false;
-
- /*** MEMBER SECTION ***/
- private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>();
-
- public static final String RESOURCE_BUNDLE_EXTENSION = ".properties";
-
- //project-specific
- private Map<String, Set<IResource>> resources =
- new HashMap<String, Set<IResource>> ();
-
- private Map<String, String> bundleNames = new HashMap<String, String> ();
-
- private Map<String, List<IResourceBundleChangedListener>> listeners =
- new HashMap<String, List<IResourceBundleChangedListener>> ();
-
- private List<IResourceExclusionListener> exclusionListeners =
- new ArrayList<IResourceExclusionListener> ();
-
- //global
- private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor> ();
-
- private static Map<String, Set<IResource>> allBundles =
- new HashMap<String, Set<IResource>> ();
-
- private static IResourceChangeListener changelistener;
-
- /*Host project*/
- private IProject project = null;
-
- /** State-Serialization Information **/
- private static boolean state_loaded = false;
- private static final String TAG_INTERNATIONALIZATION = "Internationalization";
- private static final String TAG_EXCLUDED = "Excluded";
- private static final String TAG_RES_DESC = "ResourceDescription";
- private static final String TAG_RES_DESC_ABS = "AbsolutePath";
- private static final String TAG_RES_DESC_REL = "RelativePath";
- private static final String TAB_RES_DESC_PRO = "ProjectName";
- private static final String TAB_RES_DESC_BID = "BundleId";
-
- // Define private constructor
- private ResourceBundleManager () {
- }
-
- public static ResourceBundleManager getManager (IProject project) {
- // check if persistant state has been loaded
- if (!state_loaded)
- loadManagerState();
-
- // set host-project
- if (FragmentProjectUtils.isFragment(project))
- project = FragmentProjectUtils.getFragmentHost(project);
-
-
- ResourceBundleManager manager = rbmanager.get(project);
- if (manager == null) {
- manager = new ResourceBundleManager();
- manager.project = project;
- manager.detectResourceBundles();
- rbmanager.put(project, manager);
-
- }
- return manager;
- }
-
- public Set<Locale> getProvidedLocales (String bundleName) {
- RBManager instance = RBManager.getInstance(project);
-
- Set<Locale> locales = new HashSet<Locale>();
- IMessagesBundleGroup group = instance.getMessagesBundleGroup(bundleName);
- if (group == null)
- return locales;
-
- for (IMessagesBundle bundle : group.getMessagesBundles()) {
- locales.add(bundle.getLocale());
- }
- return locales;
- }
-
- public static String getResourceBundleName(IResource res) {
- String name = res.getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + res.getFileExtension() + ")$"; //$NON-NLS-1$
- return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
- }
-
- protected boolean isResourceBundleLoaded (String bundleName) {
- return RBManager.getInstance(project).containsMessagesBundleGroup(bundleName);
- }
-
- protected Locale getLocaleByName (String bundleName, String localeID) {
- // Check locale
- Locale locale = null;
- bundleName = bundleNames.get(bundleName);
- localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
- if (localeID.length() == bundleName.length()) {
- // default locale
- return null;
- } else {
- localeID = localeID.substring(bundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
-
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
- break;
- default:
- locale = null;
- break;
- }
- }
-
- return locale;
- }
-
- protected void unloadResource (String bundleName, IResource resource) {
- // TODO implement more efficient
- unloadResourceBundle(bundleName);
-// loadResourceBundle(bundleName);
- }
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
- public void addBundleResource (IResource resource) {
- if (resource.isDerived())
- return;
-
- String bundleName = getResourceBundleId(resource);
- Set<IResource> res;
-
- if (!resources.containsKey(bundleName))
- res = new HashSet<IResource> ();
- else
- res = resources.get(bundleName);
-
- res.add(resource);
- resources.put(bundleName, res);
- allBundles.put(bundleName, new HashSet<IResource>(res));
- bundleNames.put(bundleName, getResourceBundleName(resource));
-
- // Fire resource changed event
- ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.ADDED,
- bundleName,
- resource.getProject());
- this.fireResourceBundleChangedEvent(bundleName, event);
- }
-
- protected void removeAllBundleResources(String bundleName) {
- unloadResourceBundle(bundleName);
- resources.remove(bundleName);
- //allBundles.remove(bundleName);
- listeners.remove(bundleName);
- }
-
- public void unloadResourceBundle (String name) {
- RBManager instance = RBManager.getInstance(project);
- instance.deleteMessagesBundle(name);
- }
-
- public IMessagesBundleGroup getResourceBundle (String name) {
- RBManager instance = RBManager.getInstance(project);
- return instance.getMessagesBundleGroup(name);
- }
-
- public Collection<IResource> getResourceBundles (String bundleName) {
- return resources.get(bundleName);
- }
-
- public List<String> getResourceBundleNames () {
- List<String> returnList = new ArrayList<String>();
-
- Iterator<String> it = resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
- return returnList;
- }
-
- public IResource getResourceFile (String file) {
- String regex = "^(.*?)"
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + "properties" + ")$";
- String bundleName = file.replaceFirst(regex, "$1");
- IResource resource = null;
-
- for (IResource res : resources.get(bundleName)) {
- if (res.getName().equalsIgnoreCase(file)) {
- resource = res;
- break;
- }
- }
-
- return resource;
- }
-
- public void fireResourceBundleChangedEvent (String bundleName, ResourceBundleChangedEvent event) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
-
- if (l == null)
- return;
-
- for (IResourceBundleChangedListener listener : l) {
- listener.resourceBundleChanged(event);
- }
- }
-
- public void registerResourceBundleChangeListener (String bundleName, IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null)
- l = new ArrayList<IResourceBundleChangedListener>();
- l.add(listener);
- listeners.put(bundleName, l);
- }
-
- public void unregisterResourceBundleChangeListener (String bundleName, IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null)
- return;
- l.remove(listener);
- listeners.put(bundleName, l);
- }
-
- protected void detectResourceBundles () {
- try {
- project.accept(new ResourceBundleDetectionVisitor(this));
-
- IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
- if (fragments != null){
- for (IProject p : fragments){
- p.accept(new ResourceBundleDetectionVisitor(this));
- }
- }
- } catch (CoreException e) {
- }
- }
-
- public IProject getProject () {
- return project;
- }
-
- public List<String> getResourceBundleIdentifiers () {
- List<String> returnList = new ArrayList<String>();
-
- // TODO check other resource bundles that are available on the curren class path
- Iterator<String> it = this.resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
-
- return returnList;
- }
-
- public static List<String> getAllResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
-
- for (IProject p : getAllSupportedProjects()) {
- if (!FragmentProjectUtils.isFragment(p)){
- Iterator<String> it = getManager(p).resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(p.getName() + "/" + it.next());
- }
- }
- }
- return returnList;
- }
-
- public static Set<IProject> getAllSupportedProjects () {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- Set<IProject> projs = new HashSet<IProject>();
-
- for (IProject p : projects) {
- if (InternationalizationNature.hasNature(p))
- projs.add(p);
- }
- return projs;
- }
-
- public String getKeyHoverString(String rbName, String key) {
- try {
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(rbName);
- if (!bundleGroup.containsKey(key))
- return null;
-
- String hoverText = "<html><head></head><body>";
-
- for (IMessage message : bundleGroup.getMessages(key)) {
- String displayName = message.getLocale() == null ? "Default"
- : message.getLocale().getDisplayName();
- String value = message.getValue();
- hoverText += "<b><i>" + displayName + "</i></b><br/>"
- + value.replace("\n", "<br/>") + "<br/><br/>";
- }
- return hoverText + "</body></html>";
- } catch (Exception e) {
- // silent catch
- return "";
- }
- }
-
- public boolean isKeyBroken (String rbName, String key) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(project).getMessagesBundleGroup(rbName);
- if (messagesBundleGroup == null) {
- return true;
- } else {
- return !messagesBundleGroup.containsKey(key);
- }
-
-// if (!resourceBundles.containsKey(rbName))
-// return true;
-// return !this.isResourceExisting(rbName, key);
- }
-
- protected void excludeSingleResource (IResource res) {
- IResourceDescriptor rd = new ResourceDescriptor(res);
- EditorUtils.deleteAuditMarkersForResource(res);
-
- // exclude resource
- excludedResources.add(rd);
- Collection<Object> changedExclusoins = new HashSet<Object>();
- changedExclusoins.add(res);
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
-
- // Check if the excluded resource represents a resource-bundle
- if (RBFileUtils.isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- Set<IResource> resSet = resources.remove(bundleName);
- if (resSet != null) {
- resSet.remove(res);
-
- if (!resSet.isEmpty()) {
- resources.put(bundleName, resSet);
- unloadResource(bundleName, res);
- } else {
- rd.setBundleId(bundleName);
- unloadResourceBundle(bundleName);
- (new StringLiteralAuditor()).buildProject(null, res.getProject());
- }
-
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(ResourceBundleChangedEvent.EXCLUDED, bundleName,
- res.getProject()));
- }
- }
- }
-
- public void excludeResource (IResource res, IProgressMonitor monitor) {
- try {
- if (monitor == null)
- monitor = new NullProgressMonitor();
-
- final List<IResource> resourceSubTree = new ArrayList<IResource> ();
- res.accept(new IResourceVisitor () {
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- Logger.logInfo("Excluding resource '" + resource.getFullPath().toOSString() + "'");
- resourceSubTree.add(resource);
- return true;
- }
-
- });
-
- // Iterate previously retrieved resource and exclude them from Internationalization
- monitor.beginTask("Exclude resources from Internationalization context", resourceSubTree.size());
- try {
- for (IResource resource : resourceSubTree) {
- excludeSingleResource (resource);
- EditorUtils.deleteAuditMarkersForResource(resource);
- monitor.worked(1);
- }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public void includeResource (IResource res, IProgressMonitor monitor) {
- if (monitor == null)
- monitor = new NullProgressMonitor();
-
- final Collection<Object> changedResources = new HashSet<Object>();
- IResource resource = res;
-
- if (!excludedResources.contains(new ResourceDescriptor(res))) {
- while (!(resource instanceof IProject ||
- resource instanceof IWorkspaceRoot)) {
- if (excludedResources.contains(new ResourceDescriptor(resource))) {
- excludeResource(resource, monitor);
- changedResources.add(resource);
- break;
- } else
- resource = resource.getParent();
- }
- }
-
- try {
- res.accept(new IResourceVisitor() {
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- changedResources.add(resource);
- return true;
- }
- });
-
- monitor.beginTask("Add resources to Internationalization context", changedResources.size());
- try {
- for (Object r : changedResources) {
- excludedResources.remove(new ResourceDescriptor((IResource)r));
- monitor.worked(1);
- }
-
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
-
- (new StringLiteralAuditor()).buildResource(res, null);
-
- // Check if the included resource represents a resource-bundle
- if (RBFileUtils.isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- boolean newRB = resources.containsKey(bundleName);
-
- this.addBundleResource(res);
- this.unloadResourceBundle(bundleName);
-// this.loadResourceBundle(bundleName);
-
- if (newRB)
- (new StringLiteralAuditor()).buildProject(null, res.getProject());
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(ResourceBundleChangedEvent.INCLUDED, bundleName,
- res.getProject()));
- }
-
- fireResourceExclusionEvent (new ResourceExclusionEvent(changedResources));
- }
-
- protected void fireResourceExclusionEvent (ResourceExclusionEvent event) {
- for (IResourceExclusionListener listener : exclusionListeners)
- listener.exclusionChanged (event);
- }
-
- public static boolean isResourceExcluded (IResource res) {
- IResource resource = res;
-
- if (!state_loaded)
- loadManagerState();
-
- boolean isExcluded = false;
-
- do {
- if (excludedResources.contains(new ResourceDescriptor(resource))) {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- Set<IResource> resources = allBundles.remove(getResourceBundleName(resource));
- if (resources == null)
- resources = new HashSet<IResource> ();
- resources.add(resource);
- allBundles.put(getResourceBundleName(resource), resources);
- }
-
- isExcluded = true;
- break;
- }
- resource = resource.getParent();
- } while (resource != null &&
- !(resource instanceof IProject ||
- resource instanceof IWorkspaceRoot) &&
- checkResourceExclusionRoot);
-
- return isExcluded; //excludedResources.contains(new ResourceDescriptor(res));
- }
-
- public IFile getRandomFile(String bundleName) {
- try {
- IResource res = (resources.get(bundleName)).iterator().next();
- return res.getProject().getFile(res.getProjectRelativePath());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private static void loadManagerState () {
- excludedResources = new HashSet<IResourceDescriptor>();
- FileReader reader = null;
- try {
- reader = new FileReader (FileUtils.getRBManagerStateFile());
- loadManagerState (XMLMemento.createReadRoot(reader));
- state_loaded = true;
- } catch (Exception e) {
- // do nothing
- }
-
- changelistener = new RBChangeListner();
- ResourcesPlugin.getWorkspace().addResourceChangeListener(changelistener, IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE);
- }
-
- private static void loadManagerState(XMLMemento memento) {
- IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
- for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
- IResourceDescriptor descriptor = new ResourceDescriptor();
- descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
- descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
- descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
- descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
- excludedResources.add(descriptor);
- }
- }
-
- public static void saveManagerState () {
- if (excludedResources == null)
- return;
- XMLMemento memento = XMLMemento.createWriteRoot(TAG_INTERNATIONALIZATION);
- IMemento exclChild = memento.createChild(TAG_EXCLUDED);
-
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor desc = itExcl.next();
- IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
- resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
- resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
- resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
- resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
- }
- FileWriter writer = null;
- try {
- writer = new FileWriter(FileUtils.getRBManagerStateFile());
- memento.save(writer);
- } catch (Exception e) {
- // do nothing
- } finally {
- try {
- if (writer != null)
- writer.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }
-
- @Deprecated
- protected static boolean isResourceExcluded(IProject project, String bname) {
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor rd = itExcl.next();
- if (project.getName().equals(rd.getProjectName()) && bname.equals(rd.getBundleId()))
- return true;
- }
- return false;
- }
-
- public static ResourceBundleManager getManager(String projectName) {
- for (IProject p : getAllSupportedProjects()) {
- if (p.getName().equalsIgnoreCase(projectName)){
- //check if the projectName is a fragment and return the manager for the host
- if(FragmentProjectUtils.isFragment(p))
- return getManager(FragmentProjectUtils.getFragmentHost(p));
- else return getManager(p);
- }
- }
- return null;
- }
-
- public IFile getResourceBundleFile(String resourceBundle, Locale l) {
- IFile res = null;
- Set<IResource> resSet = resources.get(resourceBundle);
-
- if ( resSet != null ) {
- for (IResource resource : resSet) {
- Locale refLoc = getLocaleByName(resourceBundle, resource.getName());
- if (refLoc == null && l == null || (refLoc != null && refLoc.equals(l) || l != null && l.equals(refLoc))) {
- res = resource.getProject().getFile(resource.getProjectRelativePath());
- break;
- }
- }
- }
-
- return res;
- }
-
- public Set<IResource> getAllResourceBundleResources(String resourceBundle) {
- return allBundles.get(resourceBundle);
- }
-
- public void registerResourceExclusionListener (IResourceExclusionListener listener) {
- exclusionListeners.add(listener);
- }
-
- public void unregisterResourceExclusionListener (IResourceExclusionListener listener) {
- exclusionListeners.remove(listener);
- }
-
- public boolean isResourceExclusionListenerRegistered (IResourceExclusionListener listener) {
- return exclusionListeners.contains(listener);
- }
-
- public static void unregisterResourceExclusionListenerFromAllManagers(
- IResourceExclusionListener excludedResource) {
- for (ResourceBundleManager mgr : rbmanager.values()) {
- mgr.unregisterResourceExclusionListener(excludedResource);
- }
- }
-
- public void addResourceBundleEntry(String resourceBundleId, String key,
- Locale locale, String message) throws ResourceBundleException {
-
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance.getMessagesBundleGroup(resourceBundleId);
- IMessage entry = bundleGroup.getMessage(key, locale);
-
-
- if (entry == null) {
- DirtyHack.setFireEnabled(false);
-
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(locale);
- IMessage m = MessagesBundleFactory.createMessage(key, locale);
- m.setText(message);
- messagesBundle.addMessage(m);
-
- instance.writeToFile(messagesBundle);
-
- DirtyHack.setFireEnabled(true);
-
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
- }
- }
-
- public void saveResourceBundle(String resourceBundleId,
- IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
-
-// RBManager.getInstance().
- }
-
- public void removeResourceBundleEntry(String resourceBundleId,
- List<String> keys) throws ResourceBundleException {
-
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup messagesBundleGroup = instance.getMessagesBundleGroup(resourceBundleId);
-
- DirtyHack.setFireEnabled(false);
-
- for (String key : keys) {
- messagesBundleGroup.removeMessages(key);
- }
-
- instance.writeToFile(messagesBundleGroup);
-
- DirtyHack.setFireEnabled(true);
-
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
- }
-
- public boolean isResourceExisting (String bundleId, String key) {
- boolean keyExists = false;
- IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
-
- if (bGroup != null) {
- keyExists = bGroup.isKey(key);
- }
-
- return keyExists;
- }
-
- public static void refreshResource(IResource resource) {
- (new StringLiteralAuditor()).buildProject(null, resource.getProject());
- (new StringLiteralAuditor()).buildResource(resource, null);
- }
-
- public Set<Locale> getProjectProvidedLocales() {
- Set<Locale> locales = new HashSet<Locale>();
-
- for (String bundleId : getResourceBundleNames()) {
- Set<Locale> rb_l = getProvidedLocales(bundleId);
- if (!rb_l.isEmpty()){
- Object[] bundlelocales = rb_l.toArray();
- for (Object l : bundlelocales) {
- /* TODO check if useful to add the default */
- if (!locales.contains(l))
- locales.add((Locale) l);
- }
- }
- }
- return locales;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
deleted file mode 100644
index 0cda211c..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.manager;
-
-import java.util.Collection;
-
-public class ResourceExclusionEvent {
-
- private Collection<Object> changedResources;
-
- public ResourceExclusionEvent(Collection<Object> changedResources) {
- super();
- this.changedResources = changedResources;
- }
-
- public void setChangedResources(Collection<Object> changedResources) {
- this.changedResources = changedResources;
- }
-
- public Collection<Object> getChangedResources() {
- return changedResources;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/CheckItem.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/CheckItem.java
deleted file mode 100644
index 44c2401f..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/CheckItem.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.preferences;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-
-public class CheckItem{
- boolean checked;
- String name;
-
- public CheckItem(String item, boolean checked) {
- this.name = item;
- this.checked = checked;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean getChecked() {
- return checked;
- }
-
- public TableItem toTableItem(Table table){
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(name);
- item.setChecked(checked);
- return item;
- }
-
- public boolean equals(CheckItem item){
- return name.equals(item.getName());
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
deleted file mode 100644
index cd9bc793..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.preferences;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipselabs.tapiji.tools.core.Activator;
-
-public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer {
-
- public TapiJIPreferenceInitializer() {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
-
- //ResourceBundle-Settings
- List<CheckItem> patterns = new LinkedList<CheckItem>();
- patterns.add(new CheckItem("^(.)*/build\\.properties", true));
- patterns.add(new CheckItem("^(.)*/config\\.properties", true));
- patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true));
- prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns));
-
- // Builder
- prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
- prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferences.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferences.java
deleted file mode 100644
index 83f9e2a3..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferences.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.preferences;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.babel.core.configuration.IConfiguration;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipselabs.tapiji.tools.core.Activator;
-
-public class TapiJIPreferences implements IConfiguration {
-
- public static final String AUDIT_SAME_VALUE = "auditSameValue";
- public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue";
- public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage";
- public static final String AUDIT_RB = "auditResourceBundle";
- public static final String AUDIT_RESOURCE = "auditResource";
-
- public static final String NON_RB_PATTERN = "NoRBPattern";
-
- private static final IPreferenceStore PREF = Activator.getDefault().getPreferenceStore();
-
- private static final String DELIMITER = ";";
- private static final String ATTRIBUTE_DELIMITER = ":";
-
- public boolean getAuditSameValue() {
- return PREF.getBoolean(AUDIT_SAME_VALUE);
- }
-
-
- public boolean getAuditMissingValue() {
- return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY);
- }
-
-
- public boolean getAuditMissingLanguage() {
- return PREF.getBoolean(AUDIT_MISSING_LANGUAGE);
- }
-
-
- public boolean getAuditRb() {
- return PREF.getBoolean(AUDIT_RB);
- }
-
-
- public boolean getAuditResource() {
- return PREF.getBoolean(AUDIT_RESOURCE);
- }
-
- public String getNonRbPattern() {
- return PREF.getString(NON_RB_PATTERN);
- }
-
- public static List<CheckItem> getNonRbPatternAsList() {
- return convertStringToList(PREF.getString(NON_RB_PATTERN));
- }
-
- public static List<CheckItem> convertStringToList(String string) {
- StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
- int tokenCount = tokenizer.countTokens();
- List<CheckItem> elements = new LinkedList<CheckItem>();
-
- for (int i = 0; i < tokenCount; i++) {
- StringTokenizer attribute = new StringTokenizer(tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
- String name = attribute.nextToken();
- boolean checked;
- if (attribute.nextToken().equals("true")) checked = true;
- else checked = false;
-
- elements.add(new CheckItem(name, checked));
- }
- return elements;
- }
-
-
- public static String convertListToString(List<CheckItem> patterns) {
- StringBuilder sb = new StringBuilder();
- int tokenCount = 0;
-
- for (CheckItem s : patterns){
- sb.append(s.getName());
- sb.append(ATTRIBUTE_DELIMITER);
- if(s.checked) sb.append("true");
- else sb.append("false");
-
- if (++tokenCount!=patterns.size())
- sb.append(DELIMITER);
- }
- return sb.toString();
- }
-
-
- public static void addPropertyChangeListener(IPropertyChangeListener listener){
- Activator.getDefault().getPreferenceStore().addPropertyChangeListener(listener);
- }
-
-
- public static void removePropertyChangeListener(IPropertyChangeListener listener) {
- Activator.getDefault().getPreferenceStore().removePropertyChangeListener(listener);
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java
deleted file mode 100644
index 1d1dd945..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java
+++ /dev/null
@@ -1,205 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.view;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-public class MessagesViewState {
-
- private static final String TAG_VISIBLE_LOCALES = "visible_locales";
- private static final String TAG_LOCALE = "locale";
- private static final String TAG_LOCALE_LANGUAGE = "language";
- private static final String TAG_LOCALE_COUNTRY = "country";
- private static final String TAG_LOCALE_VARIANT = "variant";
- private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
- private static final String TAG_MATCHING_PRECISION= "matching_precision";
- private static final String TAG_SELECTED_PROJECT = "selected_project";
- private static final String TAG_SELECTED_BUNDLE = "selected_bundle";
- private static final String TAG_ENABLED = "enabled";
- private static final String TAG_VALUE = "value";
- private static final String TAG_SEARCH_STRING = "search_string";
- private static final String TAG_EDITABLE = "editable";
-
- private List<Locale> visibleLocales;
- private SortInfo sortings;
- private boolean fuzzyMatchingEnabled;
- private float matchingPrecision = .75f;
- private String selectedProjectName;
- private String selectedBundleId;
- private String searchString;
- private boolean editable;
-
- public void saveState (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (visibleLocales != null) {
- IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES);
- for (Locale loc : visibleLocales) {
- IMemento memLoc = memVL.createChild(TAG_LOCALE);
- memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage());
- memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry());
- memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant());
- }
- }
-
- if (sortings != null) {
- sortings.saveState(memento);
- }
-
- IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
- memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
-
- IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
- memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
-
- selectedProjectName = selectedProjectName != null ? selectedProjectName : "";
- selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
-
- IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
- memSP.putString(TAG_VALUE, selectedProjectName);
-
- IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
- memSB.putString(TAG_VALUE, selectedBundleId);
-
- IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
- memSStr.putString(TAG_VALUE, searchString);
-
- IMemento memEditable = memento.createChild(TAG_EDITABLE);
- memEditable.putBoolean(TAG_ENABLED, editable);
- } catch (Exception e) {
-
- }
- }
-
- public void init (IMemento memento) {
- if (memento == null)
- return;
-
-
- if (memento.getChild(TAG_VISIBLE_LOCALES) != null) {
- if (visibleLocales == null)
- visibleLocales = new ArrayList<Locale>();
- IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES).getChildren(TAG_LOCALE);
- for (IMemento mLocale : mLocales) {
- if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null && mLocale.getString(TAG_LOCALE_COUNTRY) == null
- && mLocale.getString(TAG_LOCALE_VARIANT) == null) {
- continue;
- }
- Locale newLocale = new Locale (
- mLocale.getString(TAG_LOCALE_LANGUAGE),
- mLocale.getString(TAG_LOCALE_COUNTRY),
- mLocale.getString(TAG_LOCALE_VARIANT));
- if (!this.visibleLocales.contains(newLocale)) {
- visibleLocales.add(newLocale);
- }
- }
- }
-
- if (sortings == null)
- sortings = new SortInfo();
- sortings.init(memento);
-
- IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
- if (mFuzzyMatching != null)
- fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
-
- IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
- if (mMP != null)
- matchingPrecision = mMP.getFloat(TAG_VALUE);
-
- IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT);
- if (mSelProj != null)
- selectedProjectName = mSelProj.getString(TAG_VALUE);
-
- IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE);
- if (mSelBundle != null)
- selectedBundleId = mSelBundle.getString(TAG_VALUE);
-
- IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
- if (mSStr != null)
- searchString = mSStr.getString(TAG_VALUE);
-
- IMemento mEditable = memento.getChild(TAG_EDITABLE);
- if (mEditable != null)
- editable = mEditable.getBoolean(TAG_ENABLED);
- }
-
- public MessagesViewState(List<Locale> visibleLocales,
- SortInfo sortings, boolean fuzzyMatchingEnabled,
- String selectedBundleId) {
- super();
- this.visibleLocales = visibleLocales;
- this.sortings = sortings;
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- this.selectedBundleId = selectedBundleId;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public SortInfo getSortings() {
- return sortings;
- }
-
- public void setSortings(SortInfo sortings) {
- this.sortings = sortings;
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public void setSelectedBundleId(String selectedBundleId) {
- this.selectedBundleId = selectedBundleId;
- }
-
- public void setSelectedProjectName(String selectedProjectName) {
- this.selectedProjectName = selectedProjectName;
- }
-
- public void setSearchString(String searchString) {
- this.searchString = searchString;
- }
-
- public String getSelectedBundleId() {
- return selectedBundleId;
- }
-
- public String getSelectedProjectName() {
- return selectedProjectName;
- }
-
- public String getSearchString() {
- return searchString;
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public void setMatchingPrecision (float value) {
- this.matchingPrecision = value;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java
deleted file mode 100644
index cc521b9f..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.model.view;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-
-public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
- private int colIdx;
- private boolean DESC;
- private List<Locale> visibleLocales;
-
- public void setDESC(boolean dESC) {
- DESC = dESC;
- }
-
- public boolean isDESC() {
- return DESC;
- }
-
- public void setColIdx(int colIdx) {
- this.colIdx = colIdx;
- }
-
- public int getColIdx() {
- return colIdx;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void saveState (IMemento memento) {
- IMemento mCI = memento.createChild(TAG_SORT_INFO);
- mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
- mCI.putBoolean(TAG_ORDER, DESC);
- }
-
- public void init (IMemento memento) {
- IMemento mCI = memento.getChild(TAG_SORT_INFO);
- if (mCI == null)
- return;
- colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
- DESC = mCI.getBoolean(TAG_ORDER);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java
deleted file mode 100644
index 58971785..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java
+++ /dev/null
@@ -1,188 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.text.MessageFormat;
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
-import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-
-public class EditorUtils {
-
- /** Marker constants **/
- public static final String MARKER_ID = Activator.PLUGIN_ID
- + ".StringLiteralAuditMarker";
- public static final String RB_MARKER_ID = Activator.PLUGIN_ID + ".ResourceBundleAuditMarker";
-
- /** Error messages **/
- public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
- public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
- public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
-
- public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
- public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
- public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
-
- /** Editor ids **/
- public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
-
- public static String getFormattedMessage (String pattern, Object[] arguments) {
- String formattedMessage = "";
-
- MessageFormat formatter = new MessageFormat(pattern);
- formattedMessage = formatter.format(arguments);
-
- return formattedMessage;
- }
-
- public static void openEditor (IWorkbenchPage page, IFile file, String editor) {
- // open the default-editor for this file type
- try {
- // TODO open resourcebundleeditor
- IDE.openEditor(page, file, editor);
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
-
- public static void reportToMarker(String string, ILocation problem, int cause, String key, ILocation data, String context) {
- try {
- IMarker marker = problem.getFile().createMarker(MARKER_ID);
- marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.CHAR_START, problem.getStartPos());
- marker.setAttribute(IMarker.CHAR_END, problem.getEndPos());
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
- marker.setAttribute("cause", cause);
- marker.setAttribute("key", key);
- marker.setAttribute("context", context);
- if (data != null) {
- marker.setAttribute("bundleName", data.getLiteral());
- marker.setAttribute("bundleStart", data.getStartPos());
- marker.setAttribute("bundleEnd", data.getEndPos());
- }
-
- // TODO: init attributes
- marker.setAttribute("stringLiteral", string);
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- Logger.logInfo(string);
- }
-
- public static void reportToRBMarker(String string, ILocation problem, int cause, String key, String problemPartnerFile, ILocation data, String context) {
- try {
- if (!problem.getFile().exists()) return;
- IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
- marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); //TODO better-dirty implementation
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
- marker.setAttribute("cause", cause);
- marker.setAttribute("key", key);
- marker.setAttribute("context", context);
- if (data != null) {
- marker.setAttribute("language", data.getLiteral());
- marker.setAttribute("bundleLine", data.getStartPos());
- }
- marker.setAttribute("stringLiteral", string);
- marker.setAttribute("problemPartner", problemPartnerFile);
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- Logger.logInfo(string);
- }
-
- public static boolean deleteAuditMarkersForResource(IResource resource) {
- try {
- if (resource != null && resource.exists()) {
- resource.deleteMarkers(MARKER_ID, false, IResource.DEPTH_INFINITE);
- deleteAllAuditRBMarkersFromRB(resource);
- }
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
- return true;
- }
-
- /*
- * Delete all RB_MARKER from the hole resourcebundle
- */
- private static boolean deleteAllAuditRBMarkersFromRB(IResource resource) throws CoreException{
-// if (resource.findMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE).length > 0)
- if (RBFileUtils.isResourceBundleFile(resource)){
- String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile)resource);
- if (rbId==null) return true; //file in no resourcebundle
-
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(resource.getProject());
- for(IResource r : rbmanager.getResourceBundles(rbId))
- r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
- }
- return true;
- }
-
- public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add){
- IMarker[] old_ms = ms;
- ms = new IMarker[old_ms.length + ms_to_add.length];
-
- System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
- System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
-
- return ms;
- }
-
- public static void updateMarker(IMarker marker) {
- FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
-
- AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel)
- getAnnotationModel(marker);
- IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
-
- try {
- model.updateMarker(doc, marker, getCurPosition(marker, model));
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public static IAnnotationModel getAnnotationModel(IMarker marker) {
- FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
-
- return JavaUI.getDocumentProvider().getAnnotationModel(input);
- }
-
- private static Position getCurPosition(IMarker marker, IAnnotationModel model) {
- Iterator iter = model.getAnnotationIterator();
- Logger.logInfo("Updates Position!");
- while (iter.hasNext()) {
- Object curr = iter.next();
- if (curr instanceof SimpleMarkerAnnotation) {
- SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
- if (marker.equals(annot.getMarker())) {
- return model.getPosition(annot);
- }
- }
- }
- return null;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java
deleted file mode 100644
index ea1402cb..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileReader;
-
-import org.eclipse.core.internal.resources.ResourceException;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.Logger;
-
-
-public class FileUtils {
-
- public static String readFile (IResource resource) {
- return readFileAsString(resource.getRawLocation().toFile());
- }
-
- protected static String readFileAsString(File filePath) {
- String content = "";
-
- if (!filePath.exists()) return content;
- try {
- BufferedReader fileReader = new BufferedReader(new FileReader(filePath));
- String line = "";
-
- while ((line = fileReader.readLine()) != null) {
- content += line + "\n";
- }
-
- // close filereader
- fileReader.close();
- } catch (Exception e) {
- // TODO log error output
- Logger.logError(e);
- }
-
- return content;
- }
-
- public static File getRBManagerStateFile() {
- return Activator.getDefault().getStateLocation().append("internationalization.xml").toFile();
- }
-
- /**
- * Don't use that -> causes {@link ResourceException} -> because File out of sync
- * @param file
- * @param editorContent
- * @throws CoreException
- * @throws OperationCanceledException
- */
- public synchronized void saveTextFile(IFile file, String editorContent)
- throws CoreException, OperationCanceledException {
- try {
- file.setContents(new ByteArrayInputStream(editorContent.getBytes()),
- false, true, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java
deleted file mode 100644
index 5dc4382a..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.tools.core.Activator;
-
-
-public class FontUtils {
-
- /**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
-
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FragmentProjectUtils.java
deleted file mode 100644
index abfbbfab..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FragmentProjectUtils.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.util.List;
-
-import org.eclipse.babel.core.util.PDEUtils;
-import org.eclipse.core.resources.IProject;
-
-public class FragmentProjectUtils{
-
- public static String getPluginId(IProject project){
- return PDEUtils.getPluginId(project);
- }
-
-
- public static IProject[] lookupFragment(IProject pluginProject){
- return PDEUtils.lookupFragment(pluginProject);
- }
-
- public static boolean isFragment(IProject pluginProject){
- return PDEUtils.isFragment(pluginProject);
- }
-
- public static List<IProject> getFragments(IProject hostProject){
- return PDEUtils.getFragments(hostProject);
- }
-
- public static String getFragmentId(IProject project, String hostPluginId){
- return PDEUtils.getFragmentId(project, hostPluginId);
- }
-
- public static IProject getFragmentHost(IProject fragment){
- return PDEUtils.getFragmentHost(fragment);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java
deleted file mode 100644
index 30437257..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.tools.core.Activator;
-
-
-
-/**
- * Utility methods related to application UI.
- * @author Pascal Essiembre ([email protected])
- * @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $
- */
-public final class ImageUtils {
-
- /** Name of resource bundle image. */
- public static final String IMAGE_RESOURCE_BUNDLE =
- "icons/resourcebundle.gif"; //$NON-NLS-1$
- /** Name of properties file image. */
- public static final String IMAGE_PROPERTIES_FILE =
- "icons/propertiesfile.gif"; //$NON-NLS-1$
- /** Name of properties file entry image */
- public static final String IMAGE_PROPERTIES_FILE_ENTRY =
- "icons/key.gif";
- /** Name of new properties file image. */
- public static final String IMAGE_NEW_PROPERTIES_FILE =
- "icons/newpropertiesfile.gif"; //$NON-NLS-1$
- /** Name of hierarchical layout image. */
- public static final String IMAGE_LAYOUT_HIERARCHICAL =
- "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
- /** Name of flat layout image. */
- public static final String IMAGE_LAYOUT_FLAT =
- "icons/flatLayout.gif"; //$NON-NLS-1$
- public static final String IMAGE_INCOMPLETE_ENTRIES =
- "icons/incomplete.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_ON =
- "icons/int.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_OFF =
- "icons/exclude.png"; //$NON-NLS-1$
- public static final String ICON_RESOURCE =
- "icons/Resource16_small.png";
- public static final String ICON_RESOURCE_INCOMPLETE =
- "icons/Resource16_warning_small.png";
-
- /** Image registry. */
- private static final ImageRegistry imageRegistry = new ImageRegistry();
-
- /**
- * Constructor.
- */
- private ImageUtils() {
- super();
- }
-
- /**
- * Gets an image.
- * @param imageName image name
- * @return image
- */
- public static Image getImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LanguageUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LanguageUtils.java
deleted file mode 100644
index a4903798..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LanguageUtils.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringBufferInputStream;
-import java.util.Locale;
-
-import org.eclipse.babel.editor.api.PropertiesGenerator;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-
-public class LanguageUtils {
- private static final String INITIALISATION_STRING = PropertiesGenerator.GENERATED_BY;
-
-
- private static IFile createFile(IContainer container, String fileName, IProgressMonitor monitor) throws CoreException, IOException {
- if (!container.exists()){
- if (container instanceof IFolder){
- ((IFolder) container).create(false, false, monitor);
- }
- }
-
- IFile file = container.getFile(new Path(fileName));
- if (!file.exists()){
- InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
- file.create(s, true, monitor);
- s.close();
- }
-
- return file;
- }
-
- /**
- * Checks if ResourceBundle provides a given locale. If the locale is not
- * provided, creates a new properties-file with the ResourceBundle-basename
- * and the index of the given locale.
- * @param project
- * @param rbId
- * @param locale
- */
- public static void addLanguageToResourceBundle(IProject project, final String rbId, final Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- if (rbManager.getProvidedLocales(rbId).contains(locale)) return;
-
- final IResource file = rbManager.getRandomFile(rbId);
- final IContainer c = ResourceUtils.getCorrespondingFolders(file.getParent(), project);
-
- new Job("create new propertfile") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- String newFilename = ResourceBundleManager.getResourceBundleName(file);
- if (locale.getLanguage() != null && !locale.getLanguage().equalsIgnoreCase(ResourceBundleManager.defaultLocaleTag)
- && !locale.getLanguage().equals(""))
- newFilename += "_"+locale.getLanguage();
- if (locale.getCountry() != null && !locale.getCountry().equals(""))
- newFilename += "_"+locale.getCountry();
- if (locale.getVariant() != null && !locale.getCountry().equals(""))
- newFilename += "_"+locale.getVariant();
- newFilename += ".properties";
-
- createFile(c, newFilename, monitor);
- } catch (CoreException e) {
- Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
- } catch (IOException e) {
- Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
- }
- monitor.done();
- return Status.OK_STATUS;
- }
- }.schedule();
- }
-
-
- /**
- * Adds new properties-files for a given locale to all ResourceBundles of a project.
- * If a ResourceBundle already contains the language, happens nothing.
- * @param project
- * @param locale
- */
- public static void addLanguageToProject(IProject project, Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- //Audit if all resourecbundles provide this locale. if not - add new file
- for (String rbId : rbManager.getResourceBundleIdentifiers()){
- addLanguageToResourceBundle(project, rbId, locale);
- }
- }
-
-
- private static void deleteFile(IFile file, boolean force, IProgressMonitor monitor) throws CoreException{
- EditorUtils.deleteAuditMarkersForResource(file);
- file.delete(force, monitor);
- }
-
- /**
- * Removes the properties-file of a given locale from a ResourceBundle, if
- * the ResourceBundle provides the locale.
- * @param project
- * @param rbId
- * @param locale
- */
- public static void removeFileFromResourceBundle(IProject project, String rbId, Locale locale) {
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- if (!rbManager.getProvidedLocales(rbId).contains(locale)) return;
-
- final IFile file = rbManager.getResourceBundleFile(rbId, locale);
- final String filename = file.getName();
-
- new Job("remove properties-file") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- deleteFile(file, true, monitor);
- } catch (CoreException e) {
-// MessageDialog.openError(Display.getCurrent().getActiveShell(), "Confirm", "File could not be deleted");
- Logger.logError("File could not be deleted",e);
- }
- return Status.OK_STATUS;
- }
- }.schedule();
- }
-
- /**
- * Removes all properties-files of a given locale from all ResourceBundles of a project.
- * @param rbManager
- * @param locale
- * @return
- */
- public static void removeLanguageFromProject(IProject project, Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- for (String rbId : rbManager.getResourceBundleIdentifiers()){
- removeFileFromResourceBundle(project, rbId, locale);
- }
-
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java
deleted file mode 100644
index aef60c50..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-public class LocaleUtils {
-
- public static Locale getLocaleByDisplayName (Set<Locale> locales, String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
- return l;
- }
- }
-
- return null;
- }
-
- public static boolean containsLocaleByDisplayName(Set<Locale> locales, String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
- return true;
- }
- }
-
- return false;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java
deleted file mode 100644
index c33682ed..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-
-public class OverlayIcon extends CompositeImageDescriptor {
-
- public static final int TOP_LEFT = 0;
- public static final int TOP_RIGHT = 1;
- public static final int BOTTOM_LEFT = 2;
- public static final int BOTTOM_RIGHT = 3;
-
- private Image img;
- private Image overlay;
- private int location;
- private Point imgSize;
-
- public OverlayIcon(Image baseImage, Image overlayImage, int location) {
- super();
- this.img = baseImage;
- this.overlay = overlayImage;
- this.location = location;
- this.imgSize = new Point(baseImage.getImageData().width, baseImage.getImageData().height);
- }
-
- @Override
- protected void drawCompositeImage(int width, int height) {
- drawImage(img.getImageData(), 0, 0);
- ImageData imageData = overlay.getImageData();
-
- switch (location) {
- case TOP_LEFT:
- drawImage(imageData, 0, 0);
- break;
- case TOP_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, 0);
- break;
- case BOTTOM_LEFT:
- drawImage(imageData, 0, imgSize.y - imageData.height);
- break;
- case BOTTOM_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, imgSize.y
- - imageData.height);
- break;
- }
- }
-
- @Override
- protected Point getSize() {
- return new Point(img.getImageData().width, img.getImageData().height);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/PDEUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/PDEUtils.java
deleted file mode 100644
index 4f9efbb7..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/PDEUtils.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * 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.eclipselabs.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.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/RBFileUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/RBFileUtils.java
deleted file mode 100644
index 1f3ada25..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/RBFileUtils.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipselabs.tapiji.tools.core.Activator;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.model.preferences.CheckItem;
-import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences;
-
-
-/**
- *
- * @author mgasser
- *
- */
-public class RBFileUtils extends Action{
- public static final String PROPERTIES_EXT = "properties";
-
-
- /**
- * Returns true if a file is a ResourceBundle-file
- */
- public static boolean isResourceBundleFile(IResource file) {
- boolean isValied = false;
-
- if (file != null && file instanceof IFile && !file.isDerived() &&
- file.getFileExtension()!=null && file.getFileExtension().equalsIgnoreCase("properties")){
- isValied = true;
-
- //Check if file is not in the blacklist
- IPreferenceStore pref = null;
- if (Activator.getDefault() != null)
- pref = Activator.getDefault().getPreferenceStore();
-
- if (pref != null){
- List<CheckItem> list = TapiJIPreferences.getNonRbPatternAsList();
- for (CheckItem item : list){
- if (item.getChecked() && file.getFullPath().toString().matches(item.getName())){
- isValied = false;
-
- //if properties-file is not RB-file and has ResouceBundleMarker, deletes all ResouceBundleMarker of the file
- if (hasResourceBundleMarker(file))
- try {
- file.deleteMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- }
- }
- }
- }
- }
-
- return isValied;
- }
-
- /**
- * Checks whether a RB-file has a problem-marker
- */
- public static boolean hasResourceBundleMarker(IResource r){
- try {
- if(r.findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
- return true;
- else return false;
- } catch (CoreException e) {
- return false;
- }
- }
-
-
- /**
- * @return the locale of a given properties-file
- */
- public static Locale getLocale(IFile file){
- String localeID = file.getName();
- localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
- String baseBundleName = ResourceBundleManager.getResourceBundleName(file);
-
- Locale locale;
- if (localeID.length() == baseBundleName.length()) {
- locale = null; //Default locale
- } else {
- localeID = localeID.substring(baseBundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
- break;
- default:
- locale = new Locale("");
- break;
- }
- }
- return locale;
- }
-
- /**
- * @return number of ResourceBundles in the subtree
- */
- public static int countRecursiveResourceBundle(IContainer container) {
- return getSubResourceBundle(container).size();
- }
-
-
- private static List<String> getSubResourceBundle(IContainer container){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(container.getProject());
-
- String conatinerId = container.getFullPath().toString();
- List<String> subResourceBundles = new ArrayList<String>();
-
- for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
- for(IResource r : rbmanager.getResourceBundles(rbId)){
- if (r.getFullPath().toString().contains(conatinerId) && (!subResourceBundles.contains(rbId))){
- subResourceBundles.add(rbId);
- }
- }
- }
- return subResourceBundles;
- }
-
- /**
- * @param container
- * @return Set with all ResourceBundles in this container
- */
- public static Set<String> getResourceBundleIds (IContainer container) {
- Set<String> resourcebundles = new HashSet<String>();
-
- try {
- for(IResource r : container.members()){
- if (r instanceof IFile) {
- String resourcebundle = getCorrespondingResourceBundleId((IFile)r);
- if (resourcebundle != null) resourcebundles.add(resourcebundle);
- }
- }
- } catch (CoreException e) {/*resourcebundle.size()==0*/}
-
- return resourcebundles;
- }
-
- /**
- *
- * @param file
- * @return ResourceBundle-name or null if no ResourceBundle contains the file
- */
- //TODO integrate in ResourceBundleManager
- public static String getCorrespondingResourceBundleId (IFile file) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file.getProject());
- String possibleRBId = null;
-
- if (isResourceBundleFile((IFile) file)) {
- possibleRBId = ResourceBundleManager.getResourceBundleId(file);
-
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- if ( possibleRBId.equals(rbId) )
- return possibleRBId;
- }
- }
- return null;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java
deleted file mode 100644
index d55d7e34..00000000
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java
+++ /dev/null
@@ -1,98 +0,0 @@
-package org.eclipselabs.tapiji.tools.core.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-
-public class ResourceUtils {
-
- private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*";
- private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
-
- public static boolean isValidResourceKey (String key) {
- boolean isValid = false;
-
- if (key != null && key.trim().length() > 0) {
- isValid = key.matches(REGEXP_RESOURCE_KEY);
- }
-
- return isValid;
- }
-
- public static String deriveNonExistingRBName (String nameProposal, ResourceBundleManager manager) {
- // Adapt the proposal to the requirements for Resource-Bundle names
- nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME, "");
-
- int i = 0;
- do {
- if (manager.getResourceBundleIdentifiers().contains(nameProposal) || nameProposal.length() == 0) {
- nameProposal = nameProposal + (++i);
- } else
- break;
- } while (true);
-
- return nameProposal;
- }
-
- public static boolean isJavaCompUnit (IResource res) {
- boolean result = false;
-
- if (res.getType() == IResource.FILE && !res.isDerived() &&
- res.getFileExtension().equalsIgnoreCase("java")) {
- result = true;
- }
-
- return result;
- }
-
- public static boolean isJSPResource(IResource res) {
- boolean result = false;
-
- if (res.getType() == IResource.FILE && !res.isDerived() &&
- (res.getFileExtension().equalsIgnoreCase("jsp") ||
- res.getFileExtension().equalsIgnoreCase("xhtml"))) {
- result = true;
- }
-
- return result;
- }
-
- /**
- *
- * @param baseFolder
- * @param targetProjects Projects with a same structure
- * @return List of
- */
- public static List<IContainer> getCorrespondingFolders(IContainer baseFolder, List<IProject> targetProjects){
- List<IContainer> correspondingFolder = new ArrayList<IContainer>();
-
- for(IProject p : targetProjects){
- IContainer c = getCorrespondingFolders(baseFolder, p);
- if (c.exists()) correspondingFolder.add(c);
- }
-
- return correspondingFolder;
- }
-
- /**
- *
- * @param baseFolder
- * @param targetProject
- * @return a Container with the corresponding path as the baseFolder. The Container doesn't must exist.
- */
- public static IContainer getCorrespondingFolders(IContainer baseFolder, IProject targetProject) {
- IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(baseFolder.getProject().getFullPath());
-
- if (!relativ_folder.isEmpty())
- return targetProject.getFolder(relativ_folder);
- else
- return targetProject;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/.project b/org.eclipselabs.tapiji.tools.java/.project
deleted file mode 100644
index fe4d5b8a..00000000
--- a/org.eclipselabs.tapiji.tools.java/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.tools.java</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF
deleted file mode 100644
index 77d8cc50..00000000
--- a/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,32 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: JavaBuilderExtension
-Bundle-SymbolicName: org.eclipselabs.tapiji.tools.java;singleton:=true
-Bundle-Version: 0.0.2.qualifier
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Require-Bundle: org.eclipse.core.resources;bundle-version="3.6.0",
- org.eclipse.jdt.core;bundle-version="3.6.0",
- org.eclipse.core.runtime;bundle-version="3.6.0",
- org.eclipse.jdt.ui;bundle-version="3.6.0",
- org.eclipse.jface,
- org.eclipselabs.tapiji.tools.core;bundle-version="0.0.2",
- org.eclipselabs.tapiji.tools.core.ui;bundle-version="1.0.0"
-Import-Package: org.eclipse.core.filebuffers,
- org.eclipse.jface.dialogs,
- org.eclipse.jface.text,
- org.eclipse.jface.text.contentassist,
- org.eclipse.jface.text.source,
- org.eclipse.jface.wizard,
- org.eclipse.swt.graphics,
- org.eclipse.swt.widgets,
- org.eclipse.text.edits,
- org.eclipse.ui,
- org.eclipse.ui.part,
- org.eclipse.ui.progress,
- org.eclipse.ui.texteditor,
- org.eclipse.ui.wizards,
- org.eclipselabs.tapiji.translator.rbe.babel.bundle,
- org.eclipselabs.tapiji.translator.rbe.ui.wizards
-Bundle-Vendor: Vienna University of Technology
-
-
diff --git a/org.eclipselabs.tapiji.tools.java/plugin.xml b/org.eclipselabs.tapiji.tools.java/plugin.xml
deleted file mode 100644
index 33585177..00000000
--- a/org.eclipselabs.tapiji.tools.java/plugin.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipselabs.tapiji.tools.core.builderExtension">
- <i18nResourceAuditor
- class="auditor.JavaResourceAuditor">
- </i18nResourceAuditor>
- </extension>
- <extension
- point="org.eclipse.jdt.ui.javaEditorTextHovers">
- <hover
- activate="true"
- class="ui.ConstantStringHover"
- description="hovers constant strings"
- id="org.eclipselabs.tapiji.tools.java.ui.ConstantStringHover"
- label="Constant Strings">
- </hover>
- </extension>
- <extension
- id="org.eclipselabs.tapiji.tools.java.ui.MessageCompletionProcessor"
- name="org.eclipselabs.tapiji.tools.java.ui.MessageCompletionProcessor"
- point="org.eclipse.jdt.ui.javaCompletionProposalComputer">
- <javaCompletionProposalComputer
- activate="true"
- categoryId="org.eclipse.jdt.ui.defaultProposalCategory"
- class="ui.MessageCompletionProposalComputer">
- <partition
- type="__java_string">
- </partition>
- <partition
- type="__dftl_partition_content_type">
- </partition>
- </javaCompletionProposalComputer>
-
- </extension>
-</plugin>
diff --git a/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java b/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java
deleted file mode 100644
index d0b4c06b..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package auditor;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipselabs.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
-import org.eclipselabs.tapiji.tools.core.builder.quickfix.IncludeResource;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
-
-import quickfix.ExcludeResourceFromInternationalization;
-import quickfix.ExportToResourceBundleResolution;
-import quickfix.IgnoreStringFromInternationalization;
-import quickfix.ReplaceResourceBundleDefReference;
-import quickfix.ReplaceResourceBundleReference;
-import auditor.model.SLLocation;
-
-public class JavaResourceAuditor extends I18nResourceAuditor {
-
- protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>();
- protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>();
- protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>();
-
- @Override
- public String[] getFileEndings() {
- return new String[] { "java" };
- }
-
- @Override
- public void audit(IResource resource) {
- IJavaElement javaElement = JavaCore.create(resource);
- if (javaElement == null)
- return;
-
- if (!(javaElement instanceof ICompilationUnit))
- return;
-
- ICompilationUnit icu = (ICompilationUnit) javaElement;
- ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
- .getProject().getFile(resource.getProjectRelativePath()),
- ResourceBundleManager.getManager(resource.getProject()));
-
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = icu;
-
- if (typeRoot == null)
- return;
-
- // get a reference to the shared AST of the loaded CompilationUnit
- CompilationUnit cu = SharedASTProvider.getAST(typeRoot,
- // do not wait for AST creation
- SharedASTProvider.WAIT_YES, null);
- if (cu == null) {
- System.out.println("Cannot audit resource: "
- + resource.getFullPath());
- return;
- }
- cu.accept(csav);
-
- // Report all constant string literals
- constantLiterals = csav.getConstantStringLiterals();
-
- // Report all broken Resource-Bundle references
- brokenResourceReferences = csav.getBrokenResourceReferences();
-
- // Report all broken definitions to Resource-Bundle references
- brokenBundleReferences = csav.getBrokenRBReferences();
- }
-
- @Override
- public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>(constantLiterals);
- }
-
- @Override
- public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>(brokenResourceReferences);
- }
-
- @Override
- public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>(brokenBundleReferences);
- }
-
- @Override
- public String getContextId() {
- return "java";
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- int cause = marker.getAttribute("cause", -1);
-
- switch (marker.getAttribute("cause", -1)) {
- case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
- resolutions.add(new IgnoreStringFromInternationalization());
- resolutions.add(new ExcludeResourceFromInternationalization());
- resolutions.add(new ExportToResourceBundleResolution());
- break;
- case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
- String dataName = marker.getAttribute("bundleName", "");
- int dataStart = marker.getAttribute("bundleStart", 0);
- int dataEnd = marker.getAttribute("bundleEnd", 0);
-
- IProject project = marker.getResource().getProject();
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(project);
-
- if (manager.getResourceBundle(dataName) != null) {
- String key = marker.getAttribute("key", "");
-
- resolutions.add(new CreateResourceBundleEntry(key, manager,
- dataName));
- resolutions.add(new ReplaceResourceBundleReference(key,
- dataName));
- resolutions.add(new ReplaceResourceBundleDefReference(dataName,
- dataStart, dataEnd));
- } else {
- String bname = dataName;
-
- Set<IResource> bundleResources = ResourceBundleManager
- .getManager(marker.getResource().getProject())
- .getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions
- .add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(bname, marker
- .getResource(), dataStart, dataEnd));
- resolutions.add(new ReplaceResourceBundleDefReference(bname,
- dataStart, dataEnd));
- }
-
- break;
- case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
- String bname = marker.getAttribute("key", "");
-
- Set<IResource> bundleResources = ResourceBundleManager.getManager(
- marker.getResource().getProject())
- .getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions.add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(marker.getAttribute(
- "key", ""), marker.getResource(), marker.getAttribute(
- IMarker.CHAR_START, 0), marker.getAttribute(
- IMarker.CHAR_END, 0)));
- resolutions.add(new ReplaceResourceBundleDefReference(marker
- .getAttribute("key", ""), marker.getAttribute(
- IMarker.CHAR_START, 0), marker.getAttribute(
- IMarker.CHAR_END, 0)));
- }
-
- return resolutions;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/auditor/MethodParameterDescriptor.java b/org.eclipselabs.tapiji.tools.java/src/auditor/MethodParameterDescriptor.java
deleted file mode 100644
index 93098766..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/auditor/MethodParameterDescriptor.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package auditor;
-
-import java.util.List;
-
-public class MethodParameterDescriptor {
-
- private List<String> methodName;
- private String declaringClass;
- private boolean considerSuperclass;
- private int position;
-
- public MethodParameterDescriptor(List<String> methodName, String declaringClass,
- boolean considerSuperclass, int position) {
- super();
- this.setMethodName(methodName);
- this.declaringClass = declaringClass;
- this.considerSuperclass = considerSuperclass;
- this.position = position;
- }
-
- public String getDeclaringClass() {
- return declaringClass;
- }
- public void setDeclaringClass(String declaringClass) {
- this.declaringClass = declaringClass;
- }
- public boolean isConsiderSuperclass() {
- return considerSuperclass;
- }
- public void setConsiderSuperclass(boolean considerSuperclass) {
- this.considerSuperclass = considerSuperclass;
- }
- public int getPosition() {
- return position;
- }
- public void setPosition(int position) {
- this.position = position;
- }
-
- public void setMethodName(List<String> methodName) {
- this.methodName = methodName;
- }
-
- public List<String> getMethodName() {
- return methodName;
- }
-
-
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java b/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java
deleted file mode 100644
index 95364f32..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java
+++ /dev/null
@@ -1,237 +0,0 @@
-package auditor;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.FieldDeclaration;
-import org.eclipse.jdt.core.dom.IVariableBinding;
-import org.eclipse.jdt.core.dom.MethodInvocation;
-import org.eclipse.jdt.core.dom.StringLiteral;
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-import util.ASTutils;
-import auditor.model.SLLocation;
-
-/**
- * @author Martin
- *
- */
-public class ResourceAuditVisitor extends ASTVisitor implements
- IResourceVisitor {
-
- private List<SLLocation> constants;
- private List<SLLocation> brokenStrings;
- private List<SLLocation> brokenRBReferences;
- private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>();
- private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>();
- private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>();
- private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>();
- private IFile file;
- private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>();
- private ResourceBundleManager manager;
-
- public ResourceAuditVisitor(IFile file, ResourceBundleManager manager) {
- constants = new ArrayList<SLLocation>();
- brokenStrings = new ArrayList<SLLocation>();
- brokenRBReferences = new ArrayList<SLLocation>();
- this.file = file;
- this.manager = manager;
- }
-
- public boolean visit(VariableDeclarationStatement varDeclaration) {
- for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration
- .fragments().iterator(); itFrag.hasNext();) {
- VariableDeclarationFragment fragment = itFrag.next();
- parseVariableDeclarationFragment(fragment);
- }
- return true;
- }
-
- public boolean visit(FieldDeclaration fieldDeclaration) {
- for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration
- .fragments().iterator(); itFrag.hasNext();) {
- VariableDeclarationFragment fragment = itFrag.next();
- parseVariableDeclarationFragment(fragment);
- }
- return true;
- }
-
- protected void parseVariableDeclarationFragment(
- VariableDeclarationFragment fragment) {
- IVariableBinding vBinding = fragment.resolveBinding();
- this.variableBindingManagers.put(vBinding, fragment);
- }
-
- public boolean visit(StringLiteral stringLiteral) {
- try {
- if (stringLiteral.getLiteralValue().trim().length() == 0)
- return true;
-
- ASTNode parent = stringLiteral.getParent();
-
- if (parent instanceof MethodInvocation) {
- MethodInvocation methodInvocation = (MethodInvocation) parent;
-
- IRegion region = new Region(stringLiteral.getStartPosition(),
- stringLiteral.getLength());
-
- // Check if this method invokes the getString-Method on a
- // ResourceBundle Implementation
- if (ASTutils.isMatchingMethodParamDesc(methodInvocation, stringLiteral,
- ASTutils.getRBAccessorDesc())) {
- // Check if the given Resource-Bundle reference is broken
- SLLocation rbName = ASTutils.resolveResourceBundleLocation(methodInvocation,
- ASTutils.getRBDefinitionDesc(), variableBindingManagers);
- if (rbName == null
- || manager.isKeyBroken(rbName.getLiteral(), stringLiteral
- .getLiteralValue())) {
- // report new problem
- SLLocation desc = new SLLocation(file, stringLiteral
- .getStartPosition(), stringLiteral
- .getStartPosition()
- + stringLiteral.getLength(), stringLiteral
- .getLiteralValue());
- desc.setData(rbName);
- brokenStrings.add(desc);
- }
-
- // store position of resource-bundle access
- keyPositions.put(Long.valueOf(stringLiteral
- .getStartPosition()), region);
- bundleKeys.put(region, stringLiteral.getLiteralValue());
- bundleReferences.put(region, rbName.getLiteral());
- return false;
- } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
- stringLiteral, ASTutils.getRBDefinitionDesc())) {
- rbDefReferences.put(Long.valueOf(stringLiteral
- .getStartPosition()), region);
- boolean referenceBroken = true;
- for (String bundle : manager.getResourceBundleIdentifiers()) {
- if (bundle.trim().equals(stringLiteral.getLiteralValue())) {
- referenceBroken = false;
- }
- }
- if (referenceBroken) {
- this.brokenRBReferences.add(new SLLocation(file, stringLiteral
- .getStartPosition(), stringLiteral
- .getStartPosition()
- + stringLiteral.getLength(), stringLiteral
- .getLiteralValue()));
- }
-
- return false;
- }
- }
-
- // check if string is followed by a "$NON-NLS$" line comment
- if (ASTutils.existsNonInternationalisationComment(stringLiteral)) {
- return false;
- }
-
- // constant string literal found
- constants.add(new SLLocation(file,
- stringLiteral.getStartPosition(), stringLiteral
- .getStartPosition()
- + stringLiteral.getLength(), stringLiteral.getLiteralValue()));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
-
- public List<SLLocation> getConstantStringLiterals() {
- return constants;
- }
-
- public List<SLLocation> getBrokenResourceReferences() {
- return brokenStrings;
- }
-
- public List<SLLocation> getBrokenRBReferences() {
- return this.brokenRBReferences;
- }
-
- public IRegion getKeyAt(Long position) {
- IRegion reg = null;
-
- Iterator<Long> keys = keyPositions.keySet().iterator();
- while (keys.hasNext()) {
- Long startPos = keys.next();
- if (startPos > position)
- break;
-
- IRegion region = keyPositions.get(startPos);
- if (region.getOffset() <= position
- && (region.getOffset() + region.getLength()) >= position) {
- reg = region;
- break;
- }
- }
-
- return reg;
- }
-
- public String getKeyAt(IRegion region) {
- if (bundleKeys.containsKey(region))
- return bundleKeys.get(region);
- else
- return "";
- }
-
- public String getBundleReference(IRegion region) {
- return bundleReferences.get(region);
- }
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- // TODO Auto-generated method stub
- return false;
- }
-
- public Collection<String> getDefinedResourceBundles(int offset) {
- Collection<String> result = new HashSet<String>();
- for (String s : bundleReferences.values()) {
- if (s != null)
- result.add(s);
- }
- return result;
- }
-
- public IRegion getRBReferenceAt(Long offset) {
- IRegion reg = null;
-
- Iterator<Long> keys = rbDefReferences.keySet().iterator();
- while (keys.hasNext()) {
- Long startPos = keys.next();
- if (startPos > offset)
- break;
-
- IRegion region = rbDefReferences.get(startPos);
- if (region != null &&
- region.getOffset() <= offset
- && (region.getOffset() + region.getLength()) >= offset) {
- reg = region;
- break;
- }
- }
-
- return reg;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/auditor/model/SLLocation.java b/org.eclipselabs.tapiji.tools.java/src/auditor/model/SLLocation.java
deleted file mode 100644
index 3bfd8d28..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/auditor/model/SLLocation.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package auditor.model;
-
-import java.io.Serializable;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-
-
-public class SLLocation implements Serializable, ILocation {
-
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
-
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
- public IFile getFile() {
- return file;
- }
- public void setFile(IFile file) {
- this.file = file;
- }
- public int getStartPos() {
- return startPos;
- }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
- public int getEndPos() {
- return endPos;
- }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
- public String getLiteral() {
- return literal;
- }
- public Serializable getData () {
- return data;
- }
- public void setData (Serializable data) {
- this.data = data;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipselabs.tapiji.tools.java/src/quickfix/ExcludeResourceFromInternationalization.java
deleted file mode 100644
index 2552412c..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/quickfix/ExcludeResourceFromInternationalization.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package quickfix;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-public class ExcludeResourceFromInternationalization implements IMarkerResolution2 {
-
- @Override
- public String getLabel() {
- return "Exclude Resource";
- }
-
- @Override
- public void run(IMarker marker) {
- final IResource resource = marker.getResource();
-
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
-
- ResourceBundleManager manager = null;
- pm.beginTask("Excluding Resource from Internationalization", 1);
-
- if (manager == null || (manager.getProject() != resource.getProject()))
- manager = ResourceBundleManager.getManager(resource.getProject());
- manager.excludeResource(resource, pm);
- pm.worked(1);
- pm.done();
- }
- });
- } catch (Exception e) {}
- }
-
- @Override
- public String getDescription() {
- return "Exclude Resource from Internationalization";
- }
-
- @Override
- public Image getImage() {
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.java/src/quickfix/ExportToResourceBundleResolution.java
deleted file mode 100644
index 56556962..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/quickfix/ExportToResourceBundleResolution.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-
-import util.ASTutils;
-
-public class ExportToResourceBundleResolution implements IMarkerResolution2 {
-
- public ExportToResourceBundleResolution () {}
-
- @Override
- public String getDescription() {
- return "Export constant string literal to a resource bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Export to Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell(),
- ResourceBundleManager.getManager(resource.getProject()),
- "",
- (startPos+1 < document.getLength() && endPos > 1) ? document.get(startPos+1, endPos-2) : "",
- "",
- "");
- if (dialog.open() != InputDialog.OK)
- return;
-
- ASTutils.insertNewBundleRef(document,
- resource,
- startPos,
- endPos,
- dialog.getSelectedResourceBundle(),
- dialog.getSelectedKey());
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
-
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/quickfix/IgnoreStringFromInternationalization.java b/org.eclipselabs.tapiji.tools.java/src/quickfix/IgnoreStringFromInternationalization.java
deleted file mode 100644
index de36b5d1..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/quickfix/IgnoreStringFromInternationalization.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.Logger;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-import util.ASTutils;
-
-public class IgnoreStringFromInternationalization implements IMarkerResolution2 {
-
- @Override
- public String getLabel() {
- return "Ignore String";
- }
-
- @Override
- public void run(IMarker marker) {
- IResource resource = marker.getResource();
- ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
-
- IJavaElement je = JavaCore.create(resource, JavaCore.create(resource.getProject()));
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = ((ICompilationUnit) je);
- // 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);
-
- /*ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
-
- IDocument doc = null;*/
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
-
-
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
-
- int position = marker.getAttribute(IMarker.CHAR_START, 0);
-
- ASTutils.createReplaceNonInternationalisationComment(cu, document, position);
- textFileBuffer.commit(null, false);
-
- } catch (JavaModelException e) {
- Logger.logError(e);
- } catch (CoreException e) {
- Logger.logError(e);
- }
-
-
- }
-
- @Override
- public String getDescription() {
- return "Ignore String from Internationalization";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipselabs.tapiji.tools.java/src/quickfix/ReplaceResourceBundleDefReference.java
deleted file mode 100644
index 1e991274..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/quickfix/ReplaceResourceBundleDefReference.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
-
-
-public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
-
- private String key;
- private int start;
- private int end;
-
- public ReplaceResourceBundleDefReference(String key, int start, int end) {
- this.key = key;
- this.start = start;
- this.end = end;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle reference '"
- + key
- + "' with a reference to an already existing Resource-Bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select an alternative Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = start;
- int endPos = end-start;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
- resource.getProject());
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- key = dialog.getSelectedBundleId();
-
- document.replace(startPos, endPos, "\"" + key + "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/quickfix/ReplaceResourceBundleReference.java b/org.eclipselabs.tapiji.tools.java/src/quickfix/ReplaceResourceBundleReference.java
deleted file mode 100644
index 7dbcb311..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/quickfix/ReplaceResourceBundleReference.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package quickfix;
-
-import java.util.Locale;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
-
-
-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, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell(),
- ResourceBundleManager.getManager(resource.getProject()),
- bundleId);
- if (dialog.open() != InputDialog.OK)
- return;
-
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
-
- document.replace(startPos, endPos, "\"" + key + "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java b/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java
deleted file mode 100644
index 246bcd24..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package ui;
-
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-import auditor.ResourceAuditVisitor;
-
-public class ConstantStringHover implements IJavaEditorTextHover {
-
- IEditorPart editor = null;
- ResourceAuditVisitor csf = null;
- ResourceBundleManager manager = null;
-
- @Override
- public void setEditor(IEditorPart editor) {
- this.editor = editor;
- initConstantStringAuditor();
- }
-
- protected void initConstantStringAuditor () {
- // parse editor content and extract resource-bundle access strings
-
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
- .getEditorInput());
-
- if (typeRoot == null)
- return;
-
- // get a reference to the shared AST of the loaded CompilationUnit
- CompilationUnit cu = SharedASTProvider.getAST(typeRoot,
- // do not wait for AST creation
- SharedASTProvider.WAIT_NO, null);
-
- if (cu == null)
- return;
-
- manager = ResourceBundleManager.getManager(
- cu.getJavaElement().getResource().getProject()
- );
-
- // determine the element at the position of the cursur
- csf = new ResourceAuditVisitor(null, manager);
- cu.accept(csf);
- }
-
- @Override
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- initConstantStringAuditor();
- if (hoverRegion == null)
- return null;
-
- // get region for string literals
- hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset());
-
- if (hoverRegion == null)
- return null;
-
- String bundleName = csf.getBundleReference(hoverRegion);
- String key = csf.getKeyAt(hoverRegion);
-
- String hoverText = manager.getKeyHoverString(bundleName, key);
- if (hoverText == null || hoverText.equals(""))
- return null;
- else
- return hoverText;
- }
-
- @Override
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- if (editor == null)
- return null;
-
- // Retrieve the property key at this position. Otherwise, null is returned.
- return csf.getKeyAt(Long.valueOf(offset));
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/MessageCompletionProposalComputer.java b/org.eclipselabs.tapiji.tools.java/src/ui/MessageCompletionProposalComputer.java
deleted file mode 100644
index 0efc6fbc..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/MessageCompletionProposalComputer.java
+++ /dev/null
@@ -1,218 +0,0 @@
-package ui;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.CompletionContext;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-import ui.autocompletion.CreateResourceBundleProposal;
-import ui.autocompletion.InsertResourceBundleReferenceProposal;
-import ui.autocompletion.MessageCompletionProposal;
-import ui.autocompletion.NewResourceBundleEntryProposal;
-import ui.autocompletion.NoActionProposal;
-import auditor.ResourceAuditVisitor;
-
-public class MessageCompletionProposalComputer implements
- IJavaCompletionProposalComputer {
-
- private ResourceAuditVisitor csav;
- private IJavaElement je;
- private IJavaElement javaElement;
- private CompilationUnit cu;
-
- public MessageCompletionProposalComputer() {
-
- }
-
-
-
- @Override
- public List<ICompletionProposal> computeCompletionProposals(
- ContentAssistInvocationContext context, IProgressMonitor monitor) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
-
- if (!InternationalizationNature.hasNature(((JavaContentAssistInvocationContext) context)
- .getCompilationUnit().getResource().getProject()) )
- return completions;
-
- try {
- CompletionContext coreContext = ((JavaContentAssistInvocationContext) context)
- .getCoreContext();
- int offset = coreContext.getOffset();
-
- if (javaElement == null)
- javaElement = ((JavaContentAssistInvocationContext) context)
- .getCompilationUnit().getElementAt(offset);
-
- String stringLiteralStart = new String(coreContext.getToken());
-
- // Check if the string literal is up to be written within the context
- // of a resource-bundle accessor method
- ResourceBundleManager manager = ResourceBundleManager.getManager(javaElement.getResource().getProject());
-
- if (csav == null) {
- csav = new ResourceAuditVisitor(null,
- manager);
- je = JavaCore.create(javaElement.getResource());
- }
-
- if (je instanceof ICompilationUnit) {
- // get the type of the currently loaded resource
- if (cu == null) {
- ITypeRoot typeRoot = ((ICompilationUnit) je);
-
- if (typeRoot == null)
- return null;
-
- // get a reference to the shared AST of the loaded CompilationUnit
- cu = SharedASTProvider.getAST(typeRoot,
- // do not wait for AST creation
- SharedASTProvider.WAIT_YES, null);
- cu.accept(csav);
- }
-
- //StringLiteralAnalyzer sla = new StringLiteralAnalyzer(javaElement.getResource());
- if (csav.getKeyAt(new Long(offset)) != null) {
- completions.addAll(getResourceBundleCompletionProposals(offset, stringLiteralStart, manager, csav, javaElement.getResource()));
- } else if (csav.getRBReferenceAt(new Long(offset)) != null) {
- completions.addAll(getRBReferenceCompletionProposals(offset, stringLiteralStart, manager, je.getResource()));
- } else {
- completions.addAll(getBasicJavaCompletionProposals(offset, stringLiteralStart, manager, csav, je.getResource()));
- }
- if (completions.size() == 1)
- completions.add(new NoActionProposal());
- } else
- return null;
- } catch (Exception e) {
- // e.printStackTrace();
- }
- return completions;
- }
-
- private Collection<ICompletionProposal> getRBReferenceCompletionProposals(
- int offset, String stringLiteralStart, ResourceBundleManager manager, IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- int posStart = offset - stringLiteralStart.length();
- boolean hit = false;
-
- // Show a list of available resource bundles
- List<String> resourceBundles = manager.getResourceBundleIdentifiers();
- for (String rbName : resourceBundles) {
- if (rbName.startsWith(stringLiteralStart)) {
- if (rbName.equals(stringLiteralStart))
- hit = true;
- else
- completions.add (new MessageCompletionProposal (posStart, stringLiteralStart.length(), rbName, true));
- }
- }
-
- if (!hit && stringLiteralStart.trim().length() > 0)
- completions.add(new CreateResourceBundleProposal(stringLiteralStart, resource, posStart, posStart + stringLiteralStart.length()));
-
- return completions;
- }
-
- protected List<ICompletionProposal> getBasicJavaCompletionProposals (
- int offset, String stringLiteralStart,
- ResourceBundleManager manager, ResourceAuditVisitor csav, IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
-
- if (stringLiteralStart.length() == 0) {
- // If nothing has been entered
- completions.add(new InsertResourceBundleReferenceProposal(
- offset - stringLiteralStart.length(),
- stringLiteralStart.length(),
- manager, resource, csav.getDefinedResourceBundles(offset)));
- completions.add(new NewResourceBundleEntryProposal(resource, stringLiteralStart, offset - stringLiteralStart.length(),
- stringLiteralStart.length(), false, manager, null/*, csav.getDefinedResourceBundles(offset)*/));
- } else {
-// if (!"Hallo Welt".equals(stringLiteralStart)) {
-// // If a part of a String has already been entered
-// if ("Hallo Welt".startsWith(stringLiteralStart) ) {
-// completions.add(new ValueOfResourceBundleProposal(offset - stringLiteralStart.length(),
-// stringLiteralStart.length(), "hello.world", "Hallo Welt!"));
-// }
- completions.add(new NewResourceBundleEntryProposal(resource, stringLiteralStart, offset - stringLiteralStart.length(),
- stringLiteralStart.length(), false, manager, null/*, csav.getDefinedResourceBundles(offset)*/));
-
-// }
- }
- return completions;
- }
-
- protected List<ICompletionProposal> getResourceBundleCompletionProposals (
- int offset, String stringLiteralStart, ResourceBundleManager manager,
- ResourceAuditVisitor csav, IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- IRegion region = csav.getKeyAt(new Long(offset));
- String bundleName = csav.getBundleReference(region);
- int posStart = offset - stringLiteralStart.length();
- IMessagesBundleGroup bundleGroup = manager.getResourceBundle(bundleName);
-
- if (stringLiteralStart.length() > 0) {
- boolean hit = false;
- // If a part of a String has already been entered
- for (String key : bundleGroup.getMessageKeys()) {
- if (key.toLowerCase().startsWith(stringLiteralStart.toLowerCase())) {
- if (!key.equals(stringLiteralStart))
- completions.add(new MessageCompletionProposal(posStart,
- stringLiteralStart.length(), key, false));
- else
- hit = true;
- }
- }
- if (!hit)
- completions.add(new NewResourceBundleEntryProposal(resource, stringLiteralStart, offset - stringLiteralStart.length(),
- stringLiteralStart.length(), true, manager, bundleName/*, csav.getDefinedResourceBundles(offset)*/));
- } else {
- for (String key : bundleGroup.getMessageKeys()) {
- completions.add (new MessageCompletionProposal (posStart, stringLiteralStart.length(), key, false));
- }
- completions.add(new NewResourceBundleEntryProposal(resource, stringLiteralStart, offset - stringLiteralStart.length(),
- stringLiteralStart.length(), true, manager, bundleName/*, csav.getDefinedResourceBundles(offset)*/));
-
- }
- return completions;
- }
-
- @Override
- public List computeContextInformation(
- ContentAssistInvocationContext context, IProgressMonitor monitor) {
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- // TODO Auto-generated method stub
- return "";
- }
-
- @Override
- public void sessionEnded() {
- csav = null;
- javaElement = null;
- cu = null;
- }
-
- @Override
- public void sessionStarted() {
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/CreateResourceBundleProposal.java
deleted file mode 100644
index 2d2672dd..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/CreateResourceBundleProposal.java
+++ /dev/null
@@ -1,194 +0,0 @@
-package ui.autocompletion;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.wizard.IWizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.wizards.IWizardDescriptor;
-import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import org.eclipselabs.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
-
-public class CreateResourceBundleProposal implements IJavaCompletionProposal {
-
- private IResource resource;
- private int start;
- private int end;
- private String key;
- private boolean jsfContext;
- private final String newBunldeWizard = "com.essiembre.eclipse.rbe.ui.wizards.ResourceBundleWizard";
-
- public CreateResourceBundleProposal (String key, IResource resource, int start, int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key, ResourceBundleManager.getManager( resource.getProject() ));
- this.resource = resource;
- this.start = start;
- this.end = end;
- }
-
- public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
- }
-
- public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
- }
-
- protected void runAction () {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
- if (!(wizard instanceof IResourceBundleWizard))
- return;
-
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length-1];
- String packageName = "";
-
- rbw.setBundleId(rbName);
-
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
-
- for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr.getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
-
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
-
- rbw.setDefaultPath (pathName);
-
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- (new StringLiteralAuditor()).buildProject(null, resource.getProject());
- (new StringLiteralAuditor()).buildResource(resource, null);
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- if (document.get().charAt(start-1) == '"' && document.get().charAt(start) != '"') {
- start --;
- end ++;
- }
- if (document.get().charAt(end+1) == '"' && document.get().charAt(end) != '"')
- end ++;
-
- document.replace(start, end-start,
- "\"" +
- (packageName.equals("") ? "" : packageName + ".") + rbName +
- "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- } 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
- return 99;
- }
-
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java
deleted file mode 100644
index bad4c7a2..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package ui.autocompletion;
-
-import java.util.Collection;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
-
-import util.ASTutils;
-
-public class InsertResourceBundleReferenceProposal implements IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private ResourceBundleManager manager;
- private IResource resource;
- private String reference;
-
- public InsertResourceBundleReferenceProposal (int offset, int length, ResourceBundleManager manager,
- IResource resource, Collection<String> availableBundles) {
- this.offset = offset;
- this.length = length;
- this.manager = manager;
- this.resource = resource;
- }
-
- @Override
- public void apply(IDocument document) {
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell(),
- manager, "");
- if (dialog.open() != InputDialog.OK)
- return;
-
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
-
- reference = ASTutils.insertExistingBundleRef(document, resource, offset, length, resourceBundleId, key, locale);
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return "Insert reference to a localized string literal";
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- int referenceLength = reference == null ? 0 : reference.length();
- return new Point (offset + referenceLength, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- if (this.length == 0)
- return 1097;
- else
- return 97;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/MessageCompletionProposal.java
deleted file mode 100644
index e76d5722..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/MessageCompletionProposal.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-
-
-public class MessageCompletionProposal implements IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private String content = "";
- private boolean messageAccessor = false;
-
- public MessageCompletionProposal (int offset, int length, String content, boolean messageAccessor) {
- this.offset = offset;
- this.length = length;
- this.content = content;
- this.messageAccessor = messageAccessor;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- document.replace(offset, length, content);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;//"Inserts the property key '" + content + "' of the resource-bundle 'at.test.messages'";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return content;
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- if (messageAccessor)
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return new Point (offset+content.length()+1, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- return 99;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java
deleted file mode 100644
index e713c7a6..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ /dev/null
@@ -1,119 +0,0 @@
-package ui.autocompletion;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-
-import util.ASTutils;
-
-public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
-
- private int startPos;
- private int endPos;
- private String value;
- private boolean bundleContext;
- private ResourceBundleManager manager;
- private IResource resource;
- private String bundleName;
- private String reference;
-
- public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos, boolean bundleContext,
- ResourceBundleManager manager, String bundleName) {
- this.startPos = startPos;
- this.endPos = endPos;
- this.bundleContext = bundleContext;
- this.manager = manager;
- this.value = str;
- this.resource = resource;
- this.bundleName = bundleName;
- }
-
- @Override
- public void apply(IDocument document) {
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell(),
- manager,
- bundleContext ? value : "",
- bundleContext ? "" : value,
- bundleName == null ? "" : bundleName,
- "");
- if (dialog.open() != InputDialog.OK)
- return;
-
-
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedKey();
-
- try {
- if (!bundleContext)
- reference = ASTutils.insertNewBundleRef(document, resource, startPos, endPos, resourceBundleId, key);
- else {
- document.replace(startPos, endPos, key);
- reference = key + "\"";
- }
- ResourceBundleManager.refreshResource(resource);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- if (value != null && value.length() > 0) {
- return "Exports the focused string literal into a Java Resource-Bundle. This action results " +
- "in a Resource-Bundle reference!";
- } else
- return "";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- String displayStr = "";
- if (bundleContext)
- displayStr = "Create a new resource-bundle-entry";
- else
- displayStr = "Create a new localized string literal";
-
- if (value != null && value.length() > 0)
- displayStr += " for '" + value + "'";
-
- return displayStr;
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- int refLength = reference == null ? 0 : reference.length() -1;
- return new Point (startPos + refLength, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- if (this.value.trim().length() == 0)
- return 1096;
- else
- return 1096;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/NoActionProposal.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/NoActionProposal.java
deleted file mode 100644
index 2b3cc9d4..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/NoActionProposal.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-public class NoActionProposal implements IJavaCompletionProposal {
-
- public NoActionProposal () {
- super();
- }
-
- @Override
- public void apply(IDocument document) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- // TODO Auto-generated method stub
- return "No Default Proposals";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- return 100;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/Sorter.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/Sorter.java
deleted file mode 100644
index d13bd38e..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/Sorter.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.AbstractProposalSorter;
-import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-
-public class Sorter extends AbstractProposalSorter {
-
- private boolean loaded = false;
-
- public Sorter () {
- // i18n
- loaded = true;
- }
-
- @Override
- public void beginSorting(ContentAssistInvocationContext context) {
- // TODO Auto-generated method stub
- super.beginSorting(context);
- }
-
- @Override
- public int compare(ICompletionProposal prop1, ICompletionProposal prop2) {
- return getIndex (prop1) - getIndex (prop2);
- }
-
- protected int getIndex (ICompletionProposal prop) {
- if (prop instanceof NoActionProposal)
- return 1;
- else if (prop instanceof MessageCompletionProposal)
- return 2;
- else if (prop instanceof ValueOfResourceBundleProposal)
- return 3;
- else if (prop instanceof InsertResourceBundleReferenceProposal)
- return 4;
- else if (prop instanceof NewResourceBundleEntryProposal)
- return 5;
- else return 0;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/ValueOfResourceBundleProposal.java b/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/ValueOfResourceBundleProposal.java
deleted file mode 100644
index 396d5d72..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/ui/autocompletion/ValueOfResourceBundleProposal.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-public class ValueOfResourceBundleProposal implements IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private String content = "";
- private String matchingString = "";
-
- public ValueOfResourceBundleProposal (int offset, int length, String content, String matchingString) {
- this.offset = offset;
- this.length = length;
- this.content = content;
- this.matchingString = matchingString;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- String inplaceContent = "myResources.getString(\"" + content + "\")";
- // TODO prüfe öffnende und schließende klammern
- document.replace(offset-1, length+2, inplaceContent);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- // TODO Auto-generated method stub
- return "Insert localized reference to '" + matchingString + "'";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- return 98;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.java/src/util/ASTutils.java b/org.eclipselabs.tapiji.tools.java/src/util/ASTutils.java
deleted file mode 100644
index 512ab916..00000000
--- a/org.eclipselabs.tapiji.tools.java/src/util/ASTutils.java
+++ /dev/null
@@ -1,972 +0,0 @@
-package util;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.ASTParser;
-import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.jdt.core.dom.BodyDeclaration;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.ExpressionStatement;
-import org.eclipse.jdt.core.dom.FieldDeclaration;
-import org.eclipse.jdt.core.dom.ITypeBinding;
-import org.eclipse.jdt.core.dom.IVariableBinding;
-import org.eclipse.jdt.core.dom.ImportDeclaration;
-import org.eclipse.jdt.core.dom.MethodDeclaration;
-import org.eclipse.jdt.core.dom.MethodInvocation;
-import org.eclipse.jdt.core.dom.Modifier;
-import org.eclipse.jdt.core.dom.SimpleName;
-import org.eclipse.jdt.core.dom.SimpleType;
-import org.eclipse.jdt.core.dom.StringLiteral;
-import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.jdt.core.dom.TypeDeclaration;
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipselabs.tapiji.tools.core.Logger;
-
-import auditor.MethodParameterDescriptor;
-import auditor.model.SLLocation;
-
-public class ASTutils {
-
- private static MethodParameterDescriptor rbDefinition;
- private static MethodParameterDescriptor rbAccessor;
-
- public static MethodParameterDescriptor getRBDefinitionDesc () {
- if (rbDefinition == null) {
- // Init descriptor for Resource-Bundle-Definition
- List<String> definition = new ArrayList<String>();
- definition.add("getBundle");
- rbDefinition = new MethodParameterDescriptor(definition,
- "java.util.ResourceBundle", true, 0);
- }
-
- return rbDefinition;
- }
-
- public static MethodParameterDescriptor getRBAccessorDesc () {
- if (rbAccessor == null) {
- // Init descriptor for Resource-Bundle-Accessors
- List<String> accessors = new ArrayList<String>();
- accessors.add("getString");
- accessors.add("getStringArray");
- rbAccessor = new MethodParameterDescriptor(accessors,
- "java.util.ResourceBundle", true, 0);
- }
-
- return rbAccessor;
- }
-
- public static String insertExistingBundleRef (IDocument document,
- IResource resource,
- int offset,
- int length,
- String resourceBundleId,
- String key,
- Locale locale) {
- String reference = "";
- String newName = null;
-
- 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;
-
- // 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, offset, resourceBundleId, cu);
- if (variableName == null)
- newName = ASTutils.getNonExistingRBRefName(resourceBundleId, document, cu);
-
- try {
- reference = ASTutils.createResourceReference(
- resourceBundleId,
- key,
- locale,
- resource,
- offset,
- variableName == null ? newName : variableName,
- document,
- cu);
-
- document.replace(offset, length, reference);
-
- // create non-internationalisation-comment
- createReplaceNonInternationalisationComment(cu, document, offset);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
-
- // TODO retrieve cu in the same way as in createResourceReference
- // the current version does not parse method bodies
-
- if (variableName == null){
- ASTutils.createResourceBundleReference(resource, offset, document, resourceBundleId, locale, true, newName, cu);
-// createReplaceNonInternationalisationComment(cu, document, pos);
- }
- return reference;
- }
-
- public static String insertNewBundleRef (IDocument document,
- IResource resource,
- int startPos,
- int endPos,
- String resourceBundleId,
- String key) {
- String newName = null;
- String reference = "";
-
- 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;
-
- // 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);
-
- try {
- reference = ASTutils.createResourceReference(
- resourceBundleId,
- key,
- null,
- resource,
- startPos,
- variableName == null ? newName : variableName,
- document,
- cu);
-
- if (startPos > 0 && document.get().charAt(startPos-1) == '\"') {
- startPos --;
- endPos ++;
- }
-
- if ((startPos + endPos) < document.getLength() && document.get().charAt(startPos + endPos) == '\"')
- endPos ++;
-
- if ((startPos + endPos) < document.getLength() && document.get().charAt(startPos + endPos-1) == ';')
- endPos --;
-
- document.replace(startPos, endPos, reference);
-
- // create non-internationalisation-comment
- createReplaceNonInternationalisationComment(cu, document, startPos);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
-
- if (variableName == null) {
- // refresh reference to the shared AST of the loaded CompilationUnit
- cu = SharedASTProvider.getAST(typeRoot,
- // do not wait for AST creation
- SharedASTProvider.WAIT_YES, null);
-
- ASTutils.createResourceBundleReference(resource, startPos, document, resourceBundleId, null, true, newName, cu);
-// createReplaceNonInternationalisationComment(cu, document, pos);
- }
-
-
- return reference;
- }
-
- public static String resolveRBReferenceVar (IDocument document, IResource resource, int pos, final String bundleId, CompilationUnit cu) {
- String bundleVar;
-
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
- TypeDeclaration td = typeFinder.getEnclosingType();
- MethodDeclaration meth = typeFinder.getEnclosingMethod();
-
- if (atd == null) {
- BundleDeclarationFinder bdf = new BundleDeclarationFinder(bundleId, td,
- meth != null && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
- td.accept(bdf);
-
- bundleVar = bdf.getVariableName();
- } else {
- BundleDeclarationFinder bdf = new BundleDeclarationFinder(bundleId, atd,
- meth != null && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
- atd.accept(bdf);
-
- bundleVar = bdf.getVariableName();
- }
-
- // Check also method body
- if (meth != null) {
- try {
- InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder(bundleId,
- pos);
- typeFinder.getEnclosingMethod().accept (imbdf);
- bundleVar = imbdf.getVariableName() != null ? imbdf.getVariableName() : bundleVar;
- } catch (Exception e) {
- // ignore
- }
- }
-
- return bundleVar;
- }
-
- public static String getNonExistingRBRefName (String bundleId, IDocument document, CompilationUnit cu) {
- String referenceName = null;
- int i = 0;
-
- while (referenceName == null) {
- String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1) + "Ref" + (i == 0 ? "" : i);
- actRef = actRef.toLowerCase();
-
- VariableFinder vf = new VariableFinder(actRef);
- cu.accept(vf);
-
- if (!vf.isVariableFound()) {
- referenceName = actRef;
- break;
- }
-
- i++;
- }
-
- return referenceName;
- }
-
- @Deprecated
- public static String resolveResourceBundle(MethodInvocation methodInvocation,
- MethodParameterDescriptor rbDefinition,
- Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
- String bundleName = null;
-
- if (methodInvocation.getExpression() instanceof SimpleName) {
- SimpleName vName = (SimpleName) methodInvocation.getExpression();
- IVariableBinding vBinding = (IVariableBinding) vName
- .resolveBinding();
- VariableDeclarationFragment dec = variableBindingManagers
- .get(vBinding);
-
- if (dec.getInitializer() instanceof MethodInvocation) {
- MethodInvocation init = (MethodInvocation) dec.getInitializer();
-
- // Check declaring class
- boolean isValidClass = false;
- ITypeBinding type = init.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(
- rbDefinition.getDeclaringClass())) {
- isValidClass = true;
- break;
- } else {
- if (rbDefinition.isConsiderSuperclass())
- type = type.getSuperclass();
- else
- type = null;
- }
-
- }
- if (!isValidClass)
- return null;
-
- boolean isValidMethod = false;
- for (String mn : rbDefinition.getMethodName()) {
- if (init.getName().getFullyQualifiedName().equals(mn)) {
- isValidMethod = true;
- break;
- }
- }
- if (!isValidMethod)
- return null;
-
- // retrieve bundlename
- if (init.arguments().size() < rbDefinition.getPosition() + 1)
- return null;
-
- bundleName = ((StringLiteral) init.arguments().get(
- rbDefinition.getPosition())).getLiteralValue();
- }
- }
-
- return bundleName;
- }
-
- public static SLLocation resolveResourceBundleLocation (MethodInvocation methodInvocation,
- MethodParameterDescriptor rbDefinition,
- Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
- SLLocation bundleDesc = null;
-
- if (methodInvocation.getExpression() instanceof SimpleName) {
- SimpleName vName = (SimpleName) methodInvocation.getExpression();
- IVariableBinding vBinding = (IVariableBinding) vName
- .resolveBinding();
- VariableDeclarationFragment dec = variableBindingManagers
- .get(vBinding);
-
- if (dec.getInitializer() instanceof MethodInvocation) {
- MethodInvocation init = (MethodInvocation) dec.getInitializer();
-
- // Check declaring class
- boolean isValidClass = false;
- ITypeBinding type = init.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(
- rbDefinition.getDeclaringClass())) {
- isValidClass = true;
- break;
- } else {
- if (rbDefinition.isConsiderSuperclass())
- type = type.getSuperclass();
- else
- type = null;
- }
-
- }
- if (!isValidClass)
- return null;
-
- boolean isValidMethod = false;
- for (String mn : rbDefinition.getMethodName()) {
- if (init.getName().getFullyQualifiedName().equals(mn)) {
- isValidMethod = true;
- break;
- }
- }
- if (!isValidMethod)
- return null;
-
- // retrieve bundlename
- if (init.arguments().size() < rbDefinition.getPosition() + 1)
- return null;
-
- StringLiteral bundleLiteral = ((StringLiteral) init.arguments().get(
- rbDefinition.getPosition()));
- bundleDesc = new SLLocation (null, bundleLiteral.getStartPosition(), bundleLiteral.getLength() + bundleLiteral.getStartPosition(), bundleLiteral.getLiteralValue());
- }
- }
-
- return bundleDesc;
- }
-
- private static boolean isMatchingMethodDescriptor (
- MethodInvocation methodInvocation,
- MethodParameterDescriptor desc) {
- boolean result = false;
-
- if (methodInvocation.resolveMethodBinding() == null)
- return false;
-
- String methodName = methodInvocation.resolveMethodBinding().getName();
-
- // Check declaring class
- ITypeBinding type = methodInvocation.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(desc.getDeclaringClass())) {
- result = true;
- break;
- } else {
- if (desc.isConsiderSuperclass())
- type = type.getSuperclass();
- else
- type = null;
- }
-
- }
-
- if (!result)
- return false;
-
- result = !result;
-
- // Check method name
- for (String method : desc.getMethodName()) {
- if (method.equals(methodName)) {
- result = true;
- break;
- }
- }
-
- return result;
- }
-
- public static boolean isMatchingMethodParamDesc(
- MethodInvocation methodInvocation, String literal,
- MethodParameterDescriptor desc) {
- boolean result = isMatchingMethodDescriptor (methodInvocation, desc);
-
- if (!result)
- return false;
- else
- result = false;
-
- if (methodInvocation.arguments().size() > desc.getPosition()) {
- if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) {
- StringLiteral sl = (StringLiteral) methodInvocation.arguments().get(desc.getPosition());
- if (sl.getLiteralValue().trim().toLowerCase().equals(literal.toLowerCase()))
- result = true;
- }
- }
-
- return result;
- }
-
- public static boolean isMatchingMethodParamDesc(
- MethodInvocation methodInvocation, StringLiteral literal,
- MethodParameterDescriptor desc) {
- int keyParameter = desc.getPosition();
- boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
-
- if (!result)
- return false;
-
- // Check position within method call
- StructuralPropertyDescriptor spd = literal.getLocationInParent();
- if (spd.isChildListProperty()) {
- List<ASTNode> arguments = (List<ASTNode>) methodInvocation
- .getStructuralProperty(spd);
- result = (arguments.size() > keyParameter && arguments
- .get(keyParameter) == literal);
- }
-
- return result;
- }
-
- public static ICompilationUnit createCompilationUnit (IResource resource) {
- // Instantiate a new AST parser
- ASTParser parser = ASTParser.newParser (AST.JLS3);
- parser.setResolveBindings(true);
-
- ICompilationUnit cu =
- JavaCore.createCompilationUnitFrom(resource.getProject().getFile(resource.getRawLocation()));
-
- return cu;
- }
-
- public static CompilationUnit createCompilationUnit (IDocument document) {
- // Instantiate a new AST parser
- ASTParser parser = ASTParser.newParser (AST.JLS3);
- parser.setResolveBindings(true);
-
- parser.setSource(document.get().toCharArray());
- return (CompilationUnit) parser.createAST(null);
- }
-
- public static void createImport (IDocument doc,
- IResource resource,
- CompilationUnit cu,
- AST ast,
- ASTRewrite rewriter,
- String qualifiedClassName)
- throws CoreException, BadLocationException {
-
- ImportFinder impFinder = new ImportFinder (qualifiedClassName);
-
- cu.accept(impFinder);
-
- if (!impFinder.isImportFound()) {
-// ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
-// IPath path = resource.getFullPath();
-//
-// bufferManager.connect(path, LocationKind.IFILE, null);
-// ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(doc);
-
- // TODO create new import
- ImportDeclaration id = ast.newImportDeclaration();
- id.setName(ast.newName(qualifiedClassName.split("\\.")));
- id.setStatic(false);
-
- ListRewrite lrw = rewriter.getListRewrite(cu, cu.IMPORTS_PROPERTY);
- lrw.insertFirst(id, null);
-
-// TextEdit te = rewriter.rewriteAST(doc, null);
-// te.apply(doc);
-//
-// if (textFileBuffer != null)
-// textFileBuffer.commit(null, false);
-// else
-// FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()),
-// doc.get());
-// bufferManager.disconnect(path, LocationKind.IFILE, null);
- }
-
- }
-
- // TODO export initializer specification into a methodinvocationdefinition
- public static void createResourceBundleReference (
- IResource resource,
- int typePos,
- IDocument doc,
- String bundleId,
- Locale locale,
- boolean globalReference,
- String variableName,
- CompilationUnit cu) {
-
- try {
-
- if (globalReference) {
-
- // retrieve compilation unit from document
- PositionalTypeFinder typeFinder = new PositionalTypeFinder( typePos );
- cu.accept(typeFinder);
- ASTNode node = typeFinder.getEnclosingType();
- ASTNode anonymNode = typeFinder.getEnclosingAnonymType();
- if (anonymNode != null)
- node = anonymNode;
-
- MethodDeclaration meth = typeFinder.getEnclosingMethod();
- AST ast = node.getAST();
-
- VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
- vdf.setName(ast.newSimpleName(variableName));
-
- // set initializer
- vdf.setInitializer(createResourceBundleGetter(ast, bundleId, locale));
-
- FieldDeclaration fd = ast.newFieldDeclaration(vdf);
- fd.setType(ast.newSimpleType(ast.newName(new String [] {"ResourceBundle"} )));
-
- if (meth != null && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
- fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC));
-
-
- // rewrite AST
- ASTRewrite rewriter = ASTRewrite.create(ast);
- ListRewrite lrw = rewriter.getListRewrite(node,
- node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY :
- AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- lrw.insertAt(fd, /* findIndexOfLastField(node.bodyDeclarations())+1 */
- 0, null);
-
- // create import if required
- createImport(doc, resource, cu, ast, rewriter, getRBDefinitionDesc().getDeclaringClass());
-
- TextEdit te = rewriter.rewriteAST(doc, null);
- te.apply(doc);
- } else {
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- private static int findIndexOfLastField(List bodyDeclarations) {
- for (int i= bodyDeclarations.size() - 1; i >= 0; i--) {
- BodyDeclaration each= (BodyDeclaration)bodyDeclarations.get(i);
- if (each instanceof FieldDeclaration)
- return i;
- }
- return -1;
- }
-
- protected static MethodInvocation createResourceBundleGetter (AST ast, String bundleId, Locale locale) {
- MethodInvocation mi = ast.newMethodInvocation();
-
- mi.setName(ast.newSimpleName("getBundle"));
- mi.setExpression(ast.newName(new String[] { "ResourceBundle" }));
-
- // Add bundle argument
- StringLiteral sl = ast.newStringLiteral();
- sl.setLiteralValue(bundleId);
- mi.arguments().add(sl);
-
- // TODO Add Locale argument
-
- return mi;
- }
-
- public static ASTNode getEnclosingType (CompilationUnit cu, int pos) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder.getEnclosingAnonymType() : typeFinder.getEnclosingType();
- }
-
- public static ASTNode getEnclosingType (ASTNode cu, int pos) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder.getEnclosingAnonymType() : typeFinder.getEnclosingType();
- }
-
- protected static MethodInvocation referenceResource (AST ast, String accessorName, String key, Locale locale) {
- MethodParameterDescriptor accessorDesc = getRBAccessorDesc();
- MethodInvocation mi = ast.newMethodInvocation();
-
- mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0)));
-
- // Declare expression
- StringLiteral sl = ast.newStringLiteral();
- sl.setLiteralValue(key);
-
- // TODO define locale expression
- if (mi.arguments().size() == accessorDesc.getPosition())
- mi.arguments().add(sl);
-
- SimpleName name = ast.newSimpleName(accessorName);
- mi.setExpression(name);
-
- return mi;
- }
-
- public static String createResourceReference (String bundleId,
- String key,
- Locale locale,
- IResource resource,
- int typePos,
- String accessorName,
- IDocument doc,
- CompilationUnit cu) {
-
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos);
- cu.accept(typeFinder);
- AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
- TypeDeclaration td = typeFinder.getEnclosingType();
-
- // retrieve compilation unit from document
- ASTNode node = atd == null ? td : atd;
- AST ast = node.getAST();
-
- ExpressionStatement expressionStatement = ast
- .newExpressionStatement(referenceResource(ast, accessorName, key, locale));
-
- String exp = expressionStatement.toString();
-
- // remove semicolon and line break at the end of this expression statement
- if (exp.endsWith(";\n"))
- exp = exp.substring(0, exp.length()-2);
-
- return exp;
- }
-
- private static int findNonInternationalisationPosition(CompilationUnit cu, IDocument doc, int offset){
- LinePreStringsFinder lsfinder = null;
- try {
- lsfinder = new LinePreStringsFinder(offset, doc);
- cu.accept(lsfinder);
- } catch (BadLocationException e) {
- Logger.logError(e);
- }
- if (lsfinder == null) return 1;
-
- List<StringLiteral> strings = lsfinder.getStrings();
-
- return strings.size()+1;
- }
-
- public static void createReplaceNonInternationalisationComment(CompilationUnit cu, IDocument doc, int position) {
- int i = findNonInternationalisationPosition(cu, doc, position);
-
- IRegion reg;
- try {
- reg = doc.getLineInformationOfOffset(position);
- doc.replace(reg.getOffset()+reg.getLength(), 0, " //$NON-NLS-"+i+"$");
- } catch (BadLocationException e) {
- Logger.logError(e);
- }
- }
-
- private static void createASTNonInternationalisationComment(CompilationUnit cu, IDocument doc, ASTNode parent, ASTNode fd, ASTRewrite rewriter, ListRewrite lrw) {
- int i = 1;
-
-// ListRewrite lrw2 = rewriter.getListRewrite(node, Block.STATEMENTS_PROPERTY);
- ASTNode placeHolder= rewriter.createStringPlaceholder("//$NON-NLS-"+i+"$", ASTNode.LINE_COMMENT);
- lrw.insertAfter(placeHolder, fd, null);
- }
-
- public static boolean existsNonInternationalisationComment(StringLiteral literal) throws BadLocationException {
- CompilationUnit cu = (CompilationUnit) literal.getRoot();
- ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
-
- IDocument doc = null;
- try {
- doc = new Document(icu.getSource());
- } catch (JavaModelException e) {
- Logger.logError(e);
- }
-
- // get whole line in which string literal
- int lineNo = doc.getLineOfOffset(literal.getStartPosition());
- int lineOffset = doc.getLineOffset(lineNo);
- int lineLength = doc.getLineLength(lineNo);
- String lineOfString = doc.get(lineOffset, lineLength);
-
- // search for a line comment in this line
- int indexComment = lineOfString.indexOf("//");
-
- if (indexComment == -1)
- return false;
-
- String comment = lineOfString.substring(indexComment);
-
- // remove first "//" of line comment
- comment = comment.substring(2).toLowerCase();
-
- // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
- String[] comments = comment.split("//");
-
- for (String commentFrag : comments) {
- commentFrag = commentFrag.trim();
-
- // if comment match format: "$non-nls$" then ignore whole line
- if (commentFrag.matches("^\\$non-nls\\$$")) {
- return true;
-
- // if comment match format: "$non-nls-{number}$" then only ignore string which is on given position
- } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
- int iString = findNonInternationalisationPosition(cu, doc, literal.getStartPosition());
- int iComment = new Integer(commentFrag.substring(9,10));
- if (iString == iComment)
- return true;
- }
- }
- return false;
- }
-
- static class PositionalTypeFinder extends ASTVisitor {
-
- private int position;
- private TypeDeclaration enclosingType;
- private AnonymousClassDeclaration enclosingAnonymType;
- private MethodDeclaration enclosingMethod;
-
- public PositionalTypeFinder (int pos) {
- position = pos;
- }
-
- public TypeDeclaration getEnclosingType() {
- return enclosingType;
- }
-
- public AnonymousClassDeclaration getEnclosingAnonymType () {
- return enclosingAnonymType;
- }
-
- public MethodDeclaration getEnclosingMethod () {
- return enclosingMethod;
- }
-
- public boolean visit (MethodDeclaration node) {
- if (position >= node.getStartPosition() &&
- position <= (node.getStartPosition() + node.getLength())) {
- enclosingMethod = node;
- return true;
- } else
- return false;
- }
-
- public boolean visit (TypeDeclaration node) {
- if (position >= node.getStartPosition() &&
- position <= (node.getStartPosition() + node.getLength())) {
- enclosingType = node;
- return true;
- } else
- return false;
- }
-
- public boolean visit (AnonymousClassDeclaration node) {
- if (position >= node.getStartPosition() &&
- position <= (node.getStartPosition() + node.getLength())) {
- enclosingAnonymType = node;
- return true;
- } else
- return false;
- }
- }
-
- static class ImportFinder extends ASTVisitor {
-
- String qName;
- boolean importFound = false;
-
- public ImportFinder (String qName) {
- this.qName = qName;
- }
-
- public boolean isImportFound () {
- return importFound;
- }
-
- public boolean visit (ImportDeclaration id) {
- if (id.getName().getFullyQualifiedName().equals(
- qName
- ))
- importFound = true;
-
- return true;
- }
- }
-
- static class VariableFinder extends ASTVisitor {
-
- boolean found = false;
- String variableName;
-
- public boolean isVariableFound () {
- return found;
- }
-
- public VariableFinder (String variableName) {
- this.variableName = variableName;
- }
-
- public boolean visit (VariableDeclarationFragment vdf) {
- if (vdf.getName().getFullyQualifiedName().equals(variableName)) {
- found = true;
- return false;
- }
-
- return true;
- }
- }
-
- static class InMethodBundleDeclFinder extends ASTVisitor {
- String varName;
- String bundleId;
- int pos;
-
- public InMethodBundleDeclFinder (String bundleId, int pos) {
- this.bundleId = bundleId;
- this.pos = pos;
- }
-
- public String getVariableName () {
- return varName;
- }
-
- public boolean visit (VariableDeclarationFragment fdvd) {
- if (fdvd.getStartPosition() > pos)
- return false;
-
-// boolean bStatic = (fdvd.resolveBinding().getModifiers() & Modifier.STATIC) == Modifier.STATIC;
-// if (!bStatic && isStatic)
-// return true;
-
- String tmpVarName = fdvd.getName().getFullyQualifiedName();
-
- if (fdvd.getInitializer() instanceof MethodInvocation) {
- MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
- if (isMatchingMethodParamDesc(
- fdi, bundleId, getRBDefinitionDesc()))
- varName = tmpVarName;
- }
- return true;
- }
- }
-
- static class BundleDeclarationFinder extends ASTVisitor {
-
- String varName;
- String bundleId;
- ASTNode typeDef;
- boolean isStatic;
-
- public BundleDeclarationFinder (String bundleId, ASTNode td, boolean isStatic) {
- this.bundleId = bundleId;
- this.typeDef = td;
- this.isStatic = isStatic;
- }
-
- public String getVariableName () {
- return varName;
- }
-
- public boolean visit (MethodDeclaration md) {
- return true;
- }
-
- public boolean visit (FieldDeclaration fd) {
- if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef)
- return false;
-
- boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
- if (!bStatic && isStatic)
- return true;
-
- if (fd.getType() instanceof SimpleType) {
- SimpleType fdType = (SimpleType) fd.getType();
- String typeName = fdType.getName().getFullyQualifiedName();
- String referenceName = getRBDefinitionDesc().getDeclaringClass();
- if (typeName.equals(referenceName) ||
- (referenceName.lastIndexOf(".") >= 0 && typeName.equals(referenceName.substring(referenceName.lastIndexOf(".")+1)))) {
- // Check VariableDeclarationFragment
- if (fd.fragments().size() == 1) {
- if (fd.fragments().get(0) instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd.fragments().get(0);
- String tmpVarName = fdvd.getName().getFullyQualifiedName();
-
- if (fdvd.getInitializer() instanceof MethodInvocation) {
- MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
- if (isMatchingMethodParamDesc(
- fdi, bundleId, getRBDefinitionDesc()))
- varName = tmpVarName;
- }
- }
- }
- }
- }
- return false;
- }
-
- }
-
- static class LinePreStringsFinder extends ASTVisitor{
- private int position;
- private int line;
- private List<StringLiteral> strings;
- private IDocument document;
-
- public LinePreStringsFinder(int position, IDocument document) throws BadLocationException{
- this.document=document;
- this.position = position;
- line = document.getLineOfOffset(position);
- strings = new ArrayList<StringLiteral>();
- }
-
- public List<StringLiteral> getStrings(){
- return strings;
- }
-
- @Override
- public boolean visit (StringLiteral node){
- try{
- if (line == document.getLineOfOffset(node.getStartPosition()) && node.getStartPosition() < position){
- strings.add(node);
- return true;
- }
- }catch(BadLocationException e){
- }
- return true;
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html b/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html
index ed4b1966..b776137d 100644
--- a/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html
+++ b/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html
@@ -1,6 +1,6 @@
<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">
+ 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">
@@ -8,7 +8,7 @@
<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">
+ 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>
@@ -24,304 +24,429 @@
<o:CharactersWithSpaces>11384</o:CharactersWithSpaces>
<o:Version>9.4402</o:Version>
</o:DocumentProperties>
-</xml><![endif]--><!--[if gte mso 9]><xml>
+</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;}
+<!-- /* 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 ("AGREEMENT"). 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'>"Contribution" 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'>"Contributor" means any person or
-entity that distributes the Program.</span> </p>
-
-<p><span style='font-size:10.0pt'>"Licensed Patents " 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'>"Program" means the Contributions
-distributed in accordance with this Agreement.</span> </p>
-
-<p><span style='font-size:10.0pt'>"Recipient" 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 ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") 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 "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING,
-WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
-MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. 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]> <![endif]><o:p></o:p></p>
-
-</div>
+<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
+ ("AGREEMENT"). 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'>"Contribution"
+ 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'>"Contributor" means
+ any person or entity that distributes the Program.</span>
+ </p>
+
+ <p>
+ <span style='font-size: 10.0pt'>"Licensed Patents "
+ 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'>"Program" means the
+ Contributions distributed in accordance with this Agreement.</span>
+ </p>
+
+ <p>
+ <span style='font-size: 10.0pt'>"Recipient" 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 ("Commercial Contributor") hereby agrees to
+ defend and indemnify every other Contributor ("Indemnified
+ Contributor") against any losses, damages and costs
+ (collectively "Losses") 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 "AS IS"
+ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
+ OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
+ CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
+ FOR A PARTICULAR PURPOSE. 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]>
+
+ <![endif]><o:p></o:p></p>
+
+ </div>
</body>
diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml
index bed901fa..27b6d5b4 100644
--- a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml
+++ b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml
@@ -115,8 +115,8 @@ This Agreement is governed by the laws of the State of New York and the intellec
<import plugin="org.eclipse.jst.jsp.core" version="1.2.300" match="greaterOrEqual"/>
<import plugin="org.eclipse.wst.sse.ui"/>
<import plugin="org.eclipse.core.runtime" version="3.6.0" match="greaterOrEqual"/>
- <import plugin="org.eclipselabs.tapiji.tools.core" version="0.0.2" match="greaterOrEqual"/>
- <import plugin="org.eclipselabs.tapiji.translator.rbe" version="0.0.2" match="greaterOrEqual"/>
+ <import plugin="org.eclipse.babel.tapiji.tools.core" version="0.0.2" match="greaterOrEqual"/>
+ <import plugin="org.eclipse.babel.tapiji.translator.rbe" version="0.0.2" match="greaterOrEqual"/>
<import plugin="org.eclipse.core.filebuffers"/>
<import plugin="org.eclipse.swt"/>
<import plugin="org.eclipse.ui.ide"/>
diff --git a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF
index 9022be10..0ffb2355 100644
--- a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF
@@ -6,7 +6,6 @@ Bundle-Version: 0.0.2.qualifier
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Require-Bundle: org.eclipse.core.resources;bundle-version="3.6.0",
org.eclipse.jface,
- org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.2",
org.eclipse.jface.text,
org.eclipse.jdt.core;bundle-version="3.6.0",
org.eclipse.jdt.ui;bundle-version="3.6.0",
@@ -14,7 +13,7 @@ Require-Bundle: org.eclipse.core.resources;bundle-version="3.6.0",
org.eclipse.jst.jsp.core;bundle-version="1.2.300",
org.eclipse.wst.sse.ui,
org.eclipse.core.runtime;bundle-version="3.6.0",
- org.eclipselabs.tapiji.tools.core.ui;bundle-version="1.0.0"
+ org.eclipse.babel.tapiji.tools.core.ui;bundle-version="0.0.2"
Import-Package: org.eclipse.core.filebuffers,
org.eclipse.core.runtime,
org.eclipse.jdt.core,
diff --git a/org.eclipselabs.tapiji.tools.jsf/plugin.xml b/org.eclipselabs.tapiji.tools.jsf/plugin.xml
index 090b7fcd..7f6bba11 100644
--- a/org.eclipselabs.tapiji.tools.jsf/plugin.xml
+++ b/org.eclipselabs.tapiji.tools.jsf/plugin.xml
@@ -40,7 +40,7 @@
</validator>
</extension>
<extension
- point="org.eclipselabs.tapiji.tools.core.builderExtension">
+ point="org.eclipse.babel.tapiji.tools.core.builderExtension">
<i18nResourceAuditor
class="auditor.JSFResourceAuditor">
</i18nResourceAuditor>
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
index e1651b31..6eca3de2 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
@@ -1,111 +1,135 @@
-package auditor;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipselabs.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
-import org.eclipselabs.tapiji.tools.core.builder.quickfix.IncludeResource;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
-
-import quickfix.ExportToResourceBundleResolution;
-import quickfix.ReplaceResourceBundleDefReference;
-import quickfix.ReplaceResourceBundleReference;
-
-public class JSFResourceAuditor extends I18nResourceAuditor {
-
- public String[] getFileEndings () {
- return new String [] {"xhtml", "jsp"};
- }
-
- public void audit(IResource resource) {
- parse (resource);
- }
-
- private void parse (IResource resource) {
-
- }
-
- @Override
- public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public String getContextId() {
- return "jsf";
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- int cause = marker.getAttribute("cause", -1);
-
- switch (cause) {
- case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
- resolutions.add(new ExportToResourceBundleResolution());
- break;
- case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
- String dataName = marker.getAttribute("bundleName", "");
- int dataStart = marker.getAttribute("bundleStart", 0);
- int dataEnd = marker.getAttribute("bundleEnd", 0);
-
- IProject project = marker.getResource().getProject();
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
-
- if (manager.getResourceBundle(dataName) != null) {
- String key = marker.getAttribute("key", "");
-
- resolutions.add(new CreateResourceBundleEntry(key, manager, dataName));
- resolutions.add(new ReplaceResourceBundleReference(key, dataName));
- resolutions.add(new ReplaceResourceBundleDefReference(dataName, dataStart, dataEnd));
- } else {
- String bname = dataName;
-
- Set<IResource> bundleResources =
- ResourceBundleManager.getManager(marker.getResource().getProject()).getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions.add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(bname, marker.getResource(), dataStart, dataEnd));
-
- resolutions.add(new ReplaceResourceBundleDefReference(bname, dataStart, dataEnd));
- }
-
- break;
- case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
- String bname = marker.getAttribute("key", "");
-
- Set<IResource> bundleResources =
- ResourceBundleManager.getManager(marker.getResource().getProject()).getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions.add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(marker.getAttribute("key", ""), marker.getResource(),marker.getAttribute(IMarker.CHAR_START, 0), marker.getAttribute(IMarker.CHAR_END, 0)));
- resolutions.add(new ReplaceResourceBundleDefReference(marker.getAttribute("key", ""), marker.getAttribute(IMarker.CHAR_START, 0), marker.getAttribute(IMarker.CHAR_END, 0)));
- }
-
- return resolutions;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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 auditor;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundle;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.IncludeResource;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+import quickfix.ExportToResourceBundleResolution;
+import quickfix.ReplaceResourceBundleDefReference;
+import quickfix.ReplaceResourceBundleReference;
+
+public class JSFResourceAuditor extends I18nResourceAuditor {
+
+ public String[] getFileEndings() {
+ return new String[] { "xhtml", "jsp" };
+ }
+
+ public void audit(IResource resource) {
+ parse(resource);
+ }
+
+ private void parse(IResource resource) {
+
+ }
+
+ @Override
+ public List<ILocation> getConstantStringLiterals() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenResourceReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenBundleReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public String getContextId() {
+ return "jsf";
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+ int cause = marker.getAttribute("cause", -1);
+
+ switch (cause) {
+ case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
+ resolutions.add(new ExportToResourceBundleResolution());
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
+ String dataName = marker.getAttribute("bundleName", "");
+ int dataStart = marker.getAttribute("bundleStart", 0);
+ int dataEnd = marker.getAttribute("bundleEnd", 0);
+
+ IProject project = marker.getResource().getProject();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(project);
+
+ if (manager.getResourceBundle(dataName) != null) {
+ String key = marker.getAttribute("key", "");
+
+ resolutions.add(new CreateResourceBundleEntry(key, dataName));
+ resolutions.add(new ReplaceResourceBundleReference(key,
+ dataName));
+ resolutions.add(new ReplaceResourceBundleDefReference(dataName,
+ dataStart, dataEnd));
+ } else {
+ String bname = dataName;
+
+ Set<IResource> bundleResources = ResourceBundleManager
+ .getManager(marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions
+ .add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(bname, marker
+ .getResource(), dataStart, dataEnd));
+
+ resolutions.add(new ReplaceResourceBundleDefReference(bname,
+ dataStart, dataEnd));
+ }
+
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
+ String bname = marker.getAttribute("key", "");
+
+ Set<IResource> bundleResources = ResourceBundleManager.getManager(
+ marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions.add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(marker.getAttribute(
+ "key", ""), marker.getResource(), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ resolutions.add(new ReplaceResourceBundleDefReference(marker
+ .getAttribute("key", ""), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ }
+
+ return resolutions;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
index 16f1eca5..26c3bbed 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
@@ -1,418 +1,466 @@
-package auditor;
-
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-public class JSFResourceBundleDetector {
-
- public static List<IRegion> getNonELValueRegions (String elExpression) {
- List<IRegion> stringRegions = new ArrayList<IRegion>();
- int pos = -1;
-
- do {
- int start = pos + 1;
- int end = elExpression.indexOf("#{", start);
- end = end >= 0 ? end : elExpression.length();
-
- if (elExpression.substring(start, end).trim().length() > 0) {
- IRegion region = new Region (start, end-start);
- stringRegions.add(region);
- }
-
- if (elExpression.substring(end).startsWith("#{"))
- pos = elExpression.indexOf("}", end);
- else
- pos = end;
- } while (pos >= 0 && pos < elExpression.length());
-
- return stringRegions;
- }
-
- public static String getBundleVariableName (String elExpression) {
- String bundleVarName = null;
- String[] delimitors = new String [] { ".", "[" };
-
- int startPos = elExpression.indexOf(delimitors[0]);
-
- for (String del : delimitors) {
- if ((startPos > elExpression.indexOf(del) && elExpression.indexOf(del) >= 0) ||
- (startPos == -1 && elExpression.indexOf(del) >= 0))
- startPos = elExpression.indexOf(del);
- }
-
- if (startPos >= 0)
- bundleVarName = elExpression.substring(0, startPos);
-
- return bundleVarName;
- }
-
- public static String getResourceKey (String elExpression) {
- String key = null;
-
- if (elExpression.indexOf("[") == -1 || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression.indexOf(".") >= 0)) {
- // Separation by dot
- key = elExpression.substring(elExpression.indexOf(".") + 1);
- } else {
- // Separation by '[' and ']'
- if (elExpression.indexOf("\"") >= 0 || elExpression.indexOf("'") >= 0) {
- int startPos = elExpression.indexOf("\"") >= 0 ? elExpression.indexOf("\"") : elExpression.indexOf("'");
- int endPos = elExpression.indexOf("\"", startPos + 1) >= 0 ? elExpression.indexOf("\"", startPos + 1) : elExpression.indexOf("'", startPos + 1);
- if (startPos < endPos) {
- key = elExpression.substring(startPos+1, endPos);
- }
- }
- }
-
- return key;
- }
-
- public static String resolveResourceBundleRefIdentifier (IDocument document, int startPos) {
- String result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- if (curNode instanceof Attr) {
- final Attr attr = (Attr) curNode;
- if (attr.getNodeName().toLowerCase().equals("basename")) {
- final Element owner = attr.getOwnerElement();
- if (isBundleElement (owner, context))
- result = attr.getValue();
- }
- } else if (curNode instanceof Element) {
- final Element elem = (Element) curNode;
- if (isBundleElement (elem, context))
- result = elem.getAttribute("basename");
- }
- }
-
- return result;
- }
-
- public static String resolveResourceBundleId(IDocument document,
- String varName) {
- String content = document.get();
- String bundleId = "";
- int offset = 0;
-
- while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
- || content.indexOf("'" + varName + "'", offset+1) >= 0) {
- offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
- .indexOf("\"" + varName + "\"") : content.indexOf("'"
- + varName + "'");
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- Attr attr = null;
- if (curNode instanceof Attr) {
- attr = (Attr) curNode;
- if (!attr.getNodeName().toLowerCase().equals("var"))
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) attr.getOwnerElement();
-
- if (!isBundleElement(parentElement, context))
- continue;
-
- bundleId = parentElement.getAttribute("basename");
- break;
- }
- }
-
- return bundleId;
- }
-
- public static boolean isBundleElement (Element element, IStructuredDocumentContext context) {
- String bName = element.getTagName().substring(element.getTagName().indexOf(":")+1);
-
- if (bName.equals("loadBundle")) {
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- if (tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/core")) {
- return true;
- }
- }
-
- return false;
- }
-
- public static boolean isJSFElement (Element element, IStructuredDocumentContext context) {
- try {
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- if (tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/core") ||
- tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/html")) {
- return true;
- }
- } catch (Exception e) {}
- return false;
- }
-
- public static IRegion getBasenameRegion(IDocument document, int startPos) {
- IRegion result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- if (curNode instanceof Element) {
- final Element elem = (Element) curNode;
- if (isBundleElement (elem, context)) {
- Attr na = elem.getAttributeNode("basename");
-
- if (na != null) {
- int attrStart = document.get().indexOf("basename", startPos);
- result = new Region (document.get().indexOf(na.getValue(), attrStart), na.getValue().length());
- }
- }
- }
- }
-
- return result;
- }
-
- public static IRegion getElementAttrValueRegion(IDocument document, String attribute, int startPos) {
- IRegion result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- Node curNode = domResolver.getNode();
- if (curNode instanceof Attr)
- curNode = ((Attr) curNode).getOwnerElement();
-
- // node must be an XML attribute
- if (curNode instanceof Element) {
- final Element elem = (Element) curNode;
- Attr na = elem.getAttributeNode(attribute);
-
- if (na != null && isJSFElement(elem, context)) {
- int attrStart = document.get().indexOf(attribute, startPos);
- result = new Region (document.get().indexOf(na.getValue().trim(), attrStart), na.getValue().trim().length());
- }
- }
- }
-
- return result;
- }
-
- public static IRegion resolveResourceBundleRefPos(IDocument document,
- String varName) {
- String content = document.get();
- IRegion region = null;
- int offset = 0;
-
- while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
- || content.indexOf("'" + varName + "'", offset+1) >= 0) {
- offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
- .indexOf("\"" + varName + "\"") : content.indexOf("'"
- + varName + "'");
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- Attr attr = null;
- if (curNode instanceof Attr) {
- attr = (Attr) curNode;
- if (!attr.getNodeName().toLowerCase().equals("var"))
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) attr.getOwnerElement();
-
- if (!isBundleElement(parentElement, context))
- continue;
-
- String bundleId = parentElement.getAttribute("basename");
-
- if (bundleId != null && bundleId.trim().length() > 0) {
-
- while (region == null) {
- int basename = content.indexOf("basename", offset);
- int value = content.indexOf(bundleId, content.indexOf("=", basename));
- if (value > basename) {
- region = new Region (value, bundleId.length());
- }
- }
-
- }
- break;
- }
- }
-
- return region;
- }
-
- public static String resolveResourceBundleVariable(IDocument document,
- String selectedResourceBundle) {
- String content = document.get();
- String variableName = null;
- int offset = 0;
-
- while (content.indexOf("\"" + selectedResourceBundle + "\"", offset+1) >= 0
- || content.indexOf("'" + selectedResourceBundle + "'", offset+1) >= 0) {
- offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content
- .indexOf("\"" + selectedResourceBundle + "\"") : content.indexOf("'"
- + selectedResourceBundle + "'");
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- Attr attr = null;
- if (curNode instanceof Attr) {
- attr = (Attr) curNode;
- if (!attr.getNodeName().toLowerCase().equals("basename"))
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) attr.getOwnerElement();
-
- if (!isBundleElement(parentElement, context))
- continue;
-
- variableName = parentElement.getAttribute("var");
- break;
- }
- }
-
- return variableName;
- }
-
- public static String resolveNewVariableName (IDocument document, String selectedResourceBundle) {
- String variableName = "";
- int i = 0;
- variableName = selectedResourceBundle.replace(".", "");
- while (resolveResourceBundleId(document, variableName).trim().length() > 0 ) {
- variableName = selectedResourceBundle + (i++);
- }
- return variableName;
- }
-
- public static void createResourceBundleRef(IDocument document,
- String selectedResourceBundle,
- String variableName) {
- String content = document.get();
- int headInsertPos = -1;
- int offset = 0;
-
- while (content.indexOf("head", offset+1) >= 0) {
- offset = content.indexOf("head", offset+1);
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- if (!(curNode instanceof Element)) {
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) curNode;
-
- if (parentElement.getNodeName().equalsIgnoreCase("head")) {
- do {
- headInsertPos = content.indexOf("head", offset+5);
-
- final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolverHeadClose = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(contextHeadClose);
- if (domResolverHeadClose.getNode() instanceof Element && domResolverHeadClose.getNode().getNodeName().equalsIgnoreCase("head")) {
- headInsertPos = content.substring(0, headInsertPos).lastIndexOf("<");
- break;
- }
- } while (headInsertPos >= 0);
-
- if (headInsertPos < 0) {
- headInsertPos = content.indexOf(">", offset) + 1;
- }
-
- break;
- }
- }
- }
-
- // resolve the taglib
- try {
- int taglibPos = content.lastIndexOf("taglib");
- if (taglibPos > 0) {
- final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, taglibPos);
- taglibPos = content.indexOf("%>", taglibPos);
- if (taglibPos > 0) {
- String decl = createLoadBundleDeclaration (document, taglibContext, variableName, selectedResourceBundle);
- if (headInsertPos > taglibPos)
- document.replace(headInsertPos, 0, decl);
- else
- document.replace(taglibPos, 0, decl);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- private static String createLoadBundleDeclaration(IDocument document,
- IStructuredDocumentContext context, String variableName, String selectedResourceBundle) {
- String bundleDecl = "";
-
- // Retrieve jsf core namespace prefix
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- String bundlePrefix = tlResolver.getTagPrefixForURI("http://java.sun.com/jsf/core");
-
- MessageFormat tlFormatter = new MessageFormat ("<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n");
- bundleDecl = tlFormatter.format(new String[] {bundlePrefix, variableName, selectedResourceBundle});
-
- return bundleDecl;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package auditor;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+public class JSFResourceBundleDetector {
+
+ public static List<IRegion> getNonELValueRegions(String elExpression) {
+ List<IRegion> stringRegions = new ArrayList<IRegion>();
+ int pos = -1;
+
+ do {
+ int start = pos + 1;
+ int end = elExpression.indexOf("#{", start);
+ end = end >= 0 ? end : elExpression.length();
+
+ if (elExpression.substring(start, end).trim().length() > 0) {
+ IRegion region = new Region(start, end - start);
+ stringRegions.add(region);
+ }
+
+ if (elExpression.substring(end).startsWith("#{"))
+ pos = elExpression.indexOf("}", end);
+ else
+ pos = end;
+ } while (pos >= 0 && pos < elExpression.length());
+
+ return stringRegions;
+ }
+
+ public static String getBundleVariableName(String elExpression) {
+ String bundleVarName = null;
+ String[] delimitors = new String[] { ".", "[" };
+
+ int startPos = elExpression.indexOf(delimitors[0]);
+
+ for (String del : delimitors) {
+ if ((startPos > elExpression.indexOf(del) && elExpression
+ .indexOf(del) >= 0)
+ || (startPos == -1 && elExpression.indexOf(del) >= 0))
+ startPos = elExpression.indexOf(del);
+ }
+
+ if (startPos >= 0)
+ bundleVarName = elExpression.substring(0, startPos);
+
+ return bundleVarName;
+ }
+
+ public static String getResourceKey(String elExpression) {
+ String key = null;
+
+ if (elExpression.indexOf("[") == -1
+ || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression
+ .indexOf(".") >= 0)) {
+ // Separation by dot
+ key = elExpression.substring(elExpression.indexOf(".") + 1);
+ } else {
+ // Separation by '[' and ']'
+ if (elExpression.indexOf("\"") >= 0
+ || elExpression.indexOf("'") >= 0) {
+ int startPos = elExpression.indexOf("\"") >= 0 ? elExpression
+ .indexOf("\"") : elExpression.indexOf("'");
+ int endPos = elExpression.indexOf("\"", startPos + 1) >= 0 ? elExpression
+ .indexOf("\"", startPos + 1) : elExpression.indexOf(
+ "'", startPos + 1);
+ if (startPos < endPos) {
+ key = elExpression.substring(startPos + 1, endPos);
+ }
+ }
+ }
+
+ return key;
+ }
+
+ public static String resolveResourceBundleRefIdentifier(IDocument document,
+ int startPos) {
+ String result = null;
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, startPos);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ if (curNode instanceof Attr) {
+ final Attr attr = (Attr) curNode;
+ if (attr.getNodeName().toLowerCase().equals("basename")) {
+ final Element owner = attr.getOwnerElement();
+ if (isBundleElement(owner, context))
+ result = attr.getValue();
+ }
+ } else if (curNode instanceof Element) {
+ final Element elem = (Element) curNode;
+ if (isBundleElement(elem, context))
+ result = elem.getAttribute("basename");
+ }
+ }
+
+ return result;
+ }
+
+ public static String resolveResourceBundleId(IDocument document,
+ String varName) {
+ String content = document.get();
+ String bundleId = "";
+ int offset = 0;
+
+ while (content.indexOf("\"" + varName + "\"", offset + 1) >= 0
+ || content.indexOf("'" + varName + "'", offset + 1) >= 0) {
+ offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
+ .indexOf("\"" + varName + "\"") : content.indexOf("'"
+ + varName + "'");
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ Attr attr = null;
+ if (curNode instanceof Attr) {
+ attr = (Attr) curNode;
+ if (!attr.getNodeName().toLowerCase().equals("var"))
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) attr.getOwnerElement();
+
+ if (!isBundleElement(parentElement, context))
+ continue;
+
+ bundleId = parentElement.getAttribute("basename");
+ break;
+ }
+ }
+
+ return bundleId;
+ }
+
+ public static boolean isBundleElement(Element element,
+ IStructuredDocumentContext context) {
+ String bName = element.getTagName().substring(
+ element.getTagName().indexOf(":") + 1);
+
+ if (bName.equals("loadBundle")) {
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+ if (tlResolver.getTagURIForNodeName(element).trim()
+ .equalsIgnoreCase("http://java.sun.com/jsf/core")) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static boolean isJSFElement(Element element,
+ IStructuredDocumentContext context) {
+ try {
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+ if (tlResolver.getTagURIForNodeName(element).trim()
+ .equalsIgnoreCase("http://java.sun.com/jsf/core")
+ || tlResolver.getTagURIForNodeName(element).trim()
+ .equalsIgnoreCase("http://java.sun.com/jsf/html")) {
+ return true;
+ }
+ } catch (Exception e) {
+ }
+ return false;
+ }
+
+ public static IRegion getBasenameRegion(IDocument document, int startPos) {
+ IRegion result = null;
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, startPos);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ if (curNode instanceof Element) {
+ final Element elem = (Element) curNode;
+ if (isBundleElement(elem, context)) {
+ Attr na = elem.getAttributeNode("basename");
+
+ if (na != null) {
+ int attrStart = document.get().indexOf("basename",
+ startPos);
+ result = new Region(document.get().indexOf(
+ na.getValue(), attrStart), na.getValue()
+ .length());
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static IRegion getElementAttrValueRegion(IDocument document,
+ String attribute, int startPos) {
+ IRegion result = null;
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, startPos);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ Node curNode = domResolver.getNode();
+ if (curNode instanceof Attr)
+ curNode = ((Attr) curNode).getOwnerElement();
+
+ // node must be an XML attribute
+ if (curNode instanceof Element) {
+ final Element elem = (Element) curNode;
+ Attr na = elem.getAttributeNode(attribute);
+
+ if (na != null && isJSFElement(elem, context)) {
+ int attrStart = document.get().indexOf(attribute, startPos);
+ result = new Region(document.get().indexOf(
+ na.getValue().trim(), attrStart), na.getValue()
+ .trim().length());
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static IRegion resolveResourceBundleRefPos(IDocument document,
+ String varName) {
+ String content = document.get();
+ IRegion region = null;
+ int offset = 0;
+
+ while (content.indexOf("\"" + varName + "\"", offset + 1) >= 0
+ || content.indexOf("'" + varName + "'", offset + 1) >= 0) {
+ offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
+ .indexOf("\"" + varName + "\"") : content.indexOf("'"
+ + varName + "'");
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ Attr attr = null;
+ if (curNode instanceof Attr) {
+ attr = (Attr) curNode;
+ if (!attr.getNodeName().toLowerCase().equals("var"))
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) attr.getOwnerElement();
+
+ if (!isBundleElement(parentElement, context))
+ continue;
+
+ String bundleId = parentElement.getAttribute("basename");
+
+ if (bundleId != null && bundleId.trim().length() > 0) {
+
+ while (region == null) {
+ int basename = content.indexOf("basename", offset);
+ int value = content.indexOf(bundleId,
+ content.indexOf("=", basename));
+ if (value > basename) {
+ region = new Region(value, bundleId.length());
+ }
+ }
+
+ }
+ break;
+ }
+ }
+
+ return region;
+ }
+
+ public static String resolveResourceBundleVariable(IDocument document,
+ String selectedResourceBundle) {
+ String content = document.get();
+ String variableName = null;
+ int offset = 0;
+
+ while (content
+ .indexOf("\"" + selectedResourceBundle + "\"", offset + 1) >= 0
+ || content.indexOf("'" + selectedResourceBundle + "'",
+ offset + 1) >= 0) {
+ offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content
+ .indexOf("\"" + selectedResourceBundle + "\"") : content
+ .indexOf("'" + selectedResourceBundle + "'");
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ Attr attr = null;
+ if (curNode instanceof Attr) {
+ attr = (Attr) curNode;
+ if (!attr.getNodeName().toLowerCase().equals("basename"))
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) attr.getOwnerElement();
+
+ if (!isBundleElement(parentElement, context))
+ continue;
+
+ variableName = parentElement.getAttribute("var");
+ break;
+ }
+ }
+
+ return variableName;
+ }
+
+ public static String resolveNewVariableName(IDocument document,
+ String selectedResourceBundle) {
+ String variableName = "";
+ int i = 0;
+ variableName = selectedResourceBundle.replace(".", "");
+ while (resolveResourceBundleId(document, variableName).trim().length() > 0) {
+ variableName = selectedResourceBundle + (i++);
+ }
+ return variableName;
+ }
+
+ public static void createResourceBundleRef(IDocument document,
+ String selectedResourceBundle, String variableName) {
+ String content = document.get();
+ int headInsertPos = -1;
+ int offset = 0;
+
+ while (content.indexOf("head", offset + 1) >= 0) {
+ offset = content.indexOf("head", offset + 1);
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ if (!(curNode instanceof Element)) {
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) curNode;
+
+ if (parentElement.getNodeName().equalsIgnoreCase("head")) {
+ do {
+ headInsertPos = content.indexOf("head", offset + 5);
+
+ final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolverHeadClose = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(contextHeadClose);
+ if (domResolverHeadClose.getNode() instanceof Element
+ && domResolverHeadClose.getNode().getNodeName()
+ .equalsIgnoreCase("head")) {
+ headInsertPos = content.substring(0, headInsertPos)
+ .lastIndexOf("<");
+ break;
+ }
+ } while (headInsertPos >= 0);
+
+ if (headInsertPos < 0) {
+ headInsertPos = content.indexOf(">", offset) + 1;
+ }
+
+ break;
+ }
+ }
+ }
+
+ // resolve the taglib
+ try {
+ int taglibPos = content.lastIndexOf("taglib");
+ if (taglibPos > 0) {
+ final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, taglibPos);
+ taglibPos = content.indexOf("%>", taglibPos);
+ if (taglibPos > 0) {
+ String decl = createLoadBundleDeclaration(document,
+ taglibContext, variableName, selectedResourceBundle);
+ if (headInsertPos > taglibPos)
+ document.replace(headInsertPos, 0, decl);
+ else
+ document.replace(taglibPos, 0, decl);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ private static String createLoadBundleDeclaration(IDocument document,
+ IStructuredDocumentContext context, String variableName,
+ String selectedResourceBundle) {
+ String bundleDecl = "";
+
+ // Retrieve jsf core namespace prefix
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+ String bundlePrefix = tlResolver
+ .getTagPrefixForURI("http://java.sun.com/jsf/core");
+
+ MessageFormat tlFormatter = new MessageFormat(
+ "<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n");
+ bundleDecl = tlFormatter.format(new String[] { bundlePrefix,
+ variableName, selectedResourceBundle });
+
+ return bundleDecl;
+ }
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
index 3bfd8d28..28debd95 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
@@ -1,53 +1,71 @@
-package auditor.model;
-
-import java.io.Serializable;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-
-
-public class SLLocation implements Serializable, ILocation {
-
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
-
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
- public IFile getFile() {
- return file;
- }
- public void setFile(IFile file) {
- this.file = file;
- }
- public int getStartPos() {
- return startPos;
- }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
- public int getEndPos() {
- return endPos;
- }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
- public String getLiteral() {
- return literal;
- }
- public Serializable getData () {
- return data;
- }
- public void setData (Serializable data) {
- this.data = data;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package auditor.model;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+public class SLLocation implements Serializable, ILocation {
+
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
+
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
+
+ public IFile getFile() {
+ return file;
+ }
+
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+
+ public int getStartPos() {
+ return startPos;
+ }
+
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+
+ public int getEndPos() {
+ return endPos;
+ }
+
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+
+ public String getLiteral() {
+ return literal;
+ }
+
+ public Serializable getData() {
+ return data;
+ }
+
+ public void setData(Serializable data) {
+ this.data = data;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
index fef0b2bd..50b1fd90 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
@@ -1,112 +1,129 @@
-package quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-
-import auditor.JSFResourceBundleDetector;
-
-public class ExportToResourceBundleResolution implements IMarkerResolution2 {
-
- public ExportToResourceBundleResolution() {
- }
-
- @Override
- public String getDescription() {
- return "Export constant string literal to a resource bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Export to Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell(),
- ResourceBundleManager.getManager(resource.getProject()),
- "",
- (startPos < document.getLength() && endPos > 1) ? document
- .get(startPos, endPos) : "", "", "");
- if (dialog.open() != InputDialog.OK)
- return;
-
- /** Check for an existing resource bundle reference **/
- String bundleVar = JSFResourceBundleDetector
- .resolveResourceBundleVariable(document,
- dialog.getSelectedResourceBundle());
-
- boolean requiresNewReference = false;
- if (bundleVar == null) {
- requiresNewReference = true;
- bundleVar = JSFResourceBundleDetector.resolveNewVariableName(
- document, dialog.getSelectedResourceBundle());
- }
-
- // insert resource reference
- String key = dialog.getSelectedKey();
-
- if (key.indexOf(".") >= 0) {
- int quoteDblIdx = document.get().substring(0, startPos)
- .lastIndexOf("\"");
- int quoteSingleIdx = document.get().substring(0, startPos)
- .lastIndexOf("'");
- String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
-
- document.replace(startPos, endPos, "#{" + bundleVar + "["
- + quoteSign + key + quoteSign + "]}");
- } else {
- document.replace(startPos, endPos, "#{" + bundleVar + "." + key
- + "}");
- }
-
- if (requiresNewReference) {
- JSFResourceBundleDetector.createResourceBundleRef(document,
- dialog.getSelectedResourceBundle(), bundleVar);
- }
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the 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 quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+import auditor.JSFResourceBundleDetector;
+
+public class ExportToResourceBundleResolution implements IMarkerResolution2 {
+
+ public ExportToResourceBundleResolution() {
+ }
+
+ @Override
+ public String getDescription() {
+ return "Export constant string literal to a resource bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Export to Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey("");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document
+ .get(startPos, endPos) : "");
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ /** Check for an existing resource bundle reference **/
+ String bundleVar = JSFResourceBundleDetector
+ .resolveResourceBundleVariable(document,
+ dialog.getSelectedResourceBundle());
+
+ boolean requiresNewReference = false;
+ if (bundleVar == null) {
+ requiresNewReference = true;
+ bundleVar = JSFResourceBundleDetector.resolveNewVariableName(
+ document, dialog.getSelectedResourceBundle());
+ }
+
+ // insert resource reference
+ String key = dialog.getSelectedKey();
+
+ if (key.indexOf(".") >= 0) {
+ int quoteDblIdx = document.get().substring(0, startPos)
+ .lastIndexOf("\"");
+ int quoteSingleIdx = document.get().substring(0, startPos)
+ .lastIndexOf("'");
+ String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
+
+ document.replace(startPos, endPos, "#{" + bundleVar + "["
+ + quoteSign + key + quoteSign + "]}");
+ } else {
+ document.replace(startPos, endPos, "#{" + bundleVar + "." + key
+ + "}");
+ }
+
+ if (requiresNewReference) {
+ JSFResourceBundleDetector.createResourceBundleRef(document,
+ dialog.getSelectedResourceBundle(), bundleVar);
+ }
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
index 7618d69d..d98ba32f 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
@@ -1,16 +1,26 @@
-package quickfix;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolutionGenerator;
-
-public class JSFViolationResolutionGenerator implements
- IMarkerResolutionGenerator {
-
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package quickfix;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.ui.IMarkerResolution;
+import org.eclipse.ui.IMarkerResolutionGenerator;
+
+public class JSFViolationResolutionGenerator implements
+ IMarkerResolutionGenerator {
+
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
index 7fa8c32b..79fbf52b 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
@@ -1,83 +1,94 @@
-package quickfix;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
-
-
-public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
-
- private String key;
- private int start;
- private int end;
-
- public ReplaceResourceBundleDefReference(String key, int start, int end) {
- this.key = key;
- this.start = start;
- this.end = end;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle reference '"
- + key
- + "' with a reference to an already existing Resource-Bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select an alternative Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = start;
- int endPos = end-start;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
- resource.getProject());
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- key = dialog.getSelectedBundleId();
-
- document.replace(startPos, endPos, key);
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
+
+ private String key;
+ private int start;
+ private int end;
+
+ public ReplaceResourceBundleDefReference(String key, int start, int end) {
+ this.key = key;
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle reference '" + key
+ + "' with a reference to an already existing Resource-Bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select an alternative Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = start;
+ int endPos = end - start;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(
+ Display.getDefault().getActiveShell(),
+ resource.getProject());
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ key = dialog.getSelectedBundleId();
+
+ document.replace(startPos, endPos, key);
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
index 0e3d98f4..edd8e11f 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
@@ -1,104 +1,115 @@
-package quickfix;
-
-import java.util.Locale;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
-
-import auditor.JSFResourceBundleDetector;
-
-public class ReplaceResourceBundleReference implements IMarkerResolution2 {
-
- private String key;
- private String bundleId;
-
- public ReplaceResourceBundleReference(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle key '"
- + key
- + "' with a reference to an already existing localized string literal.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select alternative Resource-Bundle entry";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell(),
- ResourceBundleManager.getManager(resource.getProject()),
- bundleId);
- if (dialog.open() != InputDialog.OK)
- return;
-
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
-
- String jsfBundleVar = JSFResourceBundleDetector
- .getBundleVariableName(document.get().substring(startPos,
- startPos + endPos));
-
- if (key.indexOf(".") >= 0) {
- int quoteDblIdx = document.get().substring(0, startPos)
- .lastIndexOf("\"");
- int quoteSingleIdx = document.get().substring(0, startPos)
- .lastIndexOf("'");
- String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
-
- document.replace(startPos, endPos, jsfBundleVar + "["
- + quoteSign + key + quoteSign + "]");
- } else {
- document.replace(startPos, endPos, jsfBundleVar + "." + key);
- }
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package quickfix;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+import auditor.JSFResourceBundleDetector;
+
+public class ReplaceResourceBundleReference implements IMarkerResolution2 {
+
+ private String key;
+ private String bundleId;
+
+ public ReplaceResourceBundleReference(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle key '"
+ + key
+ + "' with a reference to an already existing localized string literal.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select alternative Resource-Bundle entry";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+
+ dialog.setProjectName(resource.getProject().getName());
+ dialog.setBundleName(bundleId);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
+
+ String jsfBundleVar = JSFResourceBundleDetector
+ .getBundleVariableName(document.get().substring(startPos,
+ startPos + endPos));
+
+ if (key.indexOf(".") >= 0) {
+ int quoteDblIdx = document.get().substring(0, startPos)
+ .lastIndexOf("\"");
+ int quoteSingleIdx = document.get().substring(0, startPos)
+ .lastIndexOf("'");
+ String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
+
+ document.replace(startPos, endPos, jsfBundleVar + "["
+ + quoteSign + key + quoteSign + "]");
+ } else {
+ document.replace(startPos, endPos, jsfBundleVar + "." + key);
+ }
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
index 4a18f152..d4db565d 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
@@ -1,63 +1,78 @@
-package ui;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-
-import util.ELUtils;
-import auditor.JSFResourceBundleDetector;
-
-/**
- * This class creates hovers for ISymbols in an el expression that have a
- * detailedDescription.
- */
-public class JSFELMessageHover implements ITextHover {
-
- private String expressionValue = "";
- private IProject project = null;
-
- public final String getHoverInfo(final ITextViewer textViewer,
- final IRegion hoverRegion) {
- String bundleName = JSFResourceBundleDetector.resolveResourceBundleId(textViewer.getDocument(),
- JSFResourceBundleDetector.getBundleVariableName(expressionValue));
- String resourceKey = JSFResourceBundleDetector.getResourceKey(expressionValue);
-
- return ELUtils.getResource (project, bundleName, resourceKey);
- }
-
- public final IRegion getHoverRegion(final ITextViewer textViewer,
- final int documentPosition) {
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(textViewer, documentPosition);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
- project = workspaceResolver.getProject();
-
- if (project != null) {
- if (!InternationalizationNature.hasNature(project))
- return null;
- } else
- return null;
-
- final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTextRegionResolver(context);
-
- if (!symbolResolver.getRegionType().equals(DOMJSPRegionContexts.JSP_VBL_CONTENT))
- return null;
- expressionValue = symbolResolver.getRegionText();
-
- return new Region (symbolResolver.getStartOffset(), symbolResolver.getLength());
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package ui;
+
+import org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextHover;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts;
+
+import util.ELUtils;
+import auditor.JSFResourceBundleDetector;
+
+/**
+ * This class creates hovers for ISymbols in an el expression that have a
+ * detailedDescription.
+ */
+public class JSFELMessageHover implements ITextHover {
+
+ private String expressionValue = "";
+ private IProject project = null;
+
+ public final String getHoverInfo(final ITextViewer textViewer,
+ final IRegion hoverRegion) {
+ String bundleName = JSFResourceBundleDetector.resolveResourceBundleId(
+ textViewer.getDocument(), JSFResourceBundleDetector
+ .getBundleVariableName(expressionValue));
+ String resourceKey = JSFResourceBundleDetector
+ .getResourceKey(expressionValue);
+
+ return ELUtils.getResource(project, bundleName, resourceKey);
+ }
+
+ public final IRegion getHoverRegion(final ITextViewer textViewer,
+ final int documentPosition) {
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(textViewer, documentPosition);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
+
+ project = workspaceResolver.getProject();
+
+ if (project != null) {
+ if (!InternationalizationNature.hasNature(project))
+ return null;
+ } else
+ return null;
+
+ final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTextRegionResolver(context);
+
+ if (!symbolResolver.getRegionType().equals(
+ DOMJSPRegionContexts.JSP_VBL_CONTENT))
+ return null;
+ expressionValue = symbolResolver.getRegionText();
+
+ return new Region(symbolResolver.getStartOffset(),
+ symbolResolver.getLength());
+
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
index 5afd59d0..0ddcd6ea 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
@@ -1,149 +1,161 @@
-package ui.autocompletion;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Node;
-
-
-public class BundleNameProposal implements IContentAssistProcessor {
-
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(viewer, offset);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
- IProject project = workspaceResolver.getProject();
- IResource resource = workspaceResolver.getResource();
-
- if (project != null) {
- if (!InternationalizationNature.hasNature(project))
- return proposals.toArray(new ICompletionProposal[proposals
- .size()]);
- } else
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
-
- addBundleProposals(proposals, context, offset, viewer.getDocument(),
- resource);
-
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- private void addBundleProposals(List<ICompletionProposal> proposals,
- final IStructuredDocumentContext context,
- int startPos,
- IDocument document,
- IResource resource) {
- final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getTextRegionResolver(context);
-
- if (resolver != null) {
- final String regionType = resolver.getRegionType();
- startPos = resolver.getStartOffset()+1;
-
- if (regionType != null
- && regionType
- .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
-
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getTaglibContextResolver(context);
-
- if (tlResolver != null) {
- Attr attr = getAttribute(context);
- String startString = attr.getValue();
-
- int length = startString.length();
-
- if (attr != null) {
- Node tagElement = attr.getOwnerElement();
- if (tagElement == null)
- return;
-
- String nodeName = tagElement.getNodeName();
- if (nodeName.substring(nodeName.indexOf(":")+1).toLowerCase().equals("loadbundle")) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
- for (String id : manager.getResourceBundleIdentifiers()) {
- if (id.startsWith(startString) && id.length() != startString.length()) {
- proposals.add(new ui.autocompletion.MessageCompletionProposal(
- startPos, length, id, true));
- }
- }
- }
- }
- }
- }
- }
- }
-
- private Attr getAttribute(IStructuredDocumentContext context) {
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- if (curNode instanceof Attr) {
- return (Attr) curNode;
- }
- }
- return null;
-
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package ui.autocompletion;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.text.contentassist.IContextInformationValidator;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Node;
+
+public class BundleNameProposal implements IContentAssistProcessor {
+
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(viewer, offset);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
+
+ IProject project = workspaceResolver.getProject();
+ IResource resource = workspaceResolver.getResource();
+
+ if (project != null) {
+ if (!InternationalizationNature.hasNature(project))
+ return proposals.toArray(new ICompletionProposal[proposals
+ .size()]);
+ } else
+ return proposals.toArray(new ICompletionProposal[proposals.size()]);
+
+ addBundleProposals(proposals, context, offset, viewer.getDocument(),
+ resource);
+
+ return proposals.toArray(new ICompletionProposal[proposals.size()]);
+ }
+
+ private void addBundleProposals(List<ICompletionProposal> proposals,
+ final IStructuredDocumentContext context, int startPos,
+ IDocument document, IResource resource) {
+ final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTextRegionResolver(context);
+
+ if (resolver != null) {
+ final String regionType = resolver.getRegionType();
+ startPos = resolver.getStartOffset() + 1;
+
+ if (regionType != null
+ && regionType
+ .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
+
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+
+ if (tlResolver != null) {
+ Attr attr = getAttribute(context);
+ String startString = attr.getValue();
+
+ int length = startString.length();
+
+ if (attr != null) {
+ Node tagElement = attr.getOwnerElement();
+ if (tagElement == null)
+ return;
+
+ String nodeName = tagElement.getNodeName();
+ if (nodeName.substring(nodeName.indexOf(":") + 1)
+ .toLowerCase().equals("loadbundle")) {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(resource.getProject());
+ for (String id : manager
+ .getResourceBundleIdentifiers()) {
+ if (id.startsWith(startString)
+ && id.length() != startString.length()) {
+ proposals
+ .add(new ui.autocompletion.MessageCompletionProposal(
+ startPos, length, id, true));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private Attr getAttribute(IStructuredDocumentContext context) {
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ if (curNode instanceof Attr) {
+ return (Attr) curNode;
+ }
+ }
+ return null;
+
+ }
+
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
index 7c43856d..309f561f 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
@@ -1,71 +1,82 @@
-package ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-
-
-public class MessageCompletionProposal implements IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private String content = "";
- private boolean messageAccessor = false;
-
- public MessageCompletionProposal (int offset, int length, String content, boolean messageAccessor) {
- this.offset = offset;
- this.length = length;
- this.content = content;
- this.messageAccessor = messageAccessor;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- document.replace(offset, length, content);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return "Inserts the property key '" + content + "' of the resource-bundle 'at.test.messages'";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return content;
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- if (messageAccessor)
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return new Point (offset+content.length()+1, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- return 99;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.ui.utils.ImageUtils;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+
+public class MessageCompletionProposal implements IJavaCompletionProposal {
+
+ private int offset = 0;
+ private int length = 0;
+ private String content = "";
+ private boolean messageAccessor = false;
+
+ public MessageCompletionProposal(int offset, int length, String content,
+ boolean messageAccessor) {
+ this.offset = offset;
+ this.length = length;
+ this.content = content;
+ this.messageAccessor = messageAccessor;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ try {
+ document.replace(offset, length, content);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ // TODO Auto-generated method stub
+ return "Inserts the property key '" + content
+ + "' of the resource-bundle 'at.test.messages'";
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ return content;
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ if (messageAccessor)
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ // TODO Auto-generated method stub
+ return new Point(offset + content.length() + 1, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ return 99;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
index 401a67ab..c61fafcb 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -1,115 +1,132 @@
-package ui.autocompletion;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-
-
-public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
-
- private int startPos;
- private int endPos;
- private String value;
- private ResourceBundleManager manager;
- private IResource resource;
- private String bundleName;
- private String reference;
- private boolean isKey;
-
- public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos,
- ResourceBundleManager manager, String bundleName, boolean isKey) {
- this.startPos = startPos;
- this.endPos = endPos;
- this.manager = manager;
- this.value = str;
- this.resource = resource;
- this.bundleName = bundleName;
- this.isKey = isKey;
- }
-
- @Override
- public void apply(IDocument document) {
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell(),
- manager,
- isKey ? value : "",
- !isKey ? value : "",
- bundleName == null ? "" : bundleName,
- "");
- if (dialog.open() != InputDialog.OK)
- return;
-
-
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedKey();
-
- try {
- document.replace(startPos, endPos, key);
- reference = key + "\"";
- ResourceBundleManager.refreshResource(resource);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return "Creates a new string literal within one of the" +
- " project's resource bundles. This action results " +
- "in a reference to the localized string literal!";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- String displayStr = "";
-
- displayStr = "Create a new localized string literal";
-
- if (this.isKey) {
- if (value != null && value.length() > 0)
- displayStr += " with the key '" + value + "'";
- } else {
- if (value != null && value.length() > 0)
- displayStr += " for '" + value + "'";
- }
- return displayStr;
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return new Point (startPos + reference.length()-1, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- if (this.value.trim().length() == 0)
- return 1096;
- else
- return 1096;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
+
+ private int startPos;
+ private int endPos;
+ private String value;
+ private ResourceBundleManager manager;
+ private IResource resource;
+ private String bundleName;
+ private String reference;
+ private boolean isKey;
+
+ public NewResourceBundleEntryProposal(IResource resource, String str,
+ int startPos, int endPos, ResourceBundleManager manager,
+ String bundleName, boolean isKey) {
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.manager = manager;
+ this.value = str;
+ this.resource = resource;
+ this.bundleName = bundleName;
+ this.isKey = isKey;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(isKey ? value : "");
+ config.setPreselectedMessage(!isKey ? value : "");
+ config.setPreselectedBundle(bundleName == null ? "" : bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedKey();
+
+ try {
+ document.replace(startPos, endPos, key);
+ reference = key + "\"";
+ ResourceBundleManager.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;
+ }
+
+ @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 e44a2c63..32559141 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
@@ -1,111 +1,125 @@
-package ui.autocompletion.jsf;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.CompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-import ui.autocompletion.NewResourceBundleEntryProposal;
-import auditor.JSFResourceBundleDetector;
-
-public class MessageCompletionProposal implements IContentAssistProcessor {
-
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List <ICompletionProposal> proposals = new ArrayList<ICompletionProposal> ();
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(viewer, offset);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
- IProject project = workspaceResolver.getProject();
- IResource resource = workspaceResolver.getResource();
-
- if (project != null) {
- if (!InternationalizationNature.hasNature(project))
- return proposals.toArray(new CompletionProposal[proposals.size()]);
- } else
- return proposals.toArray(new CompletionProposal[proposals.size()]);
-
- // Compute proposals
- String expression = getProposalPrefix (viewer.getDocument(), offset);
- String bundleId = JSFResourceBundleDetector.resolveResourceBundleId(viewer.getDocument(),
- JSFResourceBundleDetector.getBundleVariableName(expression));
- String key = JSFResourceBundleDetector.getResourceKey(expression);
-
- if (expression.trim().length() > 0 &&
- bundleId.trim().length() > 0 &&
- isNonExistingKey (project, bundleId, key)) {
- // Add 'New Resource' proposal
- int startpos = offset - key.length();
- int length = key.length();
-
- proposals.add(new NewResourceBundleEntryProposal(resource, key, startpos, length, ResourceBundleManager.getManager(project)
- , bundleId, true));
- }
-
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- private String getProposalPrefix(IDocument document, int offset) {
- String content = document.get().substring(0, offset);
- int expIntro = content.lastIndexOf("#{");
-
- return content.substring(expIntro+2, offset);
- }
-
- protected boolean isNonExistingKey (IProject project, String bundleId, String key) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
-
- return !manager.isResourceExisting(bundleId, key);
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package ui.autocompletion.jsf;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.builder.InternationalizationNature;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.contentassist.CompletionProposal;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.text.contentassist.IContextInformationValidator;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+
+import ui.autocompletion.NewResourceBundleEntryProposal;
+import auditor.JSFResourceBundleDetector;
+
+public class MessageCompletionProposal implements IContentAssistProcessor {
+
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(viewer, offset);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
+
+ IProject project = workspaceResolver.getProject();
+ IResource resource = workspaceResolver.getResource();
+
+ if (project != null) {
+ if (!InternationalizationNature.hasNature(project))
+ return proposals.toArray(new CompletionProposal[proposals
+ .size()]);
+ } else
+ return proposals.toArray(new CompletionProposal[proposals.size()]);
+
+ // Compute proposals
+ String expression = getProposalPrefix(viewer.getDocument(), offset);
+ String bundleId = JSFResourceBundleDetector.resolveResourceBundleId(
+ viewer.getDocument(),
+ JSFResourceBundleDetector.getBundleVariableName(expression));
+ String key = JSFResourceBundleDetector.getResourceKey(expression);
+
+ if (expression.trim().length() > 0 && bundleId.trim().length() > 0
+ && isNonExistingKey(project, bundleId, key)) {
+ // Add 'New Resource' proposal
+ int startpos = offset - key.length();
+ int length = key.length();
+
+ proposals.add(new NewResourceBundleEntryProposal(resource, key,
+ startpos, length,
+ ResourceBundleManager.getManager(project), bundleId, true));
+ }
+
+ return proposals.toArray(new ICompletionProposal[proposals.size()]);
+ }
+
+ private String getProposalPrefix(IDocument document, int offset) {
+ String content = document.get().substring(0, offset);
+ int expIntro = content.lastIndexOf("#{");
+
+ return content.substring(expIntro + 2, offset);
+ }
+
+ protected boolean isNonExistingKey(IProject project, String bundleId,
+ String key) {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(project);
+
+ return !manager.isResourceExisting(bundleId, key);
+ }
+
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
index 09b6f211..cdfcc46d 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
@@ -1,16 +1,27 @@
-package util;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-
-public class ELUtils {
-
- public static String getResource (IProject project, String bundleName, String key) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
- if (manager.isResourceExisting(bundleName, key))
- return manager.getKeyHoverString(bundleName, key);
- else
- return null;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package util;
+
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.core.resources.IProject;
+
+public class ELUtils {
+
+ public static String getResource(IProject project, String bundleName,
+ String key) {
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(project);
+ if (manager.isResourceExisting(bundleName, key))
+ return manager.getKeyHoverString(bundleName, key);
+ else
+ return null;
+ }
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
index 07d06586..02b5f6e8 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
@@ -1,199 +1,212 @@
-package validator;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator;
-import org.eclipse.wst.validation.internal.core.ValidationException;
-import org.eclipse.wst.validation.internal.provisional.core.IReporter;
-import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
-import org.eclipse.wst.validation.internal.provisional.core.IValidator;
-import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-
-import auditor.JSFResourceBundleDetector;
-import auditor.model.SLLocation;
-
-public class JSFInternationalizationValidator implements IValidator, ISourceValidator {
-
- private IDocument document;
-
- @Override
- public void cleanup(IReporter reporter) {
- }
-
- @Override
- public void validate(IValidationContext context, IReporter reporter)
- throws ValidationException {
- if (context.getURIs().length > 0) {
- IFile file = ResourcesPlugin.getWorkspace().getRoot()
- .getFile(new Path(context.getURIs()[0]));
-
- // full document validation
- EditorUtils.deleteAuditMarkersForResource(file.getProject()
- .findMember(file.getProjectRelativePath()));
-
- // validate all bundle definitions
- int pos = document.get().indexOf("loadBundle", 0);
- while (pos >= 0) {
- validateRegion(new Region(pos, 1), context, reporter);
- pos = document.get().indexOf("loadBundle", pos + 1);
- }
-
- // iterate all value definitions
- pos = document.get().indexOf(" value", 0);
- while (pos >= 0) {
- validateRegion(new Region(pos, 1), context, reporter);
- pos = document.get().indexOf(" value", pos + 1);
- }
- }
- }
-
- @Override
- public void connect(IDocument doc) {
- document = doc;
- }
-
- @Override
- public void disconnect(IDocument arg0) {
- document = null;
- }
-
- public void validateRegion(IRegion dirtyRegion, IValidationContext context,
- IReporter reporter) {
- int startPos = dirtyRegion.getOffset();
- int endPos = dirtyRegion.getOffset() + dirtyRegion.getLength();
-
- if (context.getURIs().length > 0) {
- IFile file = ResourcesPlugin.getWorkspace().getRoot()
- .getFile(new Path(context.getURIs()[0]));
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(file.getProject());
-
- String bundleName = JSFResourceBundleDetector
- .resolveResourceBundleRefIdentifier(document, startPos);
- if (bundleName != null
- && !manager.getResourceBundleIdentifiers().contains(
- bundleName)) {
- IRegion reg = JSFResourceBundleDetector.getBasenameRegion(
- document, startPos);
- String ref = document.get().substring(reg.getOffset(),
- reg.getOffset() + reg.getLength());
-
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
- new String[] { ref }),
- new SLLocation(file, reg.getOffset(), reg
- .getOffset() + reg.getLength(), ref),
- IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
- ref, null, "jsf");
- return;
- }
-
- IRegion evr = JSFResourceBundleDetector.getElementAttrValueRegion(
- document, "value", startPos);
- if (evr != null) {
- String elementValue = document.get().substring(evr.getOffset(),
- evr.getOffset() + evr.getLength());
-
- // check all constant string expressions
- List<IRegion> regions = JSFResourceBundleDetector
- .getNonELValueRegions(elementValue);
-
- for (IRegion region : regions) {
- // report constant string literals
- String constantLiteral = elementValue.substring(
- region.getOffset(),
- region.getOffset() + region.getLength());
-
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
- new String[] { constantLiteral }),
- new SLLocation(file, region.getOffset()
- + evr.getOffset(), evr.getOffset()
- + region.getOffset()
- + region.getLength(),
- constantLiteral),
- IMarkerConstants.CAUSE_CONSTANT_LITERAL,
- constantLiteral, null,
- "jsf");
- }
-
- // check el expressions
- int start = document.get().indexOf("#{", evr.getOffset());
-
- while (start >= 0 && start < evr.getOffset() + evr.getLength()) {
- int end = document.get().indexOf("}", start);
- end = Math.min(end, evr.getOffset() + evr.getLength());
-
- if ((end - start) > 6) {
- String def = document.get().substring(start + 2, end);
- String varName = JSFResourceBundleDetector
- .getBundleVariableName(def);
- String key = JSFResourceBundleDetector
- .getResourceKey(def);
- if (varName != null && key != null) {
- if (varName.length() > 0) {
- IRegion refReg = JSFResourceBundleDetector
- .resolveResourceBundleRefPos(document,
- varName);
-
- if (refReg == null) {
- start = document.get().indexOf("#{", end);
- continue;
- }
-
- int bundleStart = refReg.getOffset();
- int bundleEnd = refReg.getOffset()
- + refReg.getLength();
-
- if (manager.isKeyBroken(
- document.get().substring(
- refReg.getOffset(),
- refReg.getOffset()
- + refReg.getLength()),
- key)) {
- SLLocation subMarker = new SLLocation(file,
- bundleStart, bundleEnd, document
- .get().substring(
- bundleStart,
- bundleEnd));
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
- new String[] { key, subMarker.getLiteral() }),
- new SLLocation(file,
- start+2, end, key),
- IMarkerConstants.CAUSE_BROKEN_REFERENCE,
- key,
- subMarker,
- "jsf");
- }
- }
- }
- }
-
- start = document.get().indexOf("#{", end);
- }
- }
- }
- }
-
- @Override
- public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) {}
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package validator;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator;
+import org.eclipse.wst.validation.internal.core.ValidationException;
+import org.eclipse.wst.validation.internal.provisional.core.IReporter;
+import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
+import org.eclipse.wst.validation.internal.provisional.core.IValidator;
+
+import auditor.JSFResourceBundleDetector;
+import auditor.model.SLLocation;
+
+public class JSFInternationalizationValidator implements IValidator,
+ ISourceValidator {
+
+ private IDocument document;
+
+ @Override
+ public void cleanup(IReporter reporter) {
+ }
+
+ @Override
+ public void validate(IValidationContext context, IReporter reporter)
+ throws ValidationException {
+ if (context.getURIs().length > 0) {
+ IFile file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFile(new Path(context.getURIs()[0]));
+
+ // full document validation
+ 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");
+ }
+
+ // 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);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) {
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/.project b/org.eclipselabs.tapiji.tools.rbmanager/.project
deleted file mode 100644
index 91150033..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.tools.rbmanager</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF
deleted file mode 100644
index 6d2e34fc..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,16 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Manager
-Bundle-SymbolicName: org.eclipselabs.tapiji.tools.rbmanager;singleton:=true
-Bundle-Version: 0.0.2.qualifier
-Bundle-Activator: org.eclipselabs.tapiji.tools.rbmanager.RBManagerActivator
-Bundle-Vendor: GKNSINTERMETALS
-Require-Bundle: org.eclipse.core.runtime,
- org.eclipse.core.resources;bundle-version="3.6",
- org.eclipse.ui,
- org.eclipse.ui.ide;bundle-version="3.6.0",
- org.eclipse.ui.navigator;bundle-version="3.5",
- org.eclipselabs.tapiji.tools.core;bundle-version="0.0.2"
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Bundle-ActivationPolicy: lazy
-Import-Package: org.eclipselabs.tapiji.translator.rbe.babel.bundle
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/plugin.xml b/org.eclipselabs.tapiji.tools.rbmanager/plugin.xml
deleted file mode 100644
index 54767f5e..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/plugin.xml
+++ /dev/null
@@ -1,197 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.views">
- <view
- category="org.eclipselabs.tapiji"
- class="org.eclipse.ui.navigator.CommonNavigator"
- icon="icons/resourcebundle.gif"
- id="org.eclipselabs.tapiji.tools.rbmanager.ResourceBundleExplorer"
- name="Resource Bundle Explorer"
- restorable="true">
- </view>
- </extension>
- <extension
- point="org.eclipse.ui.viewActions">
- <viewContribution
- id="org.eclipselabs.tapiji.tools.rbmanager.viewContribution1"
- targetID="org.eclipselabs.tapiji.tools.rbmanager.ResourceBundleExplorer">
- <action
- class="org.eclipselabs.tapiji.tools.rbmanager.ui.view.toolbarItems.ToggleFilterActionDelegate"
- icon="icons/warning.gif"
- id="org.eclipselabs.tapiji.tools.rbmanager.activateFilter"
- label="Filter Problematic ResourceBundles"
- state="false"
- style="toggle"
- toolbarPath="additions"
- tooltip="Filters ResourceBundles With Warnings">
- </action>
- </viewContribution>
- <viewContribution
- id="org.eclipselabs.tapiji.tools.rbmanager.viewContribution2"
- targetID="org.eclipselabs.tapiji.tools.rbmanager.ResourceBundleExplorer">
- <action
- class="org.eclipselabs.tapiji.tools.rbmanager.ui.view.toolbarItems.ExpandAllActionDelegate"
- icon="icons/expandall.gif"
- id="org.eclipselabs.tapiji.tools.rbmanager.expandAll"
- label="Expand All"
- style="push"
- toolbarPath="additions">
- </action>
- </viewContribution>
- </extension>
- <extension
- point="org.eclipse.ui.navigator.viewer">
- <viewerContentBinding
- viewerId="org.eclipselabs.tapiji.tools.rbmanager.ResourceBundleExplorer">
- <includes>
- <contentExtension
- pattern="org.eclipselabs.tapiji.tools.rbmanager.resourcebundleContent">
- </contentExtension>
- <contentExtension
- pattern="org.eclipselabs.tapiji.tools.rbmanager.filter.*">
- </contentExtension>
- <contentExtension
- pattern="org.eclipse.ui.navigator.resources.filters.*">
- </contentExtension>
- <contentExtension
- pattern="org.eclipselabs.tapiji.tools.rbmanager.linkHelper">
- </contentExtension>
- </includes>
- </viewerContentBinding>
- <viewerActionBinding
- viewerId="org.eclipselabs.tapiji.tools.rbmanager.ResourceBundleExplorer">
- <includes>
- <actionExtension
- pattern="org.eclipse.ui.navigator.resources.*">
- </actionExtension>
- </includes>
- </viewerActionBinding>
- <viewer
- viewerId="org.eclipselabs.tapiji.tools.rbmanager.ResourceBundleExplorer">
- <popupMenu>
- <insertionPoint
- name="group.new">
- </insertionPoint>
- <insertionPoint
- name="group.open">
- </insertionPoint>
- <insertionPoint
- name="group.openWith">
- </insertionPoint>
- <insertionPoint
- name="group.edit">
- </insertionPoint>
- <insertionPoint
- name="expand">
- </insertionPoint>
- <insertionPoint
- name="group.port">
- </insertionPoint>
- <insertionPoint
- name="group.reorgnize">
- </insertionPoint>
- <insertionPoint
- name="group.build">
- </insertionPoint>
- <insertionPoint
- name="group.search">
- </insertionPoint>
- <insertionPoint
- name="additions">
- </insertionPoint>
- <insertionPoint
- name="group.properties">
- </insertionPoint>
- </popupMenu>
- </viewer>
- </extension>
- <extension
- point="org.eclipse.ui.navigator.navigatorContent">
- <navigatorContent
- contentProvider="org.eclipselabs.tapiji.tools.rbmanager.viewer.ResourceBundleContentProvider"
- icon="icons/resourcebundle.gif"
- id="org.eclipselabs.tapiji.tools.rbmanager.resourcebundleContent"
- labelProvider="org.eclipselabs.tapiji.tools.rbmanager.viewer.ResourceBundleLabelProvider"
- name="Resource Bundle Content"
- priority="high">
- <triggerPoints>
- <or>
- <instanceof
- value="org.eclipse.core.resources.IWorkspaceRoot">
- </instanceof>
- <instanceof
- value="org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle">
- </instanceof>
- <instanceof
- value="org.eclipse.core.resources.IContainer">
- </instanceof>
- <instanceof
- value="org.eclipse.core.resources.IProject">
- </instanceof>
- </or>
- </triggerPoints>
- <possibleChildren>
- <or>
- <instanceof
- value="org.eclipse.core.resources.IContainer">
- </instanceof>
- <instanceof
- value="org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle">
- </instanceof>
- <and>
- <instanceof
- value="org.eclipse.core.resources.IFile">
- </instanceof>
- <test
- property="org.eclipse.core.resources.extension"
- value="properties">
- </test>
- </and>
- </or></possibleChildren>
- <actionProvider
- class="org.eclipselabs.tapiji.tools.rbmanager.viewer.actions.VirtualRBActionProvider"
- id="org.eclipselabs.tapiji.tools.rbmanager.action.openProvider">
- <enablement>
- <instanceof
- value="org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle">
- </instanceof>
- </enablement>
- </actionProvider>
- <actionProvider
- class="org.eclipselabs.tapiji.tools.rbmanager.viewer.actions.GeneralActionProvider"
- id="org.eclipselabs.tapiji.tools.rbmanager.action.general">
- </actionProvider>
- </navigatorContent>
- </extension>
- <extension
- point="org.eclipse.ui.navigator.navigatorContent">
- <commonFilter
- activeByDefault="false"
- class="org.eclipselabs.tapiji.tools.rbmanager.viewer.filters.ProblematicResourceBundleFilter"
- id="org.eclipselabs.tapiji.tools.rbmanager.filter.ProblematicResourceBundleFiles"
- name="Problematic Resource Bundle Files">
- </commonFilter>
- </extension>
- <extension
- point="org.eclipse.ui.navigator.linkHelper">
- <linkHelper
- class="org.eclipselabs.tapiji.tools.rbmanager.viewer.LinkHelper"
- id="org.eclipselabs.tapiji.tools.rbmanager.linkHelper">
- <selectionEnablement>
- <instanceof value="org.eclipse.core.resources.IFile"/>
- </selectionEnablement>
- <editorInputEnablement>
- <instanceof value="org.eclipse.ui.IFileEditorInput"/>
- </editorInputEnablement>
- </linkHelper>
- </extension>
- <extension
- point="org.eclipselabs.tapiji.tools.core.builderExtension">
- <i18nAuditor
- class="org.eclipselabs.tapiji.tools.rbmanager.auditor.ResourceBundleAuditor">
- </i18nAuditor>
- </extension>
-
-</plugin>
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ImageUtils.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ImageUtils.java
deleted file mode 100644
index 7d9103c9..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ImageUtils.java
+++ /dev/null
@@ -1,101 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager;
-
-import java.io.File;
-import java.net.URISyntaxException;
-import java.util.Locale;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.tools.core.util.OverlayIcon;
-
-public class ImageUtils {
- private static final ImageRegistry imageRegistry = new ImageRegistry();
-
- private static final String WARNING_FLAG_IMAGE = "warning_flag.gif";
- private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif";
- public static final String WARNING_IMAGE = "warning.gif";
- public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif";
- public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif";
- public static final String EXPAND = "expand.gif";
- public static final String DEFAULT_LOCALICON = File.separatorChar+"countries"+File.separatorChar+"_f.gif";
- public static final String LOCATION_WITHOUT_ICON = File.separatorChar+"countries"+File.separatorChar+"un.gif";
-
- /**
- * @return a Image from the folder 'icons'
- * @throws URISyntaxException
- */
- public static Image getBaseImage(String imageName){
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- ImageDescriptor descriptor = RBManagerActivator.getImageDescriptor(imageName);
-
- if (descriptor.getImageData() != null){
- image = descriptor.createImage(false);
- imageRegistry.put(imageName, image);
- }
- }
-
- return image;
- }
-
- /**
- * @param baseImage
- * @return baseImage with a overlay warning-image
- */
- public static Image getImageWithWarning(Image baseImage){
- String imageWithWarningId = baseImage.toString()+".w";
- Image imageWithWarning = imageRegistry.get(imageWithWarningId);
-
- if (imageWithWarning==null){
- Image warningImage = getBaseImage(WARNING_FLAG_IMAGE);
- imageWithWarning = new OverlayIcon(baseImage, warningImage, OverlayIcon.BOTTOM_LEFT).createImage();
- imageRegistry.put(imageWithWarningId, imageWithWarning);
- }
-
- return imageWithWarning;
- }
-
- /**
- *
- * @param baseImage
- * @return baseImage with a overlay fragment-image
- */
- public static Image getImageWithFragment(Image baseImage){
- String imageWithFragmentId = baseImage.toString()+".f";
- Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
-
- if (imageWithFragment==null){
- Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
- imageWithFragment = new OverlayIcon(baseImage, fragement, OverlayIcon.BOTTOM_RIGHT).createImage();
- imageRegistry.put(imageWithFragmentId, imageWithFragment);
- }
-
- return imageWithFragment;
- }
-
- /**
- * @return a Image with a flag of the given country
- */
- public static Image getLocalIcon(Locale locale) {
- String imageName;
- Image image = null;
-
- if (locale != null && !locale.getCountry().equals("")){
- imageName = File.separatorChar+"countries"+File.separatorChar+ locale.getCountry().toLowerCase() +".gif";
- image = getBaseImage(imageName);
- }else {
- if (locale != null){
- imageName = File.separatorChar+"countries"+File.separatorChar+"l_"+locale.getLanguage().toLowerCase()+".gif";
- image = getBaseImage(imageName);
- }else {
- imageName = DEFAULT_LOCALICON.toLowerCase(); //Default locale icon
- image = getBaseImage(imageName);
- }
- }
-
- if (image == null) image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
- return image;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/RBManagerActivator.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/RBManagerActivator.java
deleted file mode 100644
index def44f1e..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/RBManagerActivator.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class RBManagerActivator extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipselabs.tapiji.tools.rbmanager"; //$NON-NLS-1$
- // The shared instance
- private static RBManagerActivator plugin;
-
-
- /**
- * The constructor
- */
- public RBManagerActivator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static RBManagerActivator getDefault() {
- return plugin;
- }
-
- public static ImageDescriptor getImageDescriptor(String name){
- String path = "icons/" + name;
-
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/RBLocation.java
deleted file mode 100644
index fb69c29d..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/RBLocation.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.auditor;
-
-import java.io.Serializable;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-
-public class RBLocation implements ILocation {
- private IFile file;
- private int startPos, endPos;
- private String language;
- private Serializable data;
- private ILocation sameValuePartner;
-
-
- public RBLocation(IFile file, int startPos, int endPos, String language) {
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.language = language;
- }
-
- public RBLocation(IFile file, int startPos, int endPos, String language, ILocation sameValuePartner) {
- this(file, startPos, endPos, language);
- this.sameValuePartner=sameValuePartner;
- }
-
- @Override
- public IFile getFile() {
- return file;
- }
-
- @Override
- public int getStartPos() {
- return startPos;
- }
-
- @Override
- public int getEndPos() {
- return endPos;
- }
-
- @Override
- public String getLiteral() {
- return language;
- }
-
- @Override
- public Serializable getData () {
- return data;
- }
-
- public void setData (Serializable data) {
- this.data = data;
- }
-
- public ILocation getSameValuePartner(){
- return sameValuePartner;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
deleted file mode 100644
index a6e7a176..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
+++ /dev/null
@@ -1,243 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.auditor;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.configuration.IConfiguration;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipselabs.tapiji.tools.core.extensions.I18nRBAuditor;
-import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.auditor.quickfix.MissingLanguageResolution;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- *
- */
-public class ResourceBundleAuditor extends I18nRBAuditor {
- private static final String LANGUAGE_ATTRIBUTE = "key";
-
- private List<ILocation> unspecifiedKeys = new LinkedList<ILocation>();
- private Map<ILocation, ILocation> sameValues = new HashMap<ILocation, ILocation>();
- private List<ILocation> missingLanguages = new LinkedList<ILocation>();
- private List<String> seenRBs = new LinkedList<String>();
-
-
- @Override
- public String[] getFileEndings() {
- return new String[] { "properties" };
- }
-
- @Override
- public String getContextId() {
- return "resourcebundle";
- }
-
- @Override
- public List<ILocation> getUnspecifiedKeyReferences() {
- return unspecifiedKeys;
- }
-
- @Override
- public Map<ILocation, ILocation> getSameValuesReferences() {
- return sameValues;
- }
-
- @Override
- public List<ILocation> getMissingLanguageReferences() {
- return missingLanguages;
- }
-
- /*
- * Forgets all save rbIds in seenRB and reset all problem-lists
- */
- @Override
- public void resetProblems() {
- unspecifiedKeys = new LinkedList<ILocation>();
- sameValues = new HashMap<ILocation, ILocation>();
- missingLanguages = new LinkedList<ILocation>();
- seenRBs = new LinkedList<String>();
- }
-
- /*
- * Finds the corresponding ResouceBundle for the resource. Checks if the
- * ResourceBundle is already audit and it is not already executed audit the
- * hole ResourceBundle and save the rbId in seenRB
- */
- @Override
- public void audit(IResource resource) {
- if (!RBFileUtils.isResourceBundleFile(resource))
- return;
-
- IFile file = (IFile) resource;
- String rbId = RBFileUtils.getCorrespondingResourceBundleId(file);
-
- if (!seenRBs.contains(rbId)) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(file.getProject());
- audit(rbId, rbmanager);
- seenRBs.add(rbId);
- } else
- return;
- }
-
- /*
- * audits all files of a resourcebundle
- */
- public void audit(String rbId, ResourceBundleManager rbmanager) {
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
- IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
- Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
- String[] keys = bundlegroup.getMessageKeys();
-
-
- for (IResource r : bundlefile) {
- IFile f1 = (IFile) r;
-
- for (String key : keys) {
- // check if all keys have a value
-
- if (auditUnspecifiedKey(f1, key, bundlegroup)){
- /* do nothing - all just done*/
- }else {
- // check if a key has the same value like a key of an other properties-file
- if (configuration.getAuditSameValue() && bundlefile.size() > 1)
- for (IResource r2 : bundlefile) {
- IFile f2 = (IFile) r2;
- auditSameValues(f1, f2, key, bundlegroup);
- }
- }
- }
- }
-
- if (configuration.getAuditMissingLanguage()){
- // checks if the resourcebundle supports all project-languages
- Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
- Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
-
- auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
- }
- }
-
- /*
- * Audits the file if the key is not specified. If the value is null reports a
- * problem.
- */
- private boolean auditUnspecifiedKey(IFile f1, String key,
- IMessagesBundleGroup bundlegroup) {
- if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
- int pos = calculateKeyLine(key, f1);
- unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
- return true;
- } else
- return false;
- }
-
- /*
- * Compares a key in different files and reports a problem, if the values are
- * same. It doesn't compare the files if one file is the Default-file
- */
- private void auditSameValues(IFile f1, IFile f2, String key,
- IMessagesBundleGroup bundlegroup) {
- Locale l1 = RBFileUtils.getLocale(f1);
- Locale l2 = RBFileUtils.getLocale(f2);
-
- if (!l2.equals(l1) && !(l1.toString().equals("")||l2.toString().equals(""))) {
- IMessage message = bundlegroup.getMessage(key, l2);
-
- if (message != null)
- if (bundlegroup.getMessage(key, l1).getValue()
- .equals(message.getValue())) {
- int pos1 = calculateKeyLine(key, f1);
- int pos2 = calculateKeyLine(key, f2);
- sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key),
- new RBLocation(f2, pos2, pos2 + 1, key));
- }
- }
- }
-
- /*
- * Checks if the resourcebundle supports all project-languages and report
- * missing languages.
- */
- private void auditMissingLanguage(Set<Locale> rbLocales,
- Set<Locale> projectLocales, ResourceBundleManager rbmanager,
- String rbId) {
- for (Locale pLocale : projectLocales) {
- if (!rbLocales.contains(pLocale)) {
- String language = pLocale != null ? pLocale.toString() : ResourceBundleManager.defaultLocaleTag;
-
- // Add Warning to default-file or a random chosen file
- IResource representative = rbmanager.getResourceBundleFile(
- rbId, null);
- if (representative == null)
- representative = rbmanager.getRandomFile(rbId);
- missingLanguages.add(new RBLocation((IFile) representative, 1,
- 2, language));
- }
- }
- }
-
- /*
- * Finds a position where the key is located or missing
- */
- private int calculateKeyLine(String key, IFile file) {
- int linenumber = 1;
- try {
-// if (!Boolean.valueOf(System.getProperty("dirty"))) {
-// System.setProperty("dirty", "true");
- file.refreshLocal(IFile.DEPTH_ZERO, null);
- InputStream is = file.getContents();
- BufferedReader bf = new BufferedReader(new InputStreamReader(is));
- String line;
- while ((line = bf.readLine()) != null) {
- if ((!line.isEmpty()) && (!line.startsWith("#"))
- && (line.compareTo(key) > 0))
- return linenumber;
- linenumber++;
- }
-// System.setProperty("dirty", "false");
-// }
- } catch (CoreException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return linenumber;
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
-
- switch (marker.getAttribute("cause", -1)) {
- case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
- Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
- // change
- // Name
- resolutions.add(new MissingLanguageResolution(l));
- break;
- }
-
- return resolutions;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
deleted file mode 100644
index 9318f294..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.auditor.quickfix;
-
-import java.util.Locale;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.LanguageUtils;
-
-public class MissingLanguageResolution implements IMarkerResolution2 {
-
- private Locale language;
-
- public MissingLanguageResolution(Locale language){
- this.language = language;
- }
-
- @Override
- public String getLabel() {
- return "Add missing language '"+ language +"'";
- }
-
- @Override
- public void run(IMarker marker) {
- IResource res = marker.getResource();
- String rbId = ResourceBundleManager.getResourceBundleId(res);
- LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId, language);
- }
-
- @Override
- public String getDescription() {
- return "Creates a new localized properties-file with the same basename as the resourcebundle";
- }
-
- @Override
- public Image getImage() {
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualContainer.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualContainer.java
deleted file mode 100644
index ea7e7b78..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualContainer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.model;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-
-public class VirtualContainer {
- protected ResourceBundleManager rbmanager;
- protected IContainer container;
- protected int rbCount;
-
- public VirtualContainer(IContainer container1, boolean countResourceBundles){
- this.container = container1;
- rbmanager = ResourceBundleManager.getManager(container.getProject());
- if (countResourceBundles){
- rbCount=1;
- new Job("count ResourceBundles"){
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- recount();
- return Status.OK_STATUS;
- }
- }.schedule();
- }else rbCount = 0;
- }
-
- protected VirtualContainer(IContainer container){
- this.container = container;
- }
-
- public VirtualContainer(IContainer container, int rbCount) {
- this(container, false);
- this.rbCount = rbCount;
- }
-
- public ResourceBundleManager getResourceBundleManager(){
- if (rbmanager == null)
- rbmanager = ResourceBundleManager.getManager(container.getProject());
- return rbmanager;
- }
-
- public IContainer getContainer() {
- return container;
- }
-
- public void setRbCounter(int rbCount){
- this.rbCount = rbCount;
- }
-
- public int getRbCount() {
- return rbCount;
- }
-
- public void recount(){
- rbCount = RBFileUtils.countRecursiveResourceBundle(container);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualContentManager.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualContentManager.java
deleted file mode 100644
index 2dae8c6c..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualContentManager.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.model;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-
-
-public class VirtualContentManager {
- private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>();
- private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>();
-
- static private VirtualContentManager singelton = null;
-
- private VirtualContentManager() {
- }
-
- public static VirtualContentManager getVirtualContentManager(){
- if (singelton == null){
- singelton = new VirtualContentManager();
- }
- return singelton;
- }
-
- public VirtualContainer getContainer(IContainer container) {
- return containers.get(container);
- }
-
-
- public void addVContainer(IContainer container, VirtualContainer vContainer) {
- containers.put(container, vContainer);
- }
-
- public void removeVContainer(IContainer container){
- vResourceBundles.remove(container);
- }
-
- public VirtualResourceBundle getVResourceBundles(String vRbId) {
- return vResourceBundles.get(vRbId);
- }
-
-
- public void addVResourceBundle(String vRbId, VirtualResourceBundle vResourceBundle) {
- vResourceBundles.put(vRbId, vResourceBundle);
- }
-
- public void removeVResourceBundle(String vRbId){
- vResourceBundles.remove(vRbId);
- }
-
-
- public boolean containsVResourceBundles(String vRbId) {
- return vResourceBundles.containsKey(vRbId);
- }
-
- public void reset() {
- vResourceBundles.clear();
- containers.clear();
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualProject.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualProject.java
deleted file mode 100644
index 38f1a1d1..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualProject.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.model;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-
-/**
- * Representation of a project
- *
- */
-public class VirtualProject extends VirtualContainer{
- private boolean isFragment;
- private IProject hostProject;
- private List<IProject> fragmentProjects = new LinkedList<IProject>();
-
- //Slow
- public VirtualProject(IProject project, boolean countResourceBundles) {
- super(project, countResourceBundles);
- isFragment = FragmentProjectUtils.isFragment(project);
- if (isFragment) {
- hostProject = FragmentProjectUtils.getFragmentHost(project);
- } else
- fragmentProjects = FragmentProjectUtils.getFragments(project);
- }
-
- /*
- * No fragment search
- */
- public VirtualProject(final IProject project, boolean isFragment, boolean countResourceBundles){
- super(project, countResourceBundles);
- this.isFragment = isFragment;
-// Display.getDefault().asyncExec(new Runnable() {
-// @Override
-// public void run() {
-// hostProject = FragmentProjectUtils.getFragmentHost(project);
-// }
-// });
- }
-
- public Set<Locale> getProvidedLocales(){
- return rbmanager.getProjectProvidedLocales();
- }
-
- public boolean isFragment(){
- return isFragment;
- }
-
- public IProject getHostProject(){
- return hostProject;
- }
-
- public boolean hasFragments() {
- return !fragmentProjects.isEmpty();
- }
-
- public List<IProject> getFragmets(){
- return fragmentProjects;
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualResourceBundle.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
deleted file mode 100644
index 911f84ba..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.model;
-
-import java.util.Collection;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-public class VirtualResourceBundle{
- private String resourcebundlename;
- private String resourcebundleId;
- private ResourceBundleManager rbmanager;
-
-
- public VirtualResourceBundle(String rbname, String rbId, ResourceBundleManager rbmanager) {
- this.rbmanager=rbmanager;
- resourcebundlename=rbname;
- resourcebundleId=rbId;
- }
-
- public ResourceBundleManager getResourceBundleManager() {
- return rbmanager;
- }
-
- public String getResourceBundleId(){
- return resourcebundleId;
- }
-
-
- @Override
- public String toString(){
- return resourcebundleId;
- }
-
- public IPath getFullPath() {
- return rbmanager.getRandomFile(resourcebundleId).getFullPath();
- }
-
-
- public String getName() {
- return resourcebundlename;
- }
-
- public Collection<IResource> getFiles() {
- return rbmanager.getResourceBundles(resourcebundleId);
- }
-
- public IFile getRandomFile(){
- return rbmanager.getRandomFile(resourcebundleId);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/hover/Hover.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/hover/Hover.java
deleted file mode 100644
index f6993413..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/hover/Hover.java
+++ /dev/null
@@ -1,107 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.ui.hover;
-
-import java.util.List;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackAdapter;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.Widget;
-
-
-public class Hover {
- private Shell hoverShell;
- private Point hoverPosition;
- private List<HoverInformant> informant;
-
- public Hover(Shell parent, List<HoverInformant> informant){
- this.informant = informant;
- hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
- Display display = hoverShell.getDisplay();
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.verticalSpacing = 2;
- hoverShell.setLayout(gridLayout);
-
- hoverShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- hoverShell.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- }
-
-
- private void setHoverLocation(Shell shell, Point position) {
- Rectangle displayBounds = shell.getDisplay().getBounds();
- Rectangle shellBounds = shell.getBounds();
- shellBounds.x = Math.max(
- Math.min(position.x+1, displayBounds.width - shellBounds.width), 0);
- shellBounds.y = Math.max(
- Math.min(position.y + 16, displayBounds.height - (shellBounds.height+1)), 0);
- shell.setBounds(shellBounds);
- }
-
-
- public void activateHoverHelp(final Control control) {
-
- control.addMouseListener(new MouseAdapter() {
- public void mouseDown(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible()){
- hoverShell.setVisible(false);
- }
- }
- });
-
- control.addMouseTrackListener(new MouseTrackAdapter() {
- public void mouseExit(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible())
- hoverShell.setVisible(false);
- }
-
- public void mouseHover(MouseEvent event) {
- Point pt = new Point(event.x, event.y);
- Widget widget = event.widget;
- if (widget instanceof ToolBar) {
- ToolBar w = (ToolBar) widget;
- widget = w.getItem(pt);
- }
- if (widget instanceof Table) {
- Table w = (Table) widget;
- widget = w.getItem(pt);
- }
- if (widget instanceof Tree) {
- Tree w = (Tree) widget;
- widget = w.getItem(pt);
- }
- if (widget == null) {
- hoverShell.setVisible(false);
- return;
- }
- hoverPosition = control.toDisplay(pt);
-
- boolean show = false;
- Object data = widget.getData();
-
- for (HoverInformant hi :informant){
- hi.getInfoComposite(data, hoverShell);
- if (hi.show()) show= true;
- }
-
- if (show){
- hoverShell.pack();
- hoverShell.layout();
- setHoverLocation(hoverShell, hoverPosition);
- hoverShell.setVisible(true);
- }
- else hoverShell.setVisible(false);
-
- }
- });
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/hover/HoverInformant.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
deleted file mode 100644
index dd92f82c..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.ui.hover;
-
-import org.eclipse.swt.widgets.Composite;
-
-public interface HoverInformant {
-
- public Composite getInfoComposite(Object data, Composite parent);
-
- public boolean show();
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
deleted file mode 100644
index cb3d5a34..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.ui.view.toolbarItems;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IViewActionDelegate;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.navigator.CommonNavigator;
-import org.eclipse.ui.navigator.CommonViewer;
-import org.eclipse.ui.progress.UIJob;
-
-public class ExpandAllActionDelegate implements IViewActionDelegate {
- private CommonViewer viewer;
-
- @Override
- public void run(IAction action) {
- Object data = viewer.getControl().getData();
-
- for(final IProject p : ((IWorkspaceRoot)data).getProjects()){
- UIJob job = new UIJob("expand Projects") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS);
- return Status.OK_STATUS;
- }
- };
-
- job.schedule();
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // TODO Auto-generated method stub
- }
-
- @Override
- public void init(IViewPart view) {
- viewer = ((CommonNavigator) view).getCommonViewer();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
deleted file mode 100644
index 37c43251..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.ui.view.toolbarItems;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IViewActionDelegate;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.navigator.CommonNavigator;
-import org.eclipse.ui.navigator.ICommonFilterDescriptor;
-import org.eclipse.ui.navigator.INavigatorContentService;
-import org.eclipse.ui.navigator.INavigatorFilterService;
-import org.eclipselabs.tapiji.tools.rbmanager.RBManagerActivator;
-
-
-
-public class ToggleFilterActionDelegate implements IViewActionDelegate{
- private INavigatorFilterService filterService;
- private boolean active;
- private static final String[] FILTER = {RBManagerActivator.PLUGIN_ID+".filter.ProblematicResourceBundleFiles"};
-
- @Override
- public void run(IAction action) {
- if (active==true){
- filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active = false;
- }
- else {
- filterService.activateFilterIdsAndUpdateViewer(FILTER);
- active = true;
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // Active when content change
- }
-
- @Override
- public void init(IViewPart view) {
- INavigatorContentService contentService = ((CommonNavigator) view).getCommonViewer().getNavigatorContentService();
-
- filterService = contentService.getFilterService();
- filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active=false;
- }
-
-
- @SuppressWarnings("unused")
- private String[] getActiveFilterIds() {
- ICommonFilterDescriptor[] fds = filterService.getVisibleFilterDescriptors();
- String activeFilterIds[]=new String[fds.length];
-
- for(int i=0;i<fds.length;i++)
- activeFilterIds[i]=fds[i].getId();
-
- return activeFilterIds;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/LinkHelper.java
deleted file mode 100644
index 3279e462..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/LinkHelper.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.ide.ResourceUtil;
-import org.eclipse.ui.navigator.ILinkHelper;
-
-/*
- * Allows 'link with editor'
- */
-public class LinkHelper implements ILinkHelper {
-
- public static IStructuredSelection viewer;
-
- @Override
- public IStructuredSelection findSelection(IEditorInput anInput) {
- IFile file = ResourceUtil.getFile(anInput);
- if (file != null) {
- return new StructuredSelection(file);
- }
- return StructuredSelection.EMPTY;
- }
-
- @Override
- public void activateEditor(IWorkbenchPage aPage,IStructuredSelection aSelection) {
- if (aSelection.getFirstElement() instanceof IFile)
- try {
- IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
- } catch (PartInitException e) {/**/}
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
deleted file mode 100644
index c38b6423..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
+++ /dev/null
@@ -1,386 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualContainer;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualContentManager;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualProject;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-
-
-
-/**
- *
- *
- */
-public class ResourceBundleContentProvider implements ITreeContentProvider, IResourceChangeListener, IPropertyChangeListener, IResourceBundleChangedListener{
- private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false;
- private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true;
- private StructuredViewer viewer;
- private VirtualContentManager vcManager;
- private UIJob refresh;
- private IWorkspaceRoot root;
-
- private List<IProject> listenedProjects;
- /**
- *
- */
- public ResourceBundleContentProvider() {
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
- TapiJIPreferences.addPropertyChangeListener(this);
- vcManager = VirtualContentManager.getVirtualContentManager();
- listenedProjects = new LinkedList<IProject>();
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public Object[] getChildren(final Object parentElement) {
- Object[] children = null;
-
- if (parentElement instanceof IWorkspaceRoot) {
- root = (IWorkspaceRoot) parentElement;
- try {
- IResource[] members = ((IWorkspaceRoot)parentElement).members();
-
- List<Object> displayedProjects = new ArrayList<Object>();
- for (IResource r : members)
- if (r instanceof IProject){
- IProject p = (IProject) r;
- if (FragmentProjectUtils.isFragment(r.getProject())) {
- if (vcManager.getContainer(p)==null)
- vcManager.addVContainer(p, new VirtualProject(p, true,false));
- if (FRAGMENT_PROJECTS_IN_CONTENT) displayedProjects.add(r);
- } else {
- if (SHOW_ONLY_PROJECTS_WITH_RBS){
- VirtualProject vP;
- if ((vP=(VirtualProject) vcManager.getContainer(p))==null){
- vP = new VirtualProject(p, false, true);
- vcManager.addVContainer(p, vP);
- registerResourceBundleListner(p);
- }
-
- if (vP.getRbCount()>0) displayedProjects.add(p);
- }else {
- displayedProjects.add(p);
- }
- }
- }
-
- children = displayedProjects.toArray();
- return children;
- } catch (CoreException e) { }
- }
-
-// if (parentElement instanceof IProject) {
-// final IProject iproject = (IProject) parentElement;
-// VirtualContainer vproject = vcManager.getContainer(iproject);
-// if (vproject == null){
-// vproject = new VirtualProject(iproject, true);
-// vcManager.addVContainer(iproject, vproject);
-// }
-// }
-
- if (parentElement instanceof IContainer) {
- IContainer container = (IContainer) parentElement;
- if (!((VirtualProject) vcManager.getContainer(((IResource) parentElement).getProject()))
- .isFragment())
- try {
- children = addChildren(container);
- } catch (CoreException e) {/**/}
- }
-
- if (parentElement instanceof VirtualResourceBundle) {
- VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
- ResourceBundleManager rbmanager = virtualrb.getResourceBundleManager();
- children = rbmanager.getResourceBundles(virtualrb.getResourceBundleId()).toArray();
- }
-
- return children != null ? children : new Object[0];
- }
-
- /*
- * Returns all ResourceBundles and sub-containers (with ResourceBundles in their subtree) of a Container
- */
- private Object[] addChildren(IContainer container) throws CoreException{
- Map<String, Object> children = new HashMap<String,Object>();
-
- VirtualProject p = (VirtualProject) vcManager.getContainer(container.getProject());
- List<IResource> members = new ArrayList<IResource>(Arrays.asList(container.members()));
-
- //finds files in the corresponding fragment-projects folder
- if (p.hasFragments()){
- List<IContainer> folders = ResourceUtils.getCorrespondingFolders(container, p.getFragmets());
- for (IContainer f : folders)
- for (IResource r : f.members())
- if (r instanceof IFile)
- members.add(r);
- }
-
- for(IResource r : members){
-
- if (r instanceof IFile) {
- String resourcebundleId = RBFileUtils.getCorrespondingResourceBundleId((IFile)r);
- if( resourcebundleId != null && (!children.containsKey(resourcebundleId))) {
- VirtualResourceBundle vrb;
-
- String vRBId;
-
- if (!p.isFragment()) vRBId = r.getProject()+"."+resourcebundleId;
- else vRBId = p.getHostProject() + "." + resourcebundleId;
-
- VirtualResourceBundle vResourceBundle = vcManager.getVResourceBundles(vRBId);
- if (vResourceBundle == null){
- String resourcebundleName = ResourceBundleManager.getResourceBundleName(r);
- vrb = new VirtualResourceBundle(resourcebundleName, resourcebundleId, ResourceBundleManager.getManager(r.getProject()));
- vcManager.addVResourceBundle(vRBId, vrb);
-
- } else vrb = vcManager.getVResourceBundles(vRBId);
-
- children.put(resourcebundleId, vrb);
- }
- }
- if (r instanceof IContainer)
- if (!r.isDerived()){ //Don't show the 'bin' folder
- VirtualContainer vContainer = vcManager.getContainer((IContainer) r);
-
- if (vContainer == null){
- int count = RBFileUtils.countRecursiveResourceBundle((IContainer)r);
- vContainer = new VirtualContainer(container, count);
- vcManager.addVContainer((IContainer) r, vContainer);
- }
-
- if (vContainer.getRbCount() != 0) //Don't show folder without resourcebundles
- children.put(""+children.size(), r);
- }
- }
- return children.values().toArray();
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof IContainer) {
- return ((IContainer) element).getParent();
- }
- if (element instanceof IFile) {
- String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile) element);
- return vcManager.getVResourceBundles(rbId);
- }
- if (element instanceof VirtualResourceBundle) {
- Iterator<IResource> i = new HashSet<IResource>(((VirtualResourceBundle) element).getFiles()).iterator();
- if (i.hasNext()) return i.next().getParent();
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof IWorkspaceRoot) {
- try {
- if (((IWorkspaceRoot) element).members().length > 0) return true;
- } catch (CoreException e) {}
- }
- if (element instanceof IProject){
- VirtualProject vProject = (VirtualProject) vcManager.getContainer((IProject) element);
- if (vProject!= null && vProject.isFragment()) return false;
- }
- if (element instanceof IContainer) {
- try {
- VirtualContainer vContainer = vcManager.getContainer((IContainer) element);
- if (vContainer != null)
- return vContainer.getRbCount() > 0 ? true : false;
- else if (((IContainer) element).members().length > 0) return true;
- } catch (CoreException e) {}
- }
- if (element instanceof VirtualResourceBundle){
- return true;
- }
- return false;
- }
-
- @Override
- public void dispose() {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- TapiJIPreferences.removePropertyChangeListener(this);
- vcManager.reset();
- unregisterAllResourceBundleListner();
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (StructuredViewer) viewer;
- }
-
- @Override
- //TODO remove ResourceChangelistner and add ResourceBundleChangelistner
- public void resourceChanged(final IResourceChangeEvent event) {
-
- final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- final IResource res = delta.getResource();
-
- if (!RBFileUtils.isResourceBundleFile(res))
- return true;
-
- switch (delta.getKind()) {
- case IResourceDelta.REMOVED:
- recountParenthierarchy(res.getParent());
- break;
- //TODO remove unused VirtualResourceBundles and VirtualContainer from vcManager
- case IResourceDelta.ADDED:
- checkListner(res);
- break;
- case IResourceDelta.CHANGED:
- if (delta.getFlags() != IResourceDelta.MARKERS)
- return true;
- break;
- }
-
- refresh(res);
-
- return true;
- }
- };
-
- try {
- event.getDelta().accept(visitor);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void resourceBundleChanged(ResourceBundleChangedEvent event) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(event.getProject());
-
- switch (event.getType()){
- case ResourceBundleChangedEvent.ADDED:
- case ResourceBundleChangedEvent.DELETED:
- IResource res = rbmanager.getRandomFile(event.getBundle());
- IContainer hostContainer;
-
- if (res == null)
- try{
- hostContainer = event.getProject().getFile(event.getBundle()).getParent();
- }catch (Exception e) {
- refresh(null);
- return;
- }
- else {
- VirtualProject vProject = (VirtualProject) vcManager.getContainer((IContainer) res.getProject());
- if (vProject != null && vProject.isFragment()){
- IProject hostProject = vProject.getHostProject();
- hostContainer = ResourceUtils.getCorrespondingFolders(res.getParent(), hostProject);
- } else
- hostContainer = res.getParent();
- }
-
- recountParenthierarchy(hostContainer);
- refresh(null);
- break;
- }
-
- }
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if(event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)){
- vcManager.reset();
-
- refresh(root);
- }
- }
-
- //TODO problems with remove a hole ResourceBundle
- private void recountParenthierarchy(IContainer parent) {
- if (parent.isDerived())
- return; //Don't recount the 'bin' folder
-
- VirtualContainer vContainer = vcManager.getContainer((IContainer) parent);
- if (vContainer != null){
- vContainer.recount();
- }
-
- if ((parent instanceof IFolder))
- recountParenthierarchy(parent.getParent());
- }
-
- private void refresh(final IResource res) {
- if (refresh == null || refresh.getResult() != null)
- refresh = new UIJob("refresh viewer") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (viewer != null
- && !viewer.getControl().isDisposed())
- if (res != null)
- viewer.refresh(res.getProject(),true); // refresh(res);
- else viewer.refresh();
- return Status.OK_STATUS;
- }
- };
- refresh.schedule();
- }
-
- private void registerResourceBundleListner(IProject p) {
- listenedProjects.add(p);
-
- ResourceBundleManager rbmanager =ResourceBundleManager.getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- rbmanager.registerResourceBundleChangeListener(rbId, this);
- }
- }
-
- private void unregisterAllResourceBundleListner() {
- for( IProject p : listenedProjects){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- rbmanager.unregisterResourceBundleChangeListener(rbId, this);
- }
- }
- }
-
- private void checkListner(IResource res) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res.getProject());
- String rbId = ResourceBundleManager.getResourceBundleId(res);
- rbmanager.registerResourceBundleChangeListener(rbId, this);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
deleted file mode 100644
index 454acb36..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
+++ /dev/null
@@ -1,166 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.navigator.IDescriptionProvider;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualContainer;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualContentManager;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualProject;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-
-
-
-public class ResourceBundleLabelProvider extends LabelProvider implements ILabelProvider, IDescriptionProvider{
- VirtualContentManager vcManager;
-
- public ResourceBundleLabelProvider(){
- super();
- vcManager = VirtualContentManager.getVirtualContentManager();
- }
-
- @Override
- public Image getImage(Object element) {
- Image returnImage = null;
- if (element instanceof IProject){
- VirtualProject p = (VirtualProject) vcManager.getContainer((IProject) element);
- if (p!=null && p.isFragment())
- return returnImage = ImageUtils.getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE);
- else
- returnImage = PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJ_PROJECT);
- }
- if ((element instanceof IContainer)&&(returnImage == null)){
- returnImage = PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJ_FOLDER);
- }
- if (element instanceof VirtualResourceBundle)
- returnImage = ImageUtils.getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
- if (element instanceof IFile){
- if (RBFileUtils.isResourceBundleFile((IFile)element)){
- Locale l = RBFileUtils.getLocale((IFile)element);
- returnImage = ImageUtils.getLocalIcon(l);
-
- VirtualProject p = ((VirtualProject)vcManager.getContainer(((IFile) element).getProject()));
- if (p!=null && p.isFragment())
- returnImage = ImageUtils.getImageWithFragment(returnImage);
- }
- }
-
- if (returnImage != null) {
- if (checkMarkers(element))
- //Add a Warning Image
- returnImage = ImageUtils.getImageWithWarning(returnImage);
- }
- return returnImage;
- }
-
- @Override
- public String getText(Object element) {
-
- StringBuilder text = new StringBuilder();
- if (element instanceof IContainer) {
- IContainer container = (IContainer) element;
- text.append(container.getName());
-
- if (element instanceof IProject){
- VirtualContainer vproject = vcManager.getContainer((IProject) element);
-// if (vproject != null && vproject instanceof VirtualFragment) text.append("°");
- }
-
- VirtualContainer vContainer = vcManager.getContainer(container);
- if (vContainer != null && vContainer.getRbCount() != 0)
- text.append(" ["+vContainer.getRbCount()+"]");
-
- }
- if (element instanceof VirtualResourceBundle){
- text.append(((VirtualResourceBundle)element).getName());
- }
- if (element instanceof IFile){
- if (RBFileUtils.isResourceBundleFile((IFile)element)){
- Locale locale = RBFileUtils.getLocale((IFile)element);
- text.append(" ");
- if (locale != null) {
- text.append(locale);
- }
- else {
- text.append("default");
- }
-
- VirtualProject vproject = (VirtualProject) vcManager.getContainer(((IFile) element).getProject());
- if (vproject!= null && vproject.isFragment()) text.append("°");
- }
- }
- if(element instanceof String){
- text.append(element);
- }
- return text.toString();
- }
-
- @Override
- public String getDescription(Object anElement) {
- if (anElement instanceof IResource)
- return ((IResource)anElement).getName();
- if (anElement instanceof VirtualResourceBundle)
- return ((VirtualResourceBundle)anElement).getName();
- return null;
- }
-
- private boolean checkMarkers(Object element){
- if (element instanceof IResource){
- IMarker[] ms = null;
- try {
- if ((ms=((IResource) element).findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE)).length > 0)
- return true;
-
- if (element instanceof IContainer){
- List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) element,
- FragmentProjectUtils.getFragments(((IContainer) element).getProject()));
-
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- if (ms.length>0)
- return true;
- }
- } catch (CoreException e) {
- }
- }
- if (element instanceof VirtualResourceBundle){
- ResourceBundleManager rbmanager = ((VirtualResourceBundle)element).getResourceBundleManager();
- String id = ((VirtualResourceBundle)element).getResourceBundleId();
- for (IResource r : rbmanager.getResourceBundles(id)){
- if (RBFileUtils.hasResourceBundleMarker(r)) return true;
- }
- }
-
- return false;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
deleted file mode 100644
index b6f7f3d8..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.navigator.CommonViewer;
-import org.eclipselabs.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.RBManagerActivator;
-
-
-public class ExpandAction extends Action implements IAction{
- private CommonViewer viewer;
-
- public ExpandAction(CommonViewer viewer) {
- this.viewer= viewer;
- setText("Expand Node");
- setToolTipText("expand node");
- setImageDescriptor(RBManagerActivator.getImageDescriptor(ImageUtils.EXPAND));
- }
-
- @Override
- public boolean isEnabled(){
- IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
- if (sSelection.size()>=1) return true;
- else return false;
- }
-
- @Override
- public void run(){
- IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
- Iterator<?> it = sSelection.iterator();
- while (it.hasNext()){
- viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS);
- }
-
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
deleted file mode 100644
index cbac33f9..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.CommonViewer;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-import org.eclipselabs.tapiji.tools.rbmanager.ui.hover.Hover;
-import org.eclipselabs.tapiji.tools.rbmanager.ui.hover.HoverInformant;
-import org.eclipselabs.tapiji.tools.rbmanager.viewer.actions.hoverinformants.I18NProjectInformant;
-import org.eclipselabs.tapiji.tools.rbmanager.viewer.actions.hoverinformants.RBMarkerInformant;
-
-
-public class GeneralActionProvider extends CommonActionProvider {
- private IAction expandAction;
-
- public GeneralActionProvider() {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void init(ICommonActionExtensionSite aSite){
- super.init(aSite);
- //init Expand-Action
- expandAction = new ExpandAction((CommonViewer) aSite.getStructuredViewer());
-
- //activate View-Hover
- List<HoverInformant> informants = new ArrayList<HoverInformant>();
- informants.add(new I18NProjectInformant());
- informants.add(new RBMarkerInformant());
-
- Hover hover = new Hover(Display.getCurrent().getActiveShell(), informants);
- hover.activateHoverHelp(((CommonViewer)aSite.getStructuredViewer()).getTree());
- }
-
- @Override
- public void fillContextMenu(IMenuManager menu) {
- menu.appendToGroup("expand",expandAction);
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
deleted file mode 100644
index c0a5bd08..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.RBManagerActivator;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-
-
-
-public class OpenVRBAction extends Action {
- private ISelectionProvider selectionProvider;
-
- public OpenVRBAction(ISelectionProvider selectionProvider) {
- this.selectionProvider = selectionProvider;
- }
-
- @Override
- public boolean isEnabled(){
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
- if (sSelection.size()==1) return true;
- else return false;
- }
-
- @Override
- public void run(){
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
- if (sSelection.size()==1 && sSelection.getFirstElement() instanceof VirtualResourceBundle){
- VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection.getFirstElement();
- IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
-
- EditorUtils.openEditor(wp, vRB.getRandomFile(), EditorUtils.RESOURCE_BUNDLE_EDITOR);
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
deleted file mode 100644
index 07387661..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.ICommonActionConstants;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-
-/*
- * Will be only active for VirtualResourceBundeles
- */
-public class VirtualRBActionProvider extends CommonActionProvider {
- private IAction openAction;
-
- public VirtualRBActionProvider() {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void init(ICommonActionExtensionSite aSite){
- super.init(aSite);
- openAction = new OpenVRBAction(aSite.getViewSite().getSelectionProvider());
- }
-
- @Override
- public void fillActionBars(IActionBars actionBars){
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, openAction);
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
deleted file mode 100644
index 90195751..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
+++ /dev/null
@@ -1,217 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
-
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.ui.hover.HoverInformant;
-
-public class I18NProjectInformant implements HoverInformant {
- private String locales;
- private String fragments;
- private boolean show = false;
-
- private Composite infoComposite;
- private Label localeLabel;
- private Composite localeGroup;
- private Label fragmentsLabel;
- private Composite fragmentsGroup;
-
- private GridData infoData;
- private GridData showLocalesData;
- private GridData showFragmentsData;
-
- @Override
- public Composite getInfoComposite(Object data, Composite parent) {
- show = false;
-
- if (infoComposite == null){
- infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout =new GridLayout(1,false);
- layout.verticalSpacing = 1;
- layout.horizontalSpacing = 0;
- infoComposite.setLayout(layout);
-
- infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- infoComposite.setLayoutData(infoData);
- }
-
- if (data instanceof IProject) {
- addLocale(infoComposite, data);
- addFragments(infoComposite, data);
- }
-
- if (show) {
- infoData.heightHint = -1;
- infoData.widthHint = -1;
- } else {
- infoData.heightHint = 0;
- infoData.widthHint = 0;
- }
-
- infoComposite.layout();
- infoComposite.pack();
- sinkColor(infoComposite);
-
- return infoComposite;
- }
-
- @Override
- public boolean show() {
- return show;
- }
-
- private void setColor(Control control){
- Display display = control.getParent().getDisplay();
-
- control.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- private void sinkColor(Composite composite){
- setColor(composite);
-
- for(Control c : composite.getChildren()){
- setColor(c);
- if (c instanceof Composite) sinkColor((Composite) c);
- }
- }
-
- private void addLocale(Composite parent, Object data){
- if (localeGroup == null) {
- localeGroup = new Composite(parent, SWT.NONE);
- localeLabel = new Label(localeGroup, SWT.SINGLE);
-
- showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- localeGroup.setLayoutData(showLocalesData);
- }
-
- locales = getProvidedLocales(data);
-
- if (locales.length() != 0) {
- localeLabel.setText(locales);
- localeLabel.pack();
- show = true;
-// showLocalesData.heightHint = -1;
-// showLocalesData.widthHint=-1;
- } else {
- localeLabel.setText("No Language Provided");
- localeLabel.pack();
- show = true;
-// showLocalesData.heightHint = 0;
-// showLocalesData.widthHint = 0;
- }
-
-// localeGroup.layout();
- localeGroup.pack();
- }
-
- private void addFragments(Composite parent, Object data){
- if (fragmentsGroup == null) {
- fragmentsGroup = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- fragmentsGroup.setLayout(layout);
-
- showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- fragmentsGroup.setLayoutData(showFragmentsData);
-
- Composite fragmentTitleGroup = new Composite(fragmentsGroup,
- SWT.NONE);
- layout = new GridLayout(2, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- fragmentTitleGroup.setLayout(layout);
-
- Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
- fragmentImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
- fragmentImageLabel.pack();
-
- Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
- fragementTitleLabel.setText("Project Fragments:");
- fragementTitleLabel.pack();
- fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
- }
-
- fragments = getFragmentProjects(data);
-
- if (fragments.length() != 0) {
- fragmentsLabel.setText(fragments);
- show = true;
- showFragmentsData.heightHint = -1;
- showFragmentsData.widthHint= -1;
- fragmentsLabel.pack();
- } else {
- showFragmentsData.heightHint = 0;
- showFragmentsData.widthHint = 0;
- }
-
- fragmentsGroup.layout();
- fragmentsGroup.pack();
- }
-
- private String getProvidedLocales(Object data) {
- if (data instanceof IProject) {
- ResourceBundleManager rbmanger = ResourceBundleManager.getManager((IProject) data);
- Set<Locale> ls = rbmanger.getProjectProvidedLocales();
-
- if (ls.size() > 0) {
- StringBuilder sb = new StringBuilder();
- sb.append("Provided Languages:\n");
-
- int i = 0;
- for (Locale l : ls) {
- if (!l.toString().equals(""))
- sb.append(l.getDisplayName());
- else
- sb.append("[Default]");
-
- if (++i != ls.size()) {
- sb.append(",");
- if (i % 5 == 0)
- sb.append("\n");
- else
- sb.append(" ");
- }
-
- }
- return sb.toString();
- }
- }
-
-
- return "";
- }
-
- private String getFragmentProjects(Object data) {
- if (data instanceof IProject){
- List<IProject> fragments = FragmentProjectUtils.getFragments((IProject) data);
- if (fragments.size() > 0) {
- StringBuilder sb = new StringBuilder();
-
- int i = 0;
- for (IProject f : fragments){
- sb.append(f.getName());
- if (++i != fragments.size()) sb.append("\n");
- }
- return sb.toString();
- }
- }
- return "";
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
deleted file mode 100644
index 705955f0..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
+++ /dev/null
@@ -1,266 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-import org.eclipselabs.tapiji.tools.rbmanager.ui.hover.HoverInformant;
-
-
-public class RBMarkerInformant implements HoverInformant {
- private int MAX_PROBLEMS = 20;
- private boolean show = false;
-
- private String title;
- private String problems;
-
- private Composite infoComposite;
- private Composite titleGroup;
- private Label titleLabel;
- private Composite problemGroup;
- private Label problemLabel;
-
- private GridData infoData;
- private GridData showTitleData;
- private GridData showProblemsData;
-
-
- @Override
- public Composite getInfoComposite(Object data, Composite parent) {
- show = false;
-
- if (infoComposite == null){
- infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout =new GridLayout(1,false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- infoComposite.setLayout(layout);
-
- infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- infoComposite.setLayoutData(infoData);
- }
-
- if (data instanceof VirtualResourceBundle || data instanceof IResource) {
- addTitle(infoComposite, data);
- addProblems(infoComposite, data);
- }
-
- if (show){
- infoData.heightHint=-1;
- infoData.widthHint=-1;
- } else {
- infoData.heightHint=0;
- infoData.widthHint=0;
- }
-
- infoComposite.layout();
- sinkColor(infoComposite);
- infoComposite.pack();
-
- return infoComposite;
- }
-
- @Override
- public boolean show(){
- return show;
- }
-
- private void setColor(Control control){
- Display display = control.getParent().getDisplay();
-
- control.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- private void sinkColor(Composite composite){
- setColor(composite);
-
- for(Control c : composite.getChildren()){
- setColor(c);
- if (c instanceof Composite) sinkColor((Composite) c);
- }
- }
-
- private void addTitle(Composite parent, Object data){
- if (titleGroup == null) {
- titleGroup = new Composite(parent, SWT.NONE);
- titleLabel = new Label(titleGroup, SWT.SINGLE);
-
- showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- titleGroup.setLayoutData(showTitleData);
- }
- title = getTitel(data);
-
- if (title.length() != 0) {
- titleLabel.setText(title);
- show = true;
- showTitleData.heightHint=-1;
- showTitleData.widthHint=-1;
- titleLabel.pack();
- } else {
- showTitleData.heightHint=0;
- showTitleData.widthHint=0;
- }
-
- titleGroup.layout();
- titleGroup.pack();
- }
-
-
- private void addProblems(Composite parent, Object data){
- if (problemGroup == null) {
- problemGroup = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- problemGroup.setLayout(layout);
-
- showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- problemGroup.setLayoutData(showProblemsData);
-
- Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE);
- layout = new GridLayout(2, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- problemTitleGroup.setLayout(layout);
-
- Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
- warningImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.WARNING_IMAGE));
- warningImageLabel.pack();
-
- Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
- waringTitleLabel.setText("ResourceBundle-Problems:");
- waringTitleLabel.pack();
-
- problemLabel = new Label(problemGroup, SWT.SINGLE);
- }
-
- problems = getProblems(data);
-
- if (problems.length() != 0) {
- problemLabel.setText(problems);
- show = true;
- showProblemsData.heightHint=-1;
- showProblemsData.widthHint=-1;
- problemLabel.pack();
- } else {
- showProblemsData.heightHint=0;
- showProblemsData.widthHint=0;
- }
-
- problemGroup.layout();
- problemGroup.pack();
- }
-
-
- private String getTitel(Object data) {
- if (data instanceof IFile){
- return ((IResource)data).getFullPath().toString();
- }
- if (data instanceof VirtualResourceBundle){
- return ((VirtualResourceBundle)data).getResourceBundleId();
- }
-
- return "";
- }
-
- private String getProblems(Object data){
- IMarker[] ms = null;
-
- if (data instanceof IResource){
- IResource res = (IResource) data;
- try {
- if (res.exists())
- ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- else ms = new IMarker[0];
- } catch (CoreException e) {
- e.printStackTrace();
- }
- if (data instanceof IContainer){
- //add problem of same folder in the fragment-project
- List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) res,
- FragmentProjectUtils.getFragments(res.getProject()));
-
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
-
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- }
- }
- }
- }
-
- if (data instanceof VirtualResourceBundle){
- VirtualResourceBundle vRB = (VirtualResourceBundle) data;
-
- ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
- IMarker[] file_ms;
-
- Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB.getResourceBundleId());
- if (!rBundles.isEmpty())
- for (IResource r : rBundles){
- try {
- file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
- if (ms != null) {
- ms = EditorUtils.concatMarkerArray(ms, file_ms);
- }else{
- ms = file_ms;
- }
- } catch (Exception e) {
- }
- }
- }
-
-
- StringBuilder sb = new StringBuilder();
- int count=0;
-
- if (ms != null && ms.length!=0){
- for (IMarker m : ms) {
- try {
- sb.append(m.getAttribute(IMarker.MESSAGE));
- sb.append("\n");
- count++;
- if (count == MAX_PROBLEMS && ms.length-count!=0){
- sb.append(" ... and ");
- sb.append(ms.length-count);
- sb.append(" other problems");
- break;
- }
- } catch (CoreException e) {
- }
- ;
- }
- return sb.toString();
- }
-
- return "";
- }
-}
diff --git a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java b/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
deleted file mode 100644
index 7d8010e5..00000000
--- a/org.eclipselabs.tapiji.tools.rbmanager/src/org/eclipselabs/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.eclipselabs.tapiji.tools.rbmanager.viewer.filters;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipselabs.tapiji.tools.core.util.RBFileUtils;
-import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import org.eclipselabs.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-
-
-
-public class ProblematicResourceBundleFilter extends ViewerFilter {
-
- /**
- * Shows only IContainer and VirtualResourcebundles with all his
- * properties-files, which have RB_Marker.
- */
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof IFile){
- return true;
- }
- if (element instanceof VirtualResourceBundle) {
- for (IResource f : ((VirtualResourceBundle)element).getFiles() ){
- if (RBFileUtils.hasResourceBundleMarker(f))
- return true;
- }
- }
- if (element instanceof IContainer) {
- try {
- IMarker[] ms = null;
- if ((ms=((IContainer) element).findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE)).length > 0)
- return true;
-
- List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) element,
- FragmentProjectUtils.getFragments(((IContainer) element).getProject()));
-
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- if (ms.length>0)
- return true;
-
- } catch (CoreException e) { }
- }
- return false;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/.project b/org.eclipselabs.tapiji.translator.rap.babel.core/.project
deleted file mode 100644
index 13303e51..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.translator.rap.babel.core</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap.babel.core/META-INF/MANIFEST.MF
deleted file mode 100644
index d742fc3d..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,9 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Babel Core Plug-in
-Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap.babel.core
-Bundle-Version: 1.0.0.qualifier
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Require-Bundle: org.eclipse.core.databinding;bundle-version="1.4.1",
- org.eclipse.core.runtime;bundle-version="3.8.0",
- org.eclipselabs.tapiji.translator.rap.rbe;bundle-version="0.0.2"
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/ConfigurationManager.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/ConfigurationManager.java
deleted file mode 100644
index a9d3e7e4..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/ConfigurationManager.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.configuration;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionPoint;
-import org.eclipse.core.runtime.Platform;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.IPropertiesSerializerConfig;
-
-/**
- *
- * @author Alexej Strelzow
- */
-public class ConfigurationManager {
-
- private static ConfigurationManager INSTANCE;
-
- private IConfiguration config;
-
- private IPropertiesSerializerConfig serializerConfig;
-
- private IPropertiesDeserializerConfig deserializerConfig;
-
- private ConfigurationManager() {
- config = getConfig();
- }
-
- private IConfiguration getConfig() {
-
- IExtensionPoint extp = Platform.getExtensionRegistry().getExtensionPoint(
- "org.eclipse.babel.core" + ".babelConfiguration");
- IConfigurationElement[] elements = extp.getConfigurationElements();
-
- if (elements.length != 0) {
- try {
- return (IConfiguration) elements[0].createExecutableExtension("class");
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- public static ConfigurationManager getInstance() {
- if (INSTANCE == null) {
- INSTANCE = new ConfigurationManager();
- }
- return INSTANCE;
- }
-
- public IConfiguration getConfiguration() {
- return this.config;
- }
-
- public IPropertiesSerializerConfig getSerializerConfig() {
- return serializerConfig;
- }
-
- public void setSerializerConfig(IPropertiesSerializerConfig serializerConfig) {
- this.serializerConfig = serializerConfig;
- }
-
- public IPropertiesDeserializerConfig getDeserializerConfig() {
- return deserializerConfig;
- }
-
- public void setDeserializerConfig(
- IPropertiesDeserializerConfig deserializerConfig) {
- this.deserializerConfig = deserializerConfig;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/DirtyHack.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/DirtyHack.java
deleted file mode 100644
index a673317d..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/DirtyHack.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.configuration;
-
-public final class DirtyHack {
-
- private static boolean fireEnabled = true; // no property-fire calls in in AbstractMessageModel
-
- private static boolean editorModificationEnabled = true; // no setText in EclipsePropertiesEditorResource
- // set this, if you serialize!
-
- public static boolean isFireEnabled() {
- return fireEnabled;
- }
-
- public static void setFireEnabled(boolean fireEnabled) {
- DirtyHack.fireEnabled = fireEnabled;
- }
-
- public static boolean isEditorModificationEnabled() {
- return editorModificationEnabled;
- }
-
- public static void setEditorModificationEnabled(
- boolean editorModificationEnabled) {
- DirtyHack.editorModificationEnabled = editorModificationEnabled;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/IConfiguration.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/IConfiguration.java
deleted file mode 100644
index cfb8333c..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/configuration/IConfiguration.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.configuration;
-
-/**
- *
- * @author Alexej Strelzow
- */
-public interface IConfiguration {
-
- boolean getAuditSameValue();
- boolean getAuditMissingValue();
- boolean getAuditMissingLanguage();
- boolean getAuditRb();
- boolean getAuditResource();
- String getNonRbPattern();
-
-// convertStringToList(String)
-// convertListToString(List<CheckItem>)
-// addPropertyChangeListener(IPropertyChangeListener)
-// removePropertyChangeListener(IPropertyChangeListener)
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/factory/MessagesBundleGroupFactory.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/factory/MessagesBundleGroupFactory.java
deleted file mode 100644
index 746f7534..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/factory/MessagesBundleGroupFactory.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.factory;
-
-import java.io.File;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipselabs.tapiji.translator.rap.babel.core.configuration.ConfigurationManager;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.strategy.PropertiesFileGroupStrategy;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-public class MessagesBundleGroupFactory {
-
- public static IMessagesBundleGroup createBundleGroup(IResource resource) {
-
- File ioFile = new File(resource.getRawLocation().toFile().getPath());
-
- return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile,
- ConfigurationManager.getInstance().getSerializerConfig(),
- ConfigurationManager.getInstance().getDeserializerConfig()));
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/AbstractIFileChangeListener.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/AbstractIFileChangeListener.java
deleted file mode 100644
index 8bf423d3..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/AbstractIFileChangeListener.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-
-/**
- * Same functionality than an {@link IResourceChangeListener} but listens to
- * a single file at a time. Subscribed and unsubscribed directly on
- * the MessageEditorPlugin.
- *
- * @author Hugues Malphettes
- */
-public abstract class AbstractIFileChangeListener {
-
- /**
- * Takes a IResourceChangeListener and wraps it into an AbstractIFileChangeListener.
- * <p>
- * Delegates the listenedFileChanged calls to the underlying
- * IResourceChangeListener#resourceChanged.
- * </p>
- * @param rcl
- * @param listenedFile
- * @return
- */
- public static AbstractIFileChangeListener wrapResourceChangeListener(
- final IResourceChangeListener rcl, IFile listenedFile) {
- return new AbstractIFileChangeListener(listenedFile) {
- public void listenedFileChanged(IResourceChangeEvent event) {
- rcl.resourceChanged(event);
- }
- };
- }
-
-
- //we use a string to be certain that no memory will leak from this class:
- //there is nothing to do a priori to dispose of this class.
- private final String listenedFileFullPath;
-
- /**
- * @param listenedFile The file this object listens to. It is final.
- */
- public AbstractIFileChangeListener(IFile listenedFile) {
- listenedFileFullPath = listenedFile.getFullPath().toString();
- }
-
- /**
- * @return The file listened to. It is final.
- */
- public final String getListenedFileFullPath() {
- return listenedFileFullPath;
- }
-
- /**
- * @param event The change event. It is guaranteed that this
- * event's getResource() method returns the file that this object listens to.
- */
- public abstract void listenedFileChanged(IResourceChangeEvent event);
-
- /**
- * Interface implemented by the MessageEditorPlugin.
- * <p>
- * Describes the registry of file change listeners.
- *
- * </p>
- */
- public interface IFileChangeListenerRegistry {
- /**
- * @param rcl Adds a subscriber to a resource change event.
- */
- public void subscribe(AbstractIFileChangeListener fileChangeListener);
-
- /**
- * @param rcl Removes a subscriber to a resource change event.
- */
- public void unsubscribe(AbstractIFileChangeListener fileChangeListener);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/AbstractMessageModel.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/AbstractMessageModel.java
deleted file mode 100644
index 1020871e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/AbstractMessageModel.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-import java.io.Serializable;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.configuration.DirtyHack;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-
-
-/**
- * A convenience base class for observable message-related classes.
- * This class follows the conventions and recommendations as described
- * in the <a href="http://java.sun.com/products/javabeans/docs/spec.html">SUN
- * JavaBean specifications</a>.
- *
- * @author Pascal Essiembre ([email protected])
- * @author Karsten Lentzsch ([email protected])
- */
-public abstract class AbstractMessageModel implements Serializable {
- /** Handles <code>PropertyChangeListeners</code>. */
- private transient PropertyChangeSupport changeSupport;
-
- /**
- * Adds a PropertyChangeListener to the listener list. The listener is
- * registered for all properties of this class.<p>
- * Adding a <code>null</code> listener has no effect.
- *
- * @param listener the PropertyChangeListener to be added
- */
- /*default*/ final synchronized void addPropertyChangeListener(
- final PropertyChangeListener listener) {
- if (listener == null) {
- return;
- }
- if (changeSupport == null) {
- changeSupport = new PropertyChangeSupport(this);
- }
- changeSupport.addPropertyChangeListener(listener);
- }
-
- /**
- * Removes a PropertyChangeListener from the listener list. This method
- * should be used to remove PropertyChangeListeners that were registered
- * for all bound properties of this class.<p>
- * Removing a <code>null</code> listener has no effect.
- *
- * @param listener the PropertyChangeListener to be removed
- */
- /*default*/ final synchronized void removePropertyChangeListener(
- final PropertyChangeListener listener) {
- if (listener == null || changeSupport == null) {
- return;
- }
- changeSupport.removePropertyChangeListener(listener);
- }
-
- /**
- * Returns an array of all the property change listeners registered on
- * this component.
- *
- * @return all of this component's <code>PropertyChangeListener</code>s
- * or an empty array if no property change
- * listeners are currently registered
- */
- /*default*/ final synchronized
- PropertyChangeListener[] getPropertyChangeListeners() {
- if (changeSupport == null) {
- return new PropertyChangeListener[0];
- }
- return changeSupport.getPropertyChangeListeners();
- }
-
- /**
- * Support for reporting bound property changes for Object properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final Object oldValue,
- final Object newValue) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(propertyName, oldValue, newValue);
- }
-
- /**
- * Support for reporting bound property changes for boolean properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final boolean oldValue,
- final boolean newValue) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(propertyName, oldValue, newValue);
- }
-
- /**
- * Support for reporting bound property changes for events.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param event the event that triggered the change
- */
- protected final void firePropertyChange(
- final PropertyChangeEvent event) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(event);
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final double oldValue,
- final double newValue) {
- firePropertyChange(
- propertyName, new Double(oldValue), new Double(newValue));
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final float oldValue,
- final float newValue) {
- firePropertyChange(
- propertyName, new Float(oldValue), new Float(newValue));
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final int oldValue,
- final int newValue) {
- if (changeSupport == null || !DirtyHack.isFireEnabled()) {
- return;
- }
- changeSupport.firePropertyChange(propertyName, oldValue, newValue);
- }
-
- /**
- * Support for reporting bound property changes for integer properties.
- * This method can be called when a bound property has changed and it will
- * send the appropriate PropertyChangeEvent to any registered
- * PropertyChangeListeners.
- *
- * @param propertyName the property whose value has changed
- * @param oldValue the property's previous value
- * @param newValue the property's new value
- */
- protected final void firePropertyChange(
- final String propertyName,
- final long oldValue,
- final long newValue) {
- firePropertyChange(
- propertyName, new Long(oldValue), new Long(newValue));
- }
-
- /**
- * Checks and answers if the two objects are both <code>null</code>
- * or equal.
- *
- * @param o1 the first object to compare
- * @param o2 the second object to compare
- * @return boolean true if and only if both objects are <code>null</code>
- * or equal
- */
- protected final boolean equals(final Object o1, final Object o2) {
- return BabelUtils.equals(o1, o2);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/IMessagesBundleGroupListener.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/IMessagesBundleGroupListener.java
deleted file mode 100644
index bc21fb60..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/IMessagesBundleGroupListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-
-/**
- * A listener for changes on a {@link MessagesBundleGroup}.
- * @author Pascal Essiembre ([email protected])
- * @see MessagesBundleGroup
- */
-public interface IMessagesBundleGroupListener extends IMessagesBundleListener {
-
- /**
- * A message key has been added.
- * @param key the added key
- */
- void keyAdded(String key);
- /**
- * A message key has been removed.
- * @param key the removed key
- */
- void keyRemoved(String key);
- /**
- * A messages bundle has been added.
- * @param messagesBundle the messages bundle
- */
- void messagesBundleAdded(MessagesBundle messagesBundle);
- /**
- * A messages bundle has been removed.
- * @param messagesBundle the messages bundle
- */
- void messagesBundleRemoved(MessagesBundle messagesBundle);
- /**
- * A messages bundle was modified.
- * @param messagesBundle the messages bundle
- */
- void messagesBundleChanged(
- MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/IMessagesBundleListener.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/IMessagesBundleListener.java
deleted file mode 100644
index f615a300..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/IMessagesBundleListener.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-
-/**
- * A listener for changes on a {@link MessagesBundle}.
- * @author Pascal Essiembre ([email protected])
- * @see MessagesBundle
- */
-public interface IMessagesBundleListener extends PropertyChangeListener {
- /**
- * A message was added.
- * @param messagesBundle the messages bundle on which the message was added.
- * @param message the message
- */
- void messageAdded(MessagesBundle messagesBundle, Message message);
- /**
- * A message was removed.
- * @param messagesBundle the messages bundle on which the message was
- * removed.
- * @param message the message
- */
- void messageRemoved(MessagesBundle messagesBundle, Message message);
- /**
- * A message was changed.
- * @param messagesBundle the messages bundle on which the message was
- * changed.
- * @param message the message
- */
- void messageChanged(
- MessagesBundle messagesBundle, PropertyChangeEvent changeEvent);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/Message.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/Message.java
deleted file mode 100644
index 81978223..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/Message.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeListener;
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-
-/**
- * A single entry in a <code>MessagesBundle</code>.
- *
- * @author Pascal Essiembre ([email protected])
- * @see MessagesBundle
- * @see MessagesBundleGroup
- */
-public final class Message extends AbstractMessageModel implements IMessage {
-
- /** For serialisation. */
- private static final long serialVersionUID = 1160670351341655427L;
-
- public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
- public static final String PROPERTY_ACTIVE = "active"; //$NON-NLS-1$
- public static final String PROPERTY_TEXT = "text"; //$NON-NLS-1$
-
- /** Entry unique identifier. */
- private final String key;
- /** Entry locale. */
- private final Locale locale;
- /** Entry comment. */
- private String comment;
- /** Whether this entry is commented out or not. */
- private boolean active = true;
- /** Entry text. */
- private String text;
-
- /**
- * Constructor. Key and locale arguments are <code>null</code> safe.
- * @param key unique identifier within a messages bundle
- * @param locale the message locale
- */
- public Message(final String key, final Locale locale) {
- super();
- this.key = (key == null ? "" : key); //$NON-NLS-1$
- this.locale = locale;
- }
-
-
-
- /**
- * Sets the message comment.
- * @param comment The comment to set.
- */
- public void setComment(String comment) {
- Object oldValue = this.comment;
- this.comment = comment;
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
- }
-
- public void setComment(String comment, boolean silent) {
- Object oldValue = this.comment;
- this.comment = comment;
- if (!silent) {
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
- }
- }
-
- /**
- * Sets whether the message is active or not. An inactive message is
- * one that we continue to keep track of, but will not be picked
- * up by internationalisation mechanism (e.g. <code>ResourceBundle</code>).
- * Typically, those are commented (i.e. //) key/text pairs in a
- * *.properties file.
- * @param active The active to set.
- */
- public void setActive(boolean active) {
- boolean oldValue = this.active;
- this.active = active;
- firePropertyChange(PROPERTY_ACTIVE, oldValue, active);
- }
-
- /**
- * Sets the actual message text.
- * @param text The text to set.
- */
- public void setText(String text) {
- Object oldValue = this.text;
- this.text = text;
- firePropertyChange(PROPERTY_TEXT, oldValue, text);
- }
-
- public void setText(String text, boolean silent) {
- Object oldValue = this.text;
- this.text = text;
- if (!silent) {
- firePropertyChange(PROPERTY_TEXT, oldValue, text);
- }
- }
-
- /**
- * Gets the comment associated with this message (<code>null</code> if
- * no comments).
- * @return Returns the comment.
- */
- public String getComment() {
- return comment;
- }
- /**
- * Gets the message key attribute.
- * @return Returns the key.
- */
- public String getKey() {
- return key;
- }
-
- /**
- * Gets the message text.
- * @return Returns the text.
- */
- public String getValue() {
- return text;
- }
-
- /**
- * Gets the message locale.
- * @return Returns the locale
- */
- public Locale getLocale() {
- return locale;
- }
-
- /**
- * Gets whether this message is active or not.
- * @return <code>true</code> if this message is active.
- */
- public boolean isActive() {
- return active;
- }
-
- /**
- * Copies properties of the given message to this message.
- * The properties copied over are all properties but the
- * message key and locale.
- * @param message
- */
- protected void copyFrom(IMessage message) {
- setComment(message.getComment());
- setActive(message.isActive());
- setText(message.getValue());
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof Message)) {
- return false;
- }
- Message entry = (Message) obj;
- return equals(key, entry.key)
- && equals(locale, entry.locale)
- && active == entry.active
- && equals(text, entry.text)
- && equals(comment, entry.comment);
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "Message=[[key=" + key //$NON-NLS-1$
- + "][text=" + text //$NON-NLS-1$
- + "][comment=" + comment //$NON-NLS-1$
- + "][active=" + active //$NON-NLS-1$
- + "]]"; //$NON-NLS-1$
- }
-
- public final synchronized void addMessageListener(
- final PropertyChangeListener listener) {
- addPropertyChangeListener(listener);
- }
- public final synchronized void removeMessageListener(
- final PropertyChangeListener listener) {
- removePropertyChangeListener(listener);
- }
- public final synchronized PropertyChangeListener[] getMessageListeners() {
- return getPropertyChangeListeners();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessageException.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessageException.java
deleted file mode 100644
index 1c22f95f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessageException.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-/**
- * Exception thrown when a message-related operation raised a problem.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessageException extends RuntimeException {
-
- /** For serialisation. */
- private static final long serialVersionUID = 5702621096263524623L;
-
- /**
- * Creates a new <code>MessageException</code>.
- */
- public MessageException() {
- super();
- }
-
- /**
- * Creates a new <code>MessageException</code>.
- * @param message exception message
- */
- public MessageException(String message) {
- super(message);
- }
-
- /**
- * Creates a new <code>MessageException</code>.
- * @param message exception message
- * @param cause root cause
- */
- public MessageException(String message, Throwable cause) {
- super(message, cause);
- }
-
- /**
- * Creates a new <code>MessageException</code>.
- * @param cause root cause
- */
- public MessageException(Throwable cause) {
- super(cause);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundle.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundle.java
deleted file mode 100644
index 75a34673..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundle.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResourceChangeListener;
-
-/**
- * For a given scope, all messages for a national language.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundle extends AbstractMessageModel
- implements IMessagesResourceChangeListener, IMessagesBundle {
-
- private static final long serialVersionUID = -331515196227475652L;
-
- public static final String PROPERTY_COMMENT = "comment"; //$NON-NLS-1$
- public static final String PROPERTY_MESSAGES_COUNT =
- "messagesCount"; //$NON-NLS-1$
-
- private static final IMessagesBundleListener[] EMPTY_MSG_BUNDLE_LISTENERS =
- new IMessagesBundleListener[] {};
- private final Collection<String> orderedKeys = new ArrayList<String>();
- private final Map<String, IMessage> keyedMessages = new HashMap<String, IMessage>();
-
- private final IMessagesResource resource;
-
- private final PropertyChangeListener messageListener =
- new PropertyChangeListener(){
- public void propertyChange(PropertyChangeEvent event) {
- fireMessageChanged(event);
- }
- };
- private String comment;
-
- /**
- * Creates a new <code>MessagesBundle</code>.
- * @param resource the messages bundle resource
- */
- public MessagesBundle(IMessagesResource resource) {
- super();
- this.resource = resource;
- readFromResource();
- // Handle resource changes
- resource.addMessagesResourceChangeListener(
- new IMessagesResourceChangeListener(){
- public void resourceChanged(IMessagesResource changedResource) {
- readFromResource();
- }
- });
- // Handle bundle changes
- addMessagesBundleListener(new MessagesBundleAdapter() {
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- writetoResource();
- }
- public void propertyChange(PropertyChangeEvent evt) {
- writetoResource();
- }
- });
- }
-
- /**
- * Called before this object will be discarded.
- */
- public void dispose() {
- this.resource.dispose();
- }
-
- /**
- * Gets the underlying messages resource implementation.
- * @return
- */
- public IMessagesResource getResource() {
- return resource;
- }
-
- public int getMessagesCount() {
- return keyedMessages.size();
- }
-
- /**
- * Gets the locale for the messages bundle (<code>null</code> assumes
- * the default system locale).
- * @return Returns the locale.
- */
- public Locale getLocale() {
- return resource.getLocale();
- }
-
- /**
- * Gets the overall comment, or description, for this messages bundle..
- * @return Returns the comment.
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the comment for this messages bundle.
- * @param comment The comment to set.
- */
- public void setComment(String comment) {
- Object oldValue = this.comment;
- this.comment = comment;
- firePropertyChange(PROPERTY_COMMENT, oldValue, comment);
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource
- * .IMessagesResourceChangeListener#resourceChanged(
- * org.eclipse.babel.core.message.resource.IMessagesResource)
- */
- public void resourceChanged(IMessagesResource changedResource) {
- this.resource.deserialize(this);
- }
-
- /**
- * Adds a message to this messages bundle. If the message already exists
- * its properties are updated and no new message is added.
- * @param message the message to add
- */
- public void addMessage(IMessage message) {
- Message m = (Message) message;
- int oldCount = getMessagesCount();
- if (!orderedKeys.contains(m.getKey())) {
- orderedKeys.add(m.getKey());
- }
- if (!keyedMessages.containsKey(m.getKey())) {
- keyedMessages.put(m.getKey(), m);
- m.addMessageListener(messageListener);
- firePropertyChange(
- PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
- fireMessageAdded(m);
- } else {
- // Entry already exists, update it.
- Message matchingEntry = (Message) keyedMessages.get(m.getKey());
- matchingEntry.copyFrom(m);
- }
- }
- /**
- * Removes a message from this messages bundle.
- * @param messageKey the key of the message to remove
- */
- public void removeMessage(String messageKey) {
- int oldCount = getMessagesCount();
- orderedKeys.remove(messageKey);
- Message message = (Message) keyedMessages.get(messageKey);
- if (message != null) {
- message.removePropertyChangeListener(messageListener);
- keyedMessages.remove(messageKey);
- firePropertyChange(
- PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount());
- fireMessageRemoved(message);
- }
- }
- /**
- * Removes messages from this messages bundle.
- * @param messageKeys the keys of the messages to remove
- */
- public void removeMessages(String[] messageKeys) {
- for (int i = 0; i < messageKeys.length; i++) {
- removeMessage(messageKeys[i]);
- }
- }
-
- /**
- * Renames a message key.
- * @param sourceKey the message key to rename
- * @param targetKey the new key for the message
- * @throws MessageException if the target key already exists
- */
- public void renameMessageKey(String sourceKey, String targetKey) {
- if (getMessage(targetKey) != null) {
- throw new MessageException(
- "Cannot rename: target key already exists."); //$NON-NLS-1$
- }
- IMessage sourceEntry = getMessage(sourceKey);
- if (sourceEntry != null) {
- Message targetEntry = new Message(targetKey, getLocale());
- targetEntry.copyFrom(sourceEntry);
- removeMessage(sourceKey);
- addMessage(targetEntry);
- }
- }
- /**
- * Duplicates a message.
- * @param sourceKey the message key to duplicate
- * @param targetKey the new message key
- * @throws MessageException if the target key already exists
- */
- public void duplicateMessage(String sourceKey, String targetKey) {
- if (getMessage(sourceKey) != null) {
- throw new MessageException(
- "Cannot duplicate: target key already exists."); //$NON-NLS-1$
- }
- IMessage sourceEntry = getMessage(sourceKey);
- if (sourceEntry != null) {
- Message targetEntry = new Message(targetKey, getLocale());
- targetEntry.copyFrom(sourceEntry);
- addMessage(targetEntry);
- }
- }
-
- /**
- * Gets a message.
- * @param key a message key
- * @return a message
- */
- public IMessage getMessage(String key) {
- return keyedMessages.get(key);
- }
-
- /**
- * Adds an empty message.
- * @param key the new message key
- */
- public void addMessage(String key) {
- addMessage(new Message(key, getLocale()));
- }
-
- /**
- * Gets all message keys making up this messages bundle.
- * @return message keys
- */
- public String[] getKeys() {
- return orderedKeys.toArray(BabelUtils.EMPTY_STRINGS);
- }
-
- /**
- * Obtains the set of <code>Message</code> objects in this bundle.
- * @return a collection of <code>Message</code> objects in this bundle
- */
- public Collection<IMessage> getMessages() {
- return keyedMessages.values();
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- String str = "MessagesBundle=[[locale=" + getLocale() //$NON-NLS-1$
- + "][comment=" + comment //$NON-NLS-1$
- + "][entries="; //$NON-NLS-1$
- for (IMessage message : getMessages()) {
- str += message.toString();
- }
- str += "]]"; //$NON-NLS-1$
- return str;
- }
-
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- final int PRIME = 31;
- int result = 1;
- result = PRIME * result + ((comment == null) ? 0 : comment.hashCode());
- result = PRIME * result + ((messageListener == null)
- ? 0 : messageListener.hashCode());
- result = PRIME * result + ((keyedMessages == null)
- ? 0 : keyedMessages.hashCode());
- result = PRIME * result + ((orderedKeys == null)
- ? 0 : orderedKeys.hashCode());
- result = PRIME * result + ((resource == null)
- ? 0 : resource.hashCode());
- return result;
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof MessagesBundle)) {
- return false;
- }
- MessagesBundle messagesBundle = (MessagesBundle) obj;
- return equals(comment, messagesBundle.comment)
- && equals(keyedMessages, messagesBundle.keyedMessages);
- }
-
- public final synchronized void addMessagesBundleListener(
- final IMessagesBundleListener listener) {
- addPropertyChangeListener(listener);
- }
- public final synchronized void removeMessagesBundleListener(
- final IMessagesBundleListener listener) {
- removePropertyChangeListener(listener);
- }
- public final synchronized IMessagesBundleListener[]
- getMessagesBundleListeners() {
- //TODO find more efficient way to avoid class cast.
- return Arrays.asList(
- getPropertyChangeListeners()).toArray(
- EMPTY_MSG_BUNDLE_LISTENERS);
- }
-
-
- private void readFromResource() {
- this.resource.deserialize(this);
- }
- private void writetoResource() {
- this.resource.serialize(this);
- }
-
- private void fireMessageAdded(Message message) {
- IMessagesBundleListener[] listeners = getMessagesBundleListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleListener listener = listeners[i];
- listener.messageAdded(this, message);
- }
- }
- private void fireMessageRemoved(Message message) {
- IMessagesBundleListener[] listeners = getMessagesBundleListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleListener listener = listeners[i];
- listener.messageRemoved(this, message);
- }
- }
- private void fireMessageChanged(PropertyChangeEvent event) {
- IMessagesBundleListener[] listeners = getMessagesBundleListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleListener listener = listeners[i];
- listener.messageChanged(this, event);
- }
- }
-
- public String getValue(String key) {
- return getMessage(key).getValue();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleAdapter.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleAdapter.java
deleted file mode 100644
index 43831254..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleAdapter.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-
-/**
- * An adapter class for a {@link IMessagesBundleListener}. Methods
- * implementation do nothing.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundleAdapter implements IMessagesBundleListener {
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleListener#messageAdded(
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.Message)
- */
- public void messageAdded(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleListener
- * #messageChanged(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * java.beans.PropertyChangeEvent)
- */
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleListener
- * #messageRemoved(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.Message)
- */
- public void messageRemoved(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see java.beans.PropertyChangeListener#propertyChange(
- * java.beans.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent evt) {
- // do nothing
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleGroup.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleGroup.java
deleted file mode 100644
index 2b3a8a17..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleGroup.java
+++ /dev/null
@@ -1,511 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.manager.RBManager;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.strategy.IMessagesBundleGroupStrategy;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.strategy.PropertiesFileGroupStrategy;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-/**
- * Grouping of all messages bundle of the same kind.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundleGroup extends AbstractMessageModel implements IMessagesBundleGroup {
-
- private String projectName;
-
- private static final IMessagesBundleGroupListener[]
- EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {};
- private static final Message[] EMPTY_MESSAGES = new Message[] {};
-
- public static final String PROPERTY_MESSAGES_BUNDLE_COUNT =
- "messagesBundleCount"; //$NON-NLS-1$
- public static final String PROPERTY_KEY_COUNT =
- "keyCount"; //$NON-NLS-1$
-
- /** For serialization. */
- private static final long serialVersionUID = -1977849534191384324L;
- /** Bundles forming the group (key=Locale; value=MessagesBundle). */
- private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>();
- private final Set<String> keys = new TreeSet<String>();
- private final IMessagesBundleListener messagesBundleListener =
- new MessagesBundleListener();
-
- private final IMessagesBundleGroupStrategy groupStrategy;
- private static final Locale[] EMPTY_LOCALES = new Locale[] {};
- private final String name;
- private final String resourceBundleId;
-
- /**
- * Creates a new messages bundle group.
- * @param groupStrategy a IMessagesBundleGroupStrategy instance
- */
- public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) {
- super();
- this.groupStrategy = groupStrategy;
- this.name = groupStrategy.createMessagesBundleGroupName();
- this.resourceBundleId = groupStrategy.createMessagesBundleId();
-
- this.projectName = groupStrategy.getProjectName();
-
- MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
- if (bundles != null) {
- for (int i = 0; i < bundles.length; i++) {
- addMessagesBundle(bundles[i]);
- }
- }
-
- RBManager.getInstance(this.projectName).notifyMessagesBundleCreated(this);
- }
-
- /**
- * Called before this object will be discarded.
- * Disposes the underlying MessageBundles
- */
- public void dispose() {
- for (IMessagesBundle mb : getMessagesBundles()) {
- try {
- mb.dispose();
- } catch (Throwable t) {
- //FIXME: remove debug:
- System.err.println("Error disposing message-bundle " +
- ((MessagesBundle)mb).getResource().getResourceLocationLabel());
- //disregard crashes: this is a best effort to dispose things.
- }
- }
-
- RBManager.getInstance(this.projectName).notifyMessagesBundleDeleted(this);
- }
-
-
- /**
- * Gets the messages bundle matching given locale.
- * @param locale locale of bundle to retreive
- * @return a bundle
- */
- public IMessagesBundle getMessagesBundle(Locale locale) {
- return localeBundles.get(locale);
- }
-
- /**
- * Gets the messages bundle matching given source object. A source
- * object being a context-specific concrete underlying implementation of a
- * <code>MessagesBundle</code> as per defined in
- * <code>IMessageResource</code>.
- * @param source the source object to match
- * @return a messages bundle
- * @see IMessagesResource
- */
- public MessagesBundle getMessagesBundle(Object source) {
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- if (equals(source, ((MessagesBundle)messagesBundle).getResource().getSource())) {
- return (MessagesBundle) messagesBundle;
- }
- }
- return null;
- }
-
- /**
- * Adds an empty <code>MessagesBundle</code> to this group for the
- * given locale.
- * @param locale locale for the new bundle added
- */
- public void addMessagesBundle(Locale locale) {
- addMessagesBundle(groupStrategy.createMessagesBundle(locale));
- }
-
- /**
- * Gets all locales making up this messages bundle group.
- */
- public Locale[] getLocales() {
- return localeBundles.keySet().toArray(EMPTY_LOCALES);
- }
-
- /**
- * Gets all messages associated with the given message key.
- * @param key a message key
- * @return messages
- */
- public IMessage[] getMessages(String key) {
- List<IMessage> messages = new ArrayList<IMessage>();
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- IMessage message = messagesBundle.getMessage(key);
- if (message != null) {
- messages.add(message);
- }
- }
- return messages.toArray(EMPTY_MESSAGES);
- }
-
- /**
- * Gets the message matching given key and locale.
- * @param locale locale for which to retrieve the message
- * @param key key matching entry to retrieve the message
- * @return a message
- */
- public IMessage getMessage(String key, Locale locale) {
- IMessagesBundle messagesBundle = getMessagesBundle(locale);
- if (messagesBundle != null) {
- return messagesBundle.getMessage(key);
- }
- return null;
- }
-
-
- /**
- * Adds a messages bundle to this group.
- * @param messagesBundle bundle to add
- * @throws MessageException if a messages bundle for the same locale
- * already exists.
- */
- public void addMessagesBundle(IMessagesBundle messagesBundle) {
- addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
- }
-
- public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) {
- MessagesBundle mb = (MessagesBundle) messagesBundle;
- if (localeBundles.get(mb.getLocale()) != null) {
- throw new MessageException(
- "A bundle with the same locale already exists."); //$NON-NLS-1$
- }
-
- int oldBundleCount = localeBundles.size();
- localeBundles.put(mb.getLocale(), mb);
-
- firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT,
- oldBundleCount, localeBundles.size());
- fireMessagesBundleAdded(mb);
-
- String[] bundleKeys = mb.getKeys();
- for (int i = 0; i < bundleKeys.length; i++) {
- String key = bundleKeys[i];
- if (!keys.contains(key)) {
- int oldKeyCount = keys.size();
- keys.add(key);
- firePropertyChange(
- PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
- fireKeyAdded(key);
- }
- }
- mb.addMessagesBundleListener(messagesBundleListener);
-
- }
-
- public void removeMessagesBundle(IMessagesBundle messagesBundle) {
- Locale locale = messagesBundle.getLocale();
-
- if (localeBundles.containsKey(locale)) {
- localeBundles.remove(locale);
- }
-
- // which keys should I not remove?
- Set<String> keysNotToRemove = new TreeSet<String>();
-
- for (String key : messagesBundle.getKeys()) {
- for (IMessagesBundle bundle : localeBundles.values()) {
- if (bundle.getMessage(key) != null) {
- keysNotToRemove.add(key);
- }
- }
- }
-
- // remove keys
- for (String keyToRemove : messagesBundle.getKeys()) {
- if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
- keys.remove(keyToRemove);
- }
- }
- }
-
- /**
- * Gets this messages bundle group name.
- * @return bundle group name
- */
- public String getName() {
- return name;
- }
-
- /**
- * Adds an empty message to every messages bundle of this group with the
- * given.
- * @param key message key
- */
- public void addMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- ((MessagesBundle)msgBundle).addMessage(key);
- }
- }
-
- /**
- * Renames a key in all messages bundles forming this group.
- * @param sourceKey the message key to rename
- * @param targetKey the new message name
- */
- public void renameMessageKeys(String sourceKey, String targetKey) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.renameMessageKey(
- sourceKey, targetKey);
- }
- }
-
- /**
- * Removes messages matching the given key from all messages bundle.
- * @param key key of messages to remove
- */
- public void removeMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.removeMessage(key);
- }
- }
-
- /**
- * Sets whether messages matching the <code>key</code> are active or not.
- * @param key key of messages
- */
- public void setMessagesActive(String key, boolean active) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- IMessage entry = msgBundle.getMessage(key);
- if (entry != null) {
- entry.setActive(active);
- }
- }
- }
-
- /**
- * Duplicates each messages matching the <code>sourceKey</code> to
- * the <code>newKey</code>.
- * @param sourceKey original key
- * @param targetKey new key
- * @throws MessageException if a target key already exists
- */
- public void duplicateMessages(String sourceKey, String targetKey) {
- if (sourceKey.equals(targetKey)) {
- return;
- }
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.duplicateMessage(
- sourceKey, targetKey);
- }
- }
-
- /**
- * Returns a collection of all bundles in this group.
- * @return the bundles in this group
- */
- public Collection<IMessagesBundle> getMessagesBundles() {
- return localeBundles.values();
- }
-
- /**
- * Gets all keys from all messages bundles.
- * @return all keys from all messages bundles
- */
- public String[] getMessageKeys() {
- return keys.toArray(BabelUtils.EMPTY_STRINGS);
- }
-
- /**
- * Whether the given key is found in this messages bundle group.
- * @param key the key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
- public boolean isMessageKey(String key) {
- return keys.contains(key);
- }
-
- /**
- * Gets the number of messages bundles in this group.
- * @return the number of messages bundles in this group
- */
- public int getMessagesBundleCount() {
- return localeBundles.size();
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof MessagesBundleGroup)) {
- return false;
- }
- MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
- return equals(localeBundles, messagesBundleGroup.localeBundles);
- }
-
- public final synchronized void addMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- addPropertyChangeListener(listener);
- }
- public final synchronized void removeMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- removePropertyChangeListener(listener);
- }
- public final synchronized IMessagesBundleGroupListener[]
- getMessagesBundleGroupListeners() {
- //TODO find more efficient way to avoid class cast.
- return Arrays.asList(
- getPropertyChangeListeners()).toArray(
- EMPTY_GROUP_LISTENERS);
- }
-
-
- private void fireKeyAdded(String key) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyAdded(key);
- }
- }
- private void fireKeyRemoved(String key) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyRemoved(key);
- }
- }
- private void fireMessagesBundleAdded(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleAdded(messagesBundle);
- }
- }
- private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleRemoved(messagesBundle);
- }
- }
-
- /**
- * Returns true if the supplied key is already existing in this group.
- *
- * @param key The key that shall be tested.
- *
- * @return true <=> The key is already existing.
- */
- public boolean containsKey(String key) {
- for (Locale locale : localeBundles.keySet()) {
- IMessagesBundle messagesBundle = localeBundles.get(locale);
- for (String k : messagesBundle.getKeys()) {
- if (k.equals(key)) {
- return true;
- } else {
- continue;
- }
- }
- }
- return false;
- }
-
- /**
- * Is the given key found in this bundle group.
- * @param key the key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
- public boolean isKey(String key) {
- return keys.contains(key);
- }
-
-
-
- public String getResourceBundleId() {
- return resourceBundleId;
- }
-
- public String getProjectName() {
- return this.projectName;
- }
-
- /**
- * Class listening for changes in underlying messages bundle and
- * relays them to the listeners for MessagesBundleGroup.
- */
- private class MessagesBundleListener implements IMessagesBundleListener {
- public void messageAdded(MessagesBundle messagesBundle,
- Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageAdded(messagesBundle, message);
- if (getMessages(message.getKey()).length == 1) {
- keys.add(message.getKey());
- firePropertyChange(
- PROPERTY_KEY_COUNT, oldCount, keys.size());
- fireKeyAdded(message.getKey());
- }
- }
- }
- public void messageRemoved(MessagesBundle messagesBundle,
- Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageRemoved(messagesBundle, message);
- int keyMessagesCount = getMessages(message.getKey()).length;
- if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
- keys.remove(message.getKey());
- firePropertyChange(
- PROPERTY_KEY_COUNT, oldCount, keys.size());
- fireKeyRemoved(message.getKey());
- }
- }
- }
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageChanged(messagesBundle, changeEvent);
- }
- }
- // MessagesBundle property changes:
- public void propertyChange(PropertyChangeEvent evt) {
- MessagesBundle bundle = (MessagesBundle) evt.getSource();
- IMessagesBundleGroupListener[] listeners =
- getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleChanged(bundle, evt);
- }
- }
- }
-
- public boolean hasPropertiesFileGroupStrategy() {
- return groupStrategy instanceof PropertiesFileGroupStrategy;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleGroupAdapter.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleGroupAdapter.java
deleted file mode 100644
index 53f985cd..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/MessagesBundleGroupAdapter.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.message;
-
-import java.beans.PropertyChangeEvent;
-
-/**
- * An adapter class for a {@link IMessagesBundleGroupListener}. Methods
- * implementation do nothing.
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesBundleGroupAdapter
- implements IMessagesBundleGroupListener {
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleGroupListener#
- * keyAdded(java.lang.String)
- */
- public void keyAdded(String key) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleGroupListener#
- * keyRemoved(java.lang.String)
- */
- public void keyRemoved(String key) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleGroupListener#
- * messagesBundleAdded(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle)
- */
- public void messagesBundleAdded(MessagesBundle messagesBundle) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleGroupListener#
- * messagesBundleChanged(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * java.beans.PropertyChangeEvent)
- */
- public void messagesBundleChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleGroupListener
- * #messagesBundleRemoved(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle)
- */
- public void messagesBundleRemoved(MessagesBundle messagesBundle) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleListener#messageAdded(
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.Message)
- */
- public void messageAdded(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleListener#
- * messageChanged(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * java.beans.PropertyChangeEvent)
- */
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.IMessagesBundleListener#
- * messageRemoved(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle,
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.Message)
- */
- public void messageRemoved(MessagesBundle messagesBundle, Message message) {
- // do nothing
- }
- /**
- * @see java.beans.PropertyChangeListener#propertyChange(
- * java.beans.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent evt) {
- // do nothing
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/DuplicateValueCheck.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/DuplicateValueCheck.java
deleted file mode 100644
index f7874da6..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/DuplicateValueCheck.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Checks if key as a duplicate value.
- * @author Pascal Essiembre ([email protected])
- */
-public class DuplicateValueCheck implements IMessageCheck {
-
- private String[] duplicateKeys;
-
- /**
- * Constructor.
- */
- public DuplicateValueCheck() {
- super();
- }
-
- /**
- * Resets the collected keys to null.
- */
- public void reset() {
- duplicateKeys = null;
- }
-
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
- Collection<String> keys = new ArrayList<String>();
- if (message != null) {
- IMessagesBundle messagesBundle =
- messagesBundleGroup.getMessagesBundle(message.getLocale());
- for (IMessage duplicateEntry : messagesBundle.getMessages()) {
- if (!message.getKey().equals(duplicateEntry.getKey())
- && BabelUtils.equals(message.getValue(),
- duplicateEntry.getValue())) {
- keys.add(duplicateEntry.getKey());
- }
- }
- if (!keys.isEmpty()) {
- keys.add(message.getKey());
- }
- }
-
- duplicateKeys = keys.toArray(new String[]{});
- return !keys.isEmpty();
- }
-
- public String[] getDuplicateKeys() {
- return duplicateKeys;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/IMessageCheck.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/IMessageCheck.java
deleted file mode 100644
index 8957ae2d..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/IMessageCheck.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.Message;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * All purpose {@link Message} testing. Use this interface to establish
- * whether a message within a {@link MessagesBundleGroup} is answering
- * successfully to any condition.
- * @author Pascal Essiembre ([email protected])
- */
-public interface IMessageCheck {
-
- /**
- * Checks whether a {@link Message} meets the implemented condition.
- * @param messagesBundleGroup messages bundle group
- * @param message the message being tested
- * @return <code>true</code> if condition is successfully tested
- */
- boolean checkKey(IMessagesBundleGroup messagesBundleGroup, IMessage message);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/MissingValueCheck.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/MissingValueCheck.java
deleted file mode 100644
index 5f9e1c1e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/MissingValueCheck.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Visitor for finding if a key has at least one corresponding bundle entry
- * with a missing value.
- * @author Pascal Essiembre ([email protected])
- */
-public class MissingValueCheck implements IMessageCheck {
-
- /** The singleton */
- public static MissingValueCheck MISSING_KEY = new MissingValueCheck();
-
- /**
- * Constructor.
- */
- private MissingValueCheck() {
- super();
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.checks.IMessageCheck#checkKey(
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup,
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.Message)
- */
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
- if (message == null || message.getValue() == null
- || message.getValue().length() == 0) {
- return true;
- }
- return false;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/SimilarValueCheck.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/SimilarValueCheck.java
deleted file mode 100644
index f7e3ec98..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/SimilarValueCheck.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.checks.proximity.IProximityAnalyzer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-
-/**
- * Checks if key as a duplicate value.
- * @author Pascal Essiembre ([email protected])
- */
-public class SimilarValueCheck implements IMessageCheck {
-
- private String[] similarKeys;
- private IProximityAnalyzer analyzer;
-
- /**
- * Constructor.
- */
- public SimilarValueCheck(IProximityAnalyzer analyzer) {
- super();
- this.analyzer = analyzer;
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.checks.IMessageCheck#checkKey(
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup,
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.Message)
- */
- public boolean checkKey(
- IMessagesBundleGroup messagesBundleGroup, IMessage message) {
- Collection<String> keys = new ArrayList<String>();
- if (message != null) {
- //TODO have case as preference
- String value1 = message.getValue().toLowerCase();
- IMessagesBundle messagesBundle =
- messagesBundleGroup.getMessagesBundle(message.getLocale());
- for (IMessage similarEntry : messagesBundle.getMessages()) {
- if (!message.getKey().equals(similarEntry.getKey())) {
- String value2 = similarEntry.getValue().toLowerCase();
- //TODO have preference to report identical as similar
- if (!BabelUtils.equals(value1, value2)
- && analyzer.analyse(value1, value2) >= 0.75) {
- //TODO use preferences
-// >= RBEPreferences.getReportSimilarValuesPrecision()) {
- keys.add(similarEntry.getKey());
- }
- }
- }
- if (!keys.isEmpty()) {
- keys.add(message.getKey());
- }
- }
- similarKeys = keys.toArray(new String[]{});
- return !keys.isEmpty();
- }
-
- /**
- * Gets similar keys.
- * @return similar keys
- */
- public String[] getSimilarMessageKeys() {
- return similarKeys;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/IProximityAnalyzer.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/IProximityAnalyzer.java
deleted file mode 100644
index f9545be5..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/IProximityAnalyzer.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks.proximity;
-
-/**
- * Analyse the proximity of two objects (i.e., how similar they are) and return
- * a proximity level between zero and one. The higher the return value is,
- * the closer the two objects are to each other. "One" does not need to mean
- * "identical", but it has to be the closest match and analyser can
- * potentially achieve.
- * @author Pascal Essiembre ([email protected])
- */
-public interface IProximityAnalyzer {
- /**
- * Analyses two objects and return the proximity level.
- *
- * @param str1 first object to analyse (cannot be null)
- * @param str2 second object to analyse (cannot be null)
- * @return proximity level
- */
- double analyse(String str1, String str2);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java
deleted file mode 100644
index 4de6644a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks.proximity;
-
-
-/**
- * Compares two strings (case insensitive) and returns a proximity level based
- * on the number of character transformation required to have identical strings.
- * Non-string objects are converted to strings using the <code>toString()</code>
- * method. The exact algorithm was taken from Micheal Gilleland
- * (<a href="http://merriampark.com/ld.htm">http://merriampark.com/ld.htm</a>).
- * @author Pascal Essiembre ([email protected])
- */
-public class LevenshteinDistanceAnalyzer implements IProximityAnalyzer {
-
- private static final IProximityAnalyzer INSTANCE =
- new LevenshteinDistanceAnalyzer();
-
- /**
- * Constructor.
- */
- private LevenshteinDistanceAnalyzer() {
- //TODO add case sensitivity?
- super();
- }
-
- /**
- * Gets the unique instance.
- * @return a proximity analyzer
- */
- public static IProximityAnalyzer getInstance() {
- return INSTANCE;
- }
-
- /**
- * @see com.essiembre.eclipse.rbe.model.utils.IProximityAnalyzer
- * #analyse(java.lang.Object, java.lang.Object)
- */
- public double analyse(String str1, String str2) {
- int maxLength = Math.max(str1.length(), str2.length());
- double distance = distance(str1, str2);
-
- return 1d - (distance / maxLength);
- }
-
-
- /**
- * Retuns the minimum of three values.
- * @param a first value
- * @param b second value
- * @param c third value
- * @return lowest value
- */
- private int minimum(int a, int b, int c) {
- int mi;
-
- mi = a;
- if (b < mi) {
- mi = b;
- }
- if (c < mi) {
- mi = c;
- }
- return mi;
-
- }
-
- /***
- * Compute the distance
- * @param s source string
- * @param t target string
- * @return distance
- */
- public int distance(String s, String t) {
- int d[][]; // matrix
- int n; // length of s
- int m; // length of t
- int i; // iterates through s
- int j; // iterates through t
- char s_i; // ith character of s
- char t_j; // jth character of t
- int cost; // cost
-
- // Step 1
- n = s.length();
- m = t.length();
- if (n == 0) {
- return m;
- }
- if (m == 0) {
- return n;
- }
- d = new int[n + 1][m + 1];
-
- // Step 2
- for (i = 0; i <= n; i++) {
- d[i][0] = i;
- }
-
- for (j = 0; j <= m; j++) {
- d[0][j] = j;
- }
-
- // Step 3
- for (i = 1; i <= n; i++) {
- s_i = s.charAt(i - 1);
-
- // Step 4
- for (j = 1; j <= m; j++) {
- t_j = t.charAt(j - 1);
-
- // Step 5
- if (s_i == t_j) {
- cost = 0;
- } else {
- cost = 1;
- }
-
- // Step 6
- d[i][j] = minimum(d[i - 1][j] + 1, d[i][j - 1] + 1,
- d[i - 1][j - 1] + cost);
- }
- }
-
- // Step 7
- return d[n][m];
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/WordCountAnalyzer.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/WordCountAnalyzer.java
deleted file mode 100644
index aa5ff717..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/checks/proximity/WordCountAnalyzer.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.checks.proximity;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-
-/**
- * Compares two strings (case insensitive) and returns a proximity level
- * based on how many words there are, and how many words are the same
- * in both strings. Non-string objects are converted to strings using
- * the <code>toString()</code> method.
- * @author Pascal Essiembre ([email protected])
- */
-public class WordCountAnalyzer implements IProximityAnalyzer {
-
- private static final IProximityAnalyzer INSTANCE = new WordCountAnalyzer();
- private static final String WORD_SPLIT_PATTERN =
- "\r\n|\r|\n|\\s"; //$NON-NLS-1$
-
- /**
- * Constructor.
- */
- private WordCountAnalyzer() {
- //TODO add case sensitivity?
- super();
- }
-
- /**
- * Gets the unique instance.
- * @return a proximity analyzer
- */
- public static IProximityAnalyzer getInstance() {
- return INSTANCE;
- }
-
- /**
- * @see com.essiembre.eclipse.rbe.model.utils.IProximityAnalyzer
- * #analyse(java.lang.Object, java.lang.Object)
- */
- public double analyse(String words1, String words2) {
- Collection<String> str1 = new ArrayList<String>(
- Arrays.asList(words1.split(WORD_SPLIT_PATTERN)));
- Collection<String> str2 = new ArrayList<String>(
- Arrays.asList(words2.split(WORD_SPLIT_PATTERN)));
-
- int maxWords = Math.max(str1.size(), str2.size());
- if (maxWords == 0) {
- return 0;
- }
-
- int matchedWords = 0;
- for (String str : str1) {
- if (str2.remove(str)) {
- matchedWords++;
- }
- }
-
- return (double) matchedWords / (double) maxWords;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/IMessagesEditorListener.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/IMessagesEditorListener.java
deleted file mode 100644
index 92a610a3..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/IMessagesEditorListener.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.manager;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-public interface IMessagesEditorListener {
-
- void onSave();
-
- void onModify();
-
- void onResourceChanged(IMessagesBundle bundle);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/RBManager.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/RBManager.java
deleted file mode 100644
index 3000ca02..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/RBManager.java
+++ /dev/null
@@ -1,436 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.manager;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipselabs.tapiji.translator.rap.babel.core.configuration.ConfigurationManager;
-import org.eclipselabs.tapiji.translator.rap.babel.core.configuration.DirtyHack;
-import org.eclipselabs.tapiji.translator.rap.babel.core.factory.MessagesBundleGroupFactory;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.Message;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.PropertiesFileResource;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.strategy.PropertiesFileGroupStrategy;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.PDEUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- *
- * @author Alexej Strelzow
- */
-public class RBManager {
-
- private static Map<IProject, RBManager> managerMap = new HashMap<IProject, RBManager>();
-
- private Map<String, IMessagesBundleGroup> resourceBundles;
-
- private static RBManager INSTANCE;
-
- private List<IMessagesEditorListener> editorListeners;
-
- private IProject project;
-
- private RBManager() {
- resourceBundles = new HashMap<String, IMessagesBundleGroup>();
- editorListeners = new ArrayList<IMessagesEditorListener>(3);
- }
-
- public IMessagesBundleGroup getMessagesBundleGroup(String name) {
- if (!resourceBundles.containsKey(name)) {
- System.out.println("ohje"); // TODO log
- return null;
- } else {
- return resourceBundles.get(name);
- }
- }
-
- public List<String> getMessagesBundleGroupNames() {
- Set<String> keySet = resourceBundles.keySet();
- List<String> bundleGroupNames = new ArrayList<String>();
-
- for (String key : keySet) {
- bundleGroupNames.add(project.getName() + "/" + key);
- }
- return bundleGroupNames;
- }
-
- public static List<String> getAllMessagesBundleGroupNames() {
- Set<IProject> projects = getAllSupportedProjects();
- List<String> bundleGroupNames = new ArrayList<String>();
-
- for (IProject project : projects) {
- RBManager manager = getInstance(project);
- bundleGroupNames.addAll(manager.getMessagesBundleGroupNames());
- }
- return bundleGroupNames;
- }
-
- /**
- * Hier darf nur BABEL rein
- * @param bundleGroup
- */
- public void notifyMessagesBundleCreated(IMessagesBundleGroup bundleGroup) {
- if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
- IMessagesBundleGroup oldbundleGroup = resourceBundles.get(bundleGroup.getResourceBundleId());
- if (!equalHash(oldbundleGroup, bundleGroup)) {
- boolean oldHasPropertiesStrategy = oldbundleGroup.hasPropertiesFileGroupStrategy();
- boolean newHasPropertiesStrategy = bundleGroup.hasPropertiesFileGroupStrategy();
-
- // in this case, the old one is only writing to the property file, not the editor
- // we have to sync them and store the bundle with the editor as resource
- if (oldHasPropertiesStrategy && !newHasPropertiesStrategy) {
-
- syncBundles(bundleGroup, oldbundleGroup);
- resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
-
- oldbundleGroup.dispose();
-
- } else if ( (oldHasPropertiesStrategy && newHasPropertiesStrategy)
- || (!oldHasPropertiesStrategy && !newHasPropertiesStrategy) ) {
-
-// syncBundles(oldbundleGroup, bundleGroup); do not need that, because we take the new one
- // and we do that, because otherwise we cache old Text-Editor instances, which we
- // do not need -> read only phenomenon
- resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
-
- oldbundleGroup.dispose();
- } else {
- // in this case our old resource has an EditorSite, but not the new one
- bundleGroup.dispose();
- }
- }
- } else {
- resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup);
- }
- }
-
- /**
- * Hier darf nur BABEL rein
- * @param bundleGroup
- */
- public void notifyMessagesBundleDeleted(IMessagesBundleGroup bundleGroup) {
- if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) {
- if (equalHash(resourceBundles.get(bundleGroup.getResourceBundleId()), bundleGroup)) {
- resourceBundles.remove(bundleGroup.getResourceBundleId());
- System.out.println(bundleGroup.getResourceBundleId() + " deleted!");
- }
- }
- }
-
- public void notifyResourceRemoved(IResource resourceBundle) {
- //String parentName = resourceBundle.getParent().getName();
- //String resourceBundleId = parentName + "." + getResourceBundleName(resourceBundle);
- String resourceBundleId = PropertiesFileGroupStrategy.getResourceBundleId(resourceBundle);
- IMessagesBundleGroup bundleGroup = resourceBundles.get(resourceBundleId);
- if (bundleGroup != null) {
- Locale locale = getLocaleByName(getResourceBundleName(resourceBundle), resourceBundle.getName());
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(locale);
- if (messagesBundle != null) {
- bundleGroup.removeMessagesBundle(messagesBundle);
- }
- if (bundleGroup.getMessagesBundleCount() == 0) {
- notifyMessagesBundleDeleted(bundleGroup);
- }
- }
-
- // TODO: maybe save and reinit the editor?
-
- }
-
- /**
- * Weil der BABEL-Builder nicht richtig funkt (added 1 x und removed 2 x das GLEICHE!)
- * @param oldBundleGroup
- * @param newBundleGroup
- * @return
- */
- private boolean equalHash(IMessagesBundleGroup oldBundleGroup, IMessagesBundleGroup newBundleGroup) {
- int oldHashCode = oldBundleGroup.hashCode();
- int newHashCode = newBundleGroup.hashCode();
- return oldHashCode == newHashCode;
- }
-
- private void syncBundles(IMessagesBundleGroup oldBundleGroup, IMessagesBundleGroup newBundleGroup) {
- List<IMessagesBundle> bundlesToRemove = new ArrayList<IMessagesBundle>();
- List<IMessage> keysToRemove = new ArrayList<IMessage>();
-
- DirtyHack.setFireEnabled(false); // hebelt AbstractMessageModel aus
- // sonst m�ssten wir in setText von EclipsePropertiesEditorResource ein asyncExec zulassen
-
- for (IMessagesBundle newBundle : newBundleGroup.getMessagesBundles()) {
- IMessagesBundle oldBundle = oldBundleGroup.getMessagesBundle(newBundle.getLocale());
- if (oldBundle == null) { // it's a new one
- oldBundleGroup.addMessagesBundle(newBundle.getLocale(), newBundle);
- } else { // check keys
- for (IMessage newMsg : newBundle.getMessages()) {
- if (oldBundle.getMessage(newMsg.getKey()) == null) { // new entry, create new message
- oldBundle.addMessage(new Message(newMsg.getKey(), newMsg.getLocale()));
- } else { // update old entries
- IMessage oldMsg = oldBundle.getMessage(newMsg.getKey());
- if (oldMsg == null) { // it's a new one
- oldBundle.addMessage(newMsg);
- } else { // check value
- oldMsg.setComment(newMsg.getComment());
- oldMsg.setText(newMsg.getValue());
- }
- }
- }
- }
- }
-
- // check keys
- for (IMessagesBundle oldBundle : oldBundleGroup.getMessagesBundles()) {
- IMessagesBundle newBundle = newBundleGroup.getMessagesBundle(oldBundle.getLocale());
- if (newBundle == null) { // we have an old one
- bundlesToRemove.add(oldBundle);
- } else {
- for (IMessage oldMsg : oldBundle.getMessages()) {
- if (newBundle.getMessage(oldMsg.getKey()) == null) {
- keysToRemove.add(oldMsg);
- }
- }
- }
- }
-
- for (IMessagesBundle bundle : bundlesToRemove) {
- oldBundleGroup.removeMessagesBundle(bundle);
- }
-
- for (IMessage msg : keysToRemove) {
- IMessagesBundle mb = oldBundleGroup.getMessagesBundle(msg.getLocale());
- if (mb != null) {
- mb.removeMessage(msg.getKey());
- }
- }
-
- DirtyHack.setFireEnabled(true);
-
- }
-
- /**
- * Hier darf nur TAPIJI rein
- * @param bundleGroup
- */
- public void deleteMessagesBundle(String name) {
- if (resourceBundles.containsKey(name)) {
- resourceBundles.remove(name);
- } else {
- System.out.println("ohje");
- }
- }
-
- public boolean containsMessagesBundleGroup(String name) {
- return resourceBundles.containsKey(name);
- }
-
- public static RBManager getInstance(IProject project) {
- // set host-project
- if (PDEUtils.isFragment(project))
- project = PDEUtils.getFragmentHost(project);
-
- INSTANCE = managerMap.get(project);
-
- if (INSTANCE == null) {
- INSTANCE = new RBManager();
- INSTANCE.project = project;
- managerMap.put(project, INSTANCE);
- INSTANCE.detectResourceBundles();
- }
-
- return INSTANCE;
- }
-
- public static RBManager getInstance(String projectName) {
- for (IProject project : getAllSupportedProjects()) {
- if (project.getName().equals(projectName)) {
- //check if the projectName is a fragment and return the manager for the host
- if(PDEUtils.isFragment(project)) {
- return getInstance(PDEUtils.getFragmentHost(project));
- } else {
- return getInstance(project);
- }
- }
- }
- return null;
- }
-
- public static Set<IProject> getAllSupportedProjects () {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- Set<IProject> projs = new HashSet<IProject>();
-
- for (IProject p : projects) {
- try {
- if (p.hasNature("org.eclipselabs.tapiji.tools.core.nature")) {
- projs.add(p);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- return projs;
- }
-
- public void addMessagesEditorListener(IMessagesEditorListener listener) {
- this.editorListeners.add(listener);
- }
-
- public void removeMessagesEditorListener(IMessagesEditorListener listener) {
- this.editorListeners.remove(listener);
- }
-
- public void fireEditorSaved() {
- for (IMessagesEditorListener listener : this.editorListeners) {
- listener.onSave();
- }
- }
-
- public void fireEditorChanged() {
- for (IMessagesEditorListener listener : this.editorListeners) {
- listener.onModify();
- }
- }
-
- public void fireResourceChanged(IMessagesBundle bundle) {
- for (IMessagesEditorListener listener : this.editorListeners) {
- listener.onResourceChanged(bundle);
- }
- }
-
- protected void detectResourceBundles () {
- try {
- project.accept(new ResourceBundleDetectionVisitor(this));
-
- IProject[] fragments = PDEUtils.lookupFragment(project);
- if (fragments != null){
- for (IProject p : fragments){
- p.accept(new ResourceBundleDetectionVisitor(this));
- }
- }
- } catch (CoreException e) {
- }
- }
-
- // passive loading -> see detectResourceBundles
- public void addBundleResource(IResource resource) {
- // create it with MessagesBundleFactory or read from resource!
- // we can optimize that, now we create a bundle group for each bundle
- // we should create a bundle group only once!
-
- String resourceBundleId = getResourceBundleId(resource);
- if (!resourceBundles.containsKey(resourceBundleId)) {
- // if we do not have this condition, then you will be doomed with
- // resource out of syncs, because here we instantiate
- // PropertiesFileResources, which have an evil setText-Method
- MessagesBundleGroupFactory.createBundleGroup(resource);
- }
- }
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
- public 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 void writeToFile(IMessagesBundleGroup bundleGroup) {
- for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) {
- writeToFile(bundle);
- }
- }
-
- public void writeToFile(IMessagesBundle bundle) {
- DirtyHack.setEditorModificationEnabled(false);
-
- PropertiesSerializer ps = new PropertiesSerializer(ConfigurationManager.getInstance().getSerializerConfig());
- String editorContent = ps.serialize(bundle);
- IFile file = getFile(bundle);
- try {
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- file.setContents(new ByteArrayInputStream(editorContent.getBytes()),
- false, true, null);
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- DirtyHack.setEditorModificationEnabled(true);
- }
-
- fireResourceChanged(bundle);
-
- }
-
- private IFile getFile(IMessagesBundle bundle) {
- if (bundle.getResource() instanceof PropertiesFileResource) { // different ResourceLocationLabel
- String path = bundle.getResource().getResourceLocationLabel(); // P:\Allianz\Workspace\AST\TEST\src\messages\Messages_de.properties
- int index = path.indexOf("src");
- String pathBeforeSrc = path.substring(0, index - 1);
- int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
- String projectName = path.substring(lastIndexOf + 1, index - 1);
- String relativeFilePath = path.substring(index, path.length());
-
- return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(relativeFilePath);
- } else {
- String location = bundle.getResource().getResourceLocationLabel(); ///TEST/src/messages/Messages_en_IN.properties
- location = location.substring(project.getName().length() + 1, location.length());
- return ResourcesPlugin.getWorkspace().getRoot().getProject(project.getName()).getFile(location);
- }
- }
-
- protected Locale getLocaleByName (String bundleName, String localeID) {
- // Check locale
- Locale locale = null;
- localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
- if (localeID.length() == bundleName.length()) {
- // default locale
- return null;
- } else {
- localeID = localeID.substring(bundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
-
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
- break;
- default:
- locale = null;
- break;
- }
- }
-
- return locale;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/ResourceBundleDetectionVisitor.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/ResourceBundleDetectionVisitor.java
deleted file mode 100644
index b32c30a9..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/manager/ResourceBundleDetectionVisitor.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.manager;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipselabs.tapiji.translator.rap.babel.core.configuration.ConfigurationManager;
-import org.eclipselabs.tapiji.translator.rap.babel.core.configuration.IConfiguration;
-
-
-public class ResourceBundleDetectionVisitor implements IResourceVisitor,
- IResourceDeltaVisitor {
-
- private RBManager manager = null;
-
- public ResourceBundleDetectionVisitor(RBManager manager) {
- this.manager = manager;
- }
-
- public boolean visit(IResource resource) throws CoreException {
- try {
- if (isResourceBundleFile(resource)) {
-
-// Logger.logInfo("Loading Resource-Bundle file '" + resource.getName() + "'");
-
-// if (!ResourceBundleManager.isResourceExcluded(resource)) {
- manager.addBundleResource(resource);
-// }
- return false;
- } else
- return true;
- } catch (Exception e) {
- return false;
- }
- }
-
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
-
- if (isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
-
- return true;
- }
-
- private final String RB_MARKER_ID = "org.eclipselabs.tapiji.tools.core.ResourceBundleAuditMarker";
-
- private boolean isResourceBundleFile(IResource file) {
- boolean isValied = false;
-
- if (file != null && file instanceof IFile && !file.isDerived() &&
- file.getFileExtension()!=null && file.getFileExtension().equalsIgnoreCase("properties")){
- isValied = true;
-
- List<CheckItem> list = getBlacklistItems();
- for (CheckItem item : list){
- if (item.getChecked() && file.getFullPath().toString().matches(item.getName())){
- isValied = false;
-
- //if properties-file is not RB-file and has ResouceBundleMarker, deletes all ResouceBundleMarker of the file
- if (hasResourceBundleMarker(file))
- try {
- file.deleteMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- }
- }
- }
- }
-
- return isValied;
- }
-
- private List<CheckItem> getBlacklistItems() {
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
- return convertStringToList(configuration.getNonRbPattern());
- }
-
- private static final String DELIMITER = ";";
- private static final String ATTRIBUTE_DELIMITER = ":";
-
- private 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;
- }
-
- /**
- * Checks whether a RB-file has a problem-marker
- */
- public boolean hasResourceBundleMarker(IResource r){
- try {
- if(r.findMarkers(RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
- return true;
- else return false;
- } catch (CoreException e) {
- return false;
- }
- }
-
- private class CheckItem{
- boolean checked;
- String name;
-
- public CheckItem(String item, boolean checked) {
- this.name = item;
- this.checked = checked;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean getChecked() {
- return checked;
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/AbstractMessagesResource.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/AbstractMessagesResource.java
deleted file mode 100644
index 31aac715..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/AbstractMessagesResource.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResourceChangeListener;
-
-/**
- * Base implementation of a {@link IMessagesResource} bound to a locale
- * and providing ways to add and remove {@link IMessagesResourceChangeListener}
- * instances.
- * @author Pascal Essiembre
- */
-public abstract class AbstractMessagesResource implements IMessagesResource {
-
- private Locale locale;
- private List<IMessagesResourceChangeListener> listeners = new ArrayList<IMessagesResourceChangeListener>();
-
- /**
- * Constructor.
- * @param locale bound locale
- */
- public AbstractMessagesResource(Locale locale) {
- super();
- this.locale = locale;
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.resource.IMessagesResource#getLocale()
- */
- public Locale getLocale() {
- return locale;
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource#
- * addMessagesResourceChangeListener(
- * org.eclipse.babel.core.message.resource
- * .IMessagesResourceChangeListener)
- */
- public void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener) {
- listeners.add(0, listener);
- }
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource#
- * removeMessagesResourceChangeListener(
- * org.eclipse.babel.core.message
- * .resource.IMessagesResourceChangeListener)
- */
- public void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener) {
- listeners.remove(listener);
- }
-
- /**
- * Fires notification that a {@link IMessagesResource} changed.
- * @param resource {@link IMessagesResource}
- */
- protected void fireResourceChange(IMessagesResource resource) {
- for (IMessagesResourceChangeListener listener : listeners) {
- listener.resourceChanged(resource);
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/AbstractPropertiesResource.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/AbstractPropertiesResource.java
deleted file mode 100644
index bd48c61f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/AbstractPropertiesResource.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource;
-
-import java.util.Locale;
-import java.util.Properties;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-/**
- * Based implementation of a text-based messages resource following
- * the conventions defined by the Java {@link Properties} class for
- * serialization and deserialization.
- * @author Pascal Essiembre
- */
-public abstract class AbstractPropertiesResource
- extends AbstractMessagesResource {
-
- private PropertiesDeserializer deserializer;
- private PropertiesSerializer serializer;
-
- /**
- * Constructor.
- * @param locale properties locale
- * @param serializer properties serializer
- * @param deserializer properties deserializer
- */
- public AbstractPropertiesResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer) {
- super(locale);
- this.deserializer = deserializer;
- this.serializer = serializer;
- //TODO initialises with configurations only...
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource#serialize(
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle)
- */
- public void serialize(IMessagesBundle messagesBundle) {
- setText(serializer.serialize(messagesBundle));
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource
- * #deserialize(org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle)
- */
- public void deserialize(IMessagesBundle messagesBundle) {
- deserializer.deserialize(messagesBundle, getText());
- }
-
- /**
- * Gets the {@link Properties}-like formated text.
- * @return formated text
- */
- protected abstract String getText();
- /**
- * Sets the {@link Properties}-like formated text.
- * @param text formated text
- */
- protected abstract void setText(String text);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesFileResource.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesFileResource.java
deleted file mode 100644
index 902173bd..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesFileResource.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.FileChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.FileMonitor;
-
-
-/**
- * Properties file, where the underlying storage is a regular {@link File}.
- * For files referenced through Eclipse workspace, implementors should
- * use {@link PropertiesIFileResource}.
- *
- * @author Pascal Essiembre
- * @see PropertiesIFileResource
- */
-public class PropertiesFileResource extends AbstractPropertiesResource {
-
- private File file;
-
- private FileChangeListenerImpl fileChangeListener;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param file the underlying file
- * @throws FileNotFoundException
- */
- public PropertiesFileResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- File file) throws FileNotFoundException {
- super(locale, serializer, deserializer);
- this.file = file;
- this.fileChangeListener = new FileChangeListenerImpl();
-
- FileMonitor.getInstance().addFileChangeListener(this.fileChangeListener, file, 2000); //TODO make file scan delay configurable
- }
-
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.AbstractPropertiesResource
- * #getText()
- */
- public String getText() {
- FileReader inputStream = null;
- StringWriter outputStream = null;
- try {
- if (!file.exists()) {
- return "";
- }
- inputStream = new FileReader(file);
- outputStream = new StringWriter();
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException(
- "Cannot get properties file text. Handle better.", e);
- } finally {
- closeReader(inputStream);
- closeWriter(outputStream);
- }
- return outputStream.toString();
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.AbstractPropertiesResource
- * #setText(java.lang.String)
- */
- public void setText(String content) {
- StringReader inputStream = null;
- FileWriter outputStream = null;
- try {
- inputStream = new StringReader(content);
- outputStream = new FileWriter(file);
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException(
- "Cannot get properties file text. Handle better.", e);
- } finally {
- closeReader(inputStream);
- closeWriter(outputStream);
-
-// IFile file =
-// ResourcesPlugin.getWorkspace().getRoot().getFileForLocation( new
-// Path(getResourceLocationLabel()));
-// try {
-// file.refreshLocal(IResource.DEPTH_ZERO, null);
-// } catch (CoreException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource
- * .IMessagesResource#getSource()
- */
- public Object getSource() {
- return file;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- return file.getAbsolutePath();
- }
-
- //TODO move to util class for convinience???
- private void closeWriter(Writer writer) {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException("Cannot close writer stream.", e);
- }
- }
- }
-
- //TODO move to util class for convinience???
- public void closeReader(Reader reader) {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- //TODO handle better.
- throw new RuntimeException("Cannot close reader.", e);
- }
- }
- }
-
- /**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this file.
- */
- public void dispose() {
- FileMonitor.getInstance().removeFileChangeListener(this.fileChangeListener, file);
- }
-
- private class FileChangeListenerImpl implements FileChangeListener {
-
- @Override
- public void fileChanged(final File changedFile) {
- fireResourceChange(PropertiesFileResource.this);
- }
-
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesIFileResource.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesIFileResource.java
deleted file mode 100644
index 131e717b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesIFileResource.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.AbstractIFileChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.AbstractIFileChangeListener.IFileChangeListenerRegistry;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesSerializer;
-
-
-/**
- * Properties file, where the underlying storage is a {@link IFile}.
- * When dealing with {@link File} as opposed to {@link IFile},
- * implementors should use {@link PropertiesFileResource}.
- *
- * @author Pascal Essiembre
- * @see PropertiesFileResource
- */
-public class PropertiesIFileResource extends AbstractPropertiesResource {
-
- private final IFile file;
-
- private final AbstractIFileChangeListener fileListener;
- private final IFileChangeListenerRegistry listenerRegistry;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param file the underlying {@link IFile}
- * @param listenerRegistry It is the MessageEditorPlugin.
- * Or null if we don't care for file changes.
- * We could replace it by an activator in this plugin.
- */
- public PropertiesIFileResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- IFile file, IFileChangeListenerRegistry listenerRegistry) {
- super(locale, serializer, deserializer);
- this.file = file;
- this.listenerRegistry = listenerRegistry;
-
- //[hugues] FIXME: this object is built at the beginning
- //of a build (no message editor)
- //it is disposed of at the end of the build.
- //during a build files are not changed.
- //so it is I believe never called.
- if (this.listenerRegistry != null) {
- IResourceChangeListener rcl =
- new IResourceChangeListener() {
- public void resourceChanged(IResourceChangeEvent event) {
- //no need to check: it is always the case as this
- //is subscribed for a particular file.
-// if (event.getResource() != null
-// && PropertiesIFileResource.this.file.equals(event.getResource())) {
- fireResourceChange(PropertiesIFileResource.this);
-// }
- }
- };
- fileListener = AbstractIFileChangeListener
- .wrapResourceChangeListener(rcl, file);
- this.listenerRegistry.subscribe(fileListener);
- } else {
- fileListener = null;
- }
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.AbstractPropertiesResource
- * #getText()
- */
- public String getText() {
- try {
- file.refreshLocal(IResource.DEPTH_INFINITE, null);
- InputStream is = file.getContents();
- int byteCount = is.available();
- byte[] b = new byte[byteCount];
- is.read(b);
- String content = new String(b, file.getCharset());
- return content;
- } catch (IOException e) {
- throw new RuntimeException(e); //TODO handle better
- } catch (CoreException e) {
- throw new RuntimeException(e); //TODO handle better
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.TextResource#setText(
- * java.lang.String)
- */
- public void setText(String text) {
- try {
- String charset = file.getCharset();
- ByteArrayInputStream is = new ByteArrayInputStream(
- text.getBytes(charset));
- file.setContents(is, IFile.KEEP_HISTORY, null);
- file.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (Exception e) {
- //TODO handle better
- throw new RuntimeException(
- "Cannot set content on properties file.", e); //$NON-NLS-1$
- }
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource
- * #getSource()
- */
- public Object getSource() {
- return file;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- return file.getFullPath().toString();
- }
-
- /**
- * Called before this object will be discarded.
- * If this object was listening to file changes: then unsubscribe it.
- */
- public void dispose() {
- if (this.listenerRegistry != null) {
- this.listenerRegistry.unsubscribe(this.fileListener);
- }
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesReadOnlyResource.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesReadOnlyResource.java
deleted file mode 100644
index c6d053aa..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/PropertiesReadOnlyResource.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource;
-
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesSerializer;
-
-
-/**
- * Properties file, where the underlying storage is unknown and read-only.
- * This is the case when properties are located inside a jar or the target platform.
- * This resource is not suitable to build the editor itself.
- * It is used during the build only.
- *
- * @author Pascal Essiembre
- * @author Hugues Malphettes
- * @see PropertiesFileResource
- */
-public class PropertiesReadOnlyResource extends AbstractPropertiesResource{
-
- private final String contents;
- private final String resourceLocationLabel;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param content The contents of the properties
- * @param resourceLocationLabel The label that explains to the user where
- * those properties are defined.
- */
- public PropertiesReadOnlyResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- String contents,
- String resourceLocationLabel) {
- super(locale, serializer, deserializer);
- this.contents = contents;
- this.resourceLocationLabel = resourceLocationLabel;
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.AbstractPropertiesResource
- * #getText()
- */
- public String getText() {
- return contents;
- }
-
- /**
- * Unsupported here. This is read-only.
- * @see org.eclipse.babel.core.message.resource.TextResource#setText(
- * java.lang.String)
- */
- public void setText(String text) {
- throw new UnsupportedOperationException(getResourceLocationLabel()
- + " resource is read-only"); //$NON-NLS-1$ (just an error message)
- }
-
- /**
- * @see org.eclipse.babel.core.message.resource.IMessagesResource
- * #getSource()
- */
- public Object getSource() {
- return this;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- return resourceLocationLabel;
- }
-
- /**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this object.
- */
- public void dispose() {
- //nothing to do.
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java
deleted file mode 100644
index 312a3d1b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser;
-
-public interface IPropertiesDeserializerConfig {
-
- /**
- * Defaults true.
- * @return Returns the unicodeUnescapeEnabled.
- */
- boolean isUnicodeUnescapeEnabled();
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/IPropertiesSerializerConfig.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/IPropertiesSerializerConfig.java
deleted file mode 100644
index e4fe1983..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/IPropertiesSerializerConfig.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser;
-
-public interface IPropertiesSerializerConfig {
-
- /** New Line Type: Default. */
- public static final int NEW_LINE_DEFAULT = 0;
- /** New Line Type: UNIX. */
- public static final int NEW_LINE_UNIX = 1;
- /** New Line Type: Windows. */
- public static final int NEW_LINE_WIN = 2;
- /** New Line Type: Mac. */
- public static final int NEW_LINE_MAC = 3;
-
- /**
- * Default true.
- * @return Returns the unicodeEscapeEnabled.
- */
- boolean isUnicodeEscapeEnabled();
-
- /**
- * Default to "NEW_LINE_DEFAULT".
- * @return Returns the newLineStyle.
- */
- int getNewLineStyle();
-
- /**
- * Default is 1.
- * @return Returns the groupSepBlankLineCount.
- */
- int getGroupSepBlankLineCount();
-
- /**
- * Defaults to true.
- * @return Returns the showSupportEnabled.
- */
- boolean isShowSupportEnabled();
-
- /**
- * Defaults to true.
- * @return Returns the groupKeysEnabled.
- */
- boolean isGroupKeysEnabled();
-
- /**
- * Defaults to true.
- * @return Returns the unicodeEscapeUppercase.
- */
- boolean isUnicodeEscapeUppercase();
-
- /**
- * Defaults to 80.
- * @return Returns the wrapLineLength.
- */
- int getWrapLineLength();
-
- /**
- * @return Returns the wrapLinesEnabled.
- */
- boolean isWrapLinesEnabled();
-
- /**
- * @return Returns the wrapAlignEqualsEnabled.
- */
- boolean isWrapAlignEqualsEnabled();
-
- /**
- * Defaults to 8.
- * @return Returns the wrapIndentLength.
- */
- int getWrapIndentLength();
-
- /**
- * Defaults to true.
- * @return Returns the spacesAroundEqualsEnabled.
- */
- boolean isSpacesAroundEqualsEnabled();
-
- /**
- * @return Returns the newLineNice.
- */
- boolean isNewLineNice();
-
- /**
- * @return Returns the groupLevelDepth.
- */
- int getGroupLevelDepth();
-
- /**
- * @return Returns the groupLevelSeparator.
- */
- String getGroupLevelSeparator();
-
- /**
- * @return Returns the alignEqualsEnabled.
- */
- boolean isAlignEqualsEnabled();
-
- /**
- * Defaults to true.
- * @return Returns the groupAlignEqualsEnabled.
- */
- boolean isGroupAlignEqualsEnabled();
-
- /**
- * Defaults to true.
- * @return <code>true</code> if keys are to be sorted
- */
- boolean isKeySortingEnabled();
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/PropertiesDeserializer.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/PropertiesDeserializer.java
deleted file mode 100644
index 6cdb7f48..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/PropertiesDeserializer.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Properties;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.Message;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-/**
- * Class responsible for deserializing {@link Properties}-like text into
- * a {@link MessagesBundle}.
- * @author Pascal Essiembre ([email protected])
- */
-public class PropertiesDeserializer {
-
- /** System line separator. */
- private static final String SYSTEM_LINE_SEPARATOR =
- System.getProperty("line.separator"); //$NON-NLS-1$
-
- /** Characters accepted as key value separators. */
- private static final String KEY_VALUE_SEPARATORS = "=:"; //$NON-NLS-1$
-
- /** MessagesBundle deserializer configuration. */
- private IPropertiesDeserializerConfig config;
-
- /**
- * Constructor.
- */
- public PropertiesDeserializer(IPropertiesDeserializerConfig config) {
- super();
- this.config = config;
- }
-
- /**
- * Parses a string and populates a <code>MessagesBundle</code>.
- * The string is expected to match the documented structure of a properties
- * file.
- * @param messagesBundle the target {@link MessagesBundle}
- * @param properties the string containing the properties to parse
- */
- public void deserialize(IMessagesBundle messagesBundle, String properties) {
- Locale locale = messagesBundle.getLocale();
-
- Collection<String> oldKeys =
- new ArrayList<String>(Arrays.asList(messagesBundle.getKeys()));
- Collection<String> newKeys = new ArrayList<String>();
-
- String[] lines = properties.split("\r\n|\r|\n"); //$NON-NLS-1$
-
- boolean doneWithFileComment = false;
- StringBuffer fileComment = new StringBuffer();
- StringBuffer lineComment = new StringBuffer();
- StringBuffer lineBuf = new StringBuffer();
- for (int i = 0; i < lines.length; i++) {
- String line = lines[i];
- lineBuf.setLength(0);
- lineBuf.append(line);
-
- int equalPosition = findKeyValueSeparator(line);
- boolean isRegularLine = line.matches("^[^#].*"); //$NON-NLS-1$
- boolean isCommentedLine = doneWithFileComment
- && line.matches("^##[^#].*"); //$NON-NLS-1$
-
- // parse regular and commented lines
- if (equalPosition >= 1 && (isRegularLine || isCommentedLine)) {
- doneWithFileComment = true;
- String comment = ""; //$NON-NLS-1$
- if (lineComment.length() > 0) {
- comment = lineComment.toString();
- lineComment.setLength(0);
- }
-
- if (isCommentedLine) {
- lineBuf.delete(0, 2); // remove ##
- equalPosition -= 2;
- }
- String backslash = "\\"; //$NON-NLS-1$
- while (lineBuf.lastIndexOf(backslash) == lineBuf.length() -1) {
- int lineBreakPosition = lineBuf.lastIndexOf(backslash);
- lineBuf.replace(
- lineBreakPosition,
- lineBreakPosition + 1, ""); //$NON-NLS-1$
- if (++i < lines.length) {
- String wrappedLine = lines[i].replaceFirst(
- "^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$
- if (isCommentedLine) {
- lineBuf.append(wrappedLine.replaceFirst(
- "^##", "")); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- lineBuf.append(wrappedLine);
- }
- }
- }
- String key = lineBuf.substring(0, equalPosition).trim();
- key = unescapeKey(key);
-
- String value = lineBuf.substring(equalPosition + 1)
- .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$
- // Unescape leading spaces
- if (value.startsWith("\\ ")) { //$NON-NLS-1$
- value = value.substring(1);
- }
-
- if (config.isUnicodeUnescapeEnabled()) {
- key = convertEncodedToUnicode(key);
- value = convertEncodedToUnicode(value);
- } else {
- value = value.replaceAll(
- "\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$
- value = value.replaceAll(
- "\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$
- }
- IMessage entry = messagesBundle.getMessage(key);
- if (entry == null) {
- entry = new Message(key, locale);
- messagesBundle.addMessage(entry);
- }
- entry.setActive(!isCommentedLine);
- entry.setComment(comment);
- entry.setText(value);
- newKeys.add(key);
- // parse comment line
- } else if (lineBuf.indexOf("#") == 0) { //$NON-NLS-1$
- if (!doneWithFileComment) {
- fileComment.append(lineBuf);
- fileComment.append(SYSTEM_LINE_SEPARATOR);
- } else {
- lineComment.append(lineBuf);
- lineComment.append(SYSTEM_LINE_SEPARATOR);
- }
- // handle blank or unsupported line
- } else {
- doneWithFileComment = true;
- }
- }
- oldKeys.removeAll(newKeys);
- messagesBundle.removeMessages(
- oldKeys.toArray(BabelUtils.EMPTY_STRINGS));
- messagesBundle.setComment(fileComment.toString());
- }
-
-
- /**
- * Converts encoded \uxxxx to unicode chars
- * and changes special saved chars to their original forms
- * @param str the string to convert
- * @return converted string
- * @see java.util.Properties
- */
- private String convertEncodedToUnicode(String str) {
- char aChar;
- int len = str.length();
- StringBuffer outBuffer = new StringBuffer(len);
-
- for (int x = 0; x < len;) {
- aChar = str.charAt(x++);
- if (aChar == '\\' && x + 1 <= len) {
- aChar = str.charAt(x++);
- if (aChar == 'u' && x + 4 <= len) {
- // Read the xxxx
- int value = 0;
- for (int i = 0; i < 4; i++) {
- aChar = str.charAt(x++);
- switch (aChar) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- value = (value << 4) + aChar - '0';
- break;
- case 'a': case 'b': case 'c':
- case 'd': case 'e': case 'f':
- value = (value << 4) + 10 + aChar - 'a';
- break;
- case 'A': case 'B': case 'C':
- case 'D': case 'E': case 'F':
- value = (value << 4) + 10 + aChar - 'A';
- break;
- default:
- value = aChar;
- System.err.println(
- "PropertiesDeserializer: " //$NON-NLS-1$
- + "bad character " //$NON-NLS-1$
- + "encoding for string:" //$NON-NLS-1$
- + str);
- }
- }
- outBuffer.append((char) value);
- } else {
- if (aChar == 't') {
- aChar = '\t';
- } else if (aChar == 'r') {
- aChar = '\r';
- } else if (aChar == 'n') {
- aChar = '\n';
- } else if (aChar == 'f') {
- aChar = '\f';
- } else if (aChar == 'u') {
- outBuffer.append("\\"); //$NON-NLS-1$
- }
- outBuffer.append(aChar);
- }
- } else {
- outBuffer.append(aChar);
- }
- }
- return outBuffer.toString();
- }
-
- /**
- * Finds the separator symbol that separates keys and values.
- * @param str the string on which to find seperator
- * @return the separator index or -1 if no separator was found
- */
- private int findKeyValueSeparator(String str) {
- int index = -1;
- int length = str.length();
- for (int i = 0; i < length; i++) {
- char currentChar = str.charAt(i);
- if (currentChar == '\\') {
- i++;
- } else if (KEY_VALUE_SEPARATORS.indexOf(currentChar) != -1) {
- index = i;
- break;
- }
- }
- return index;
- }
-
- private String unescapeKey(String key) {
- int length = key.length();
- StringBuffer buf = new StringBuffer();
- for (int index = 0; index < length; index++) {
- char currentChar = key.charAt(index);
- if (currentChar != '\\') {
- buf.append(currentChar);
- }
- }
- return buf.toString();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/PropertiesSerializer.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/PropertiesSerializer.java
deleted file mode 100644
index 6be6510e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/resource/ser/PropertiesSerializer.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser;
-
-import java.util.Arrays;
-import java.util.Properties;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-/**
- * Class responsible for serializing a {@link MessagesBundle} into
- * {@link Properties}-like text.
- * @author Pascal Essiembre ([email protected])
- */
-public class PropertiesSerializer {
-
- /** Generator header comment. */
- public static final String GENERATED_BY =
- "#Generated by Eclipse Messages Editor " //$NON-NLS-1$
- + "(Eclipse Babel)"; //$NON-NLS-1$
-
- /** A table of hex digits */
- private static final char[] HEX_DIGITS = {
- '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
- };
-
- /** Special resource bundle characters when persisting any text. */
- private static final String SPECIAL_VALUE_SAVE_CHARS =
- "\t\f"; //$NON-NLS-1$
- /** Special resource bundle characters when persisting keys. */
- private static final String SPECIAL_KEY_SAVE_CHARS =
- "=\t\f#!: "; //$NON-NLS-1$
-
- /** System line separator. */
- private static final String SYSTEM_LINE_SEP =
- System.getProperty("line.separator"); //$NON-NLS-1$
- /** Forced line separators. */
- private static final String[] FORCED_LINE_SEP = new String[4];
- static {
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_DEFAULT] = null;
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_UNIX] =
- "\\\\n"; //$NON-NLS-1$
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_WIN] =
- "\\\\r\\\\n"; //$NON-NLS-1$
- FORCED_LINE_SEP[IPropertiesSerializerConfig.NEW_LINE_MAC] =
- "\\\\r"; //$NON-NLS-1$
- }
-
- private IPropertiesSerializerConfig config;
-
- /**
- * Constructor.
- */
- public PropertiesSerializer(IPropertiesSerializerConfig config) {
- super();
- this.config = config;
- }
-
- /**
- * Serializes a given <code>MessagesBundle</code> into a formatted string.
- * The returned string will conform to documented properties file structure.
- * @param messagesBundle the bundle used to generate the string
- * @return the generated string
- */
- public String serialize(IMessagesBundle messagesBundle) {
- String lineBreak = SYSTEM_LINE_SEP;
- int numOfLineBreaks = config.getGroupSepBlankLineCount();
- StringBuffer text = new StringBuffer();
-
- // Header comment
- String headComment = messagesBundle.getComment();
- if (config.isShowSupportEnabled()
- && !headComment.startsWith(GENERATED_BY)) {
- text.append(GENERATED_BY);
- text.append(SYSTEM_LINE_SEP);
- }
- if (headComment != null && headComment.length() > 0) {
- text.append(headComment);
- }
-
- // Format
- String group = null;
- int equalIndex = -1;
- String[] keys = messagesBundle.getKeys();
- if (config.isKeySortingEnabled()) {
- Arrays.sort(keys);
- }
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
- IMessage message = messagesBundle.getMessage(key);
- String value = message.getValue();
- String comment = message.getComment();
-
- if (value != null){
- // escape backslashes
- if (config.isUnicodeEscapeEnabled()) {
- value = value.replaceAll(
- "\\\\", "\\\\\\\\");//$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // handle new lines in value
- String lineStyleCh = FORCED_LINE_SEP[config.getNewLineStyle()];
- if (lineStyleCh != null) {
- value = value.replaceAll(
- "\r\n|\r|\n", lineStyleCh); //$NON-NLS-1$
- } else {
- value = value.replaceAll(
- "\r", "\\\\r"); //$NON-NLS-1$ //$NON-NLS-2$
- value = value.replaceAll(
- "\n", "\\\\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- value = ""; //$NON-NLS-1$
- }
-
- //TODO Put check here and add to config: keep empty values?
- //default being false
-
- // handle group equal align and line break options
- if (config.isGroupKeysEnabled()) {
- String newGroup = getKeyGroup(key);
- if (newGroup == null || !newGroup.equals(group)) {
- group = newGroup;
- equalIndex = getEqualIndex(key, group, messagesBundle);
- for (int j = 0; j < numOfLineBreaks; j++) {
- text.append(lineBreak);
- }
- }
- } else {
- equalIndex = getEqualIndex(key, null, messagesBundle);
- }
-
- // Build line
- if (config.isUnicodeEscapeEnabled()) {
- key = convertUnicodeToEncoded(key);
- value = convertUnicodeToEncoded(value);
- }
- if (comment != null && comment.length() > 0) {
- text.append(comment);
- }
- appendKey(text, key, equalIndex, message.isActive());
- appendValue(text, value, equalIndex, message.isActive());
- text.append(lineBreak);
- }
- return text.toString();
- }
-
- /**
- * Converts unicodes to encoded \uxxxx.
- * @param str string to convert
- * @return converted string
- * @see java.util.Properties
- */
- private String convertUnicodeToEncoded(String str) {
- int len = str.length();
- StringBuffer outBuffer = new StringBuffer(len * 2);
-
- for (int x = 0; x < len; x++) {
- char aChar = str.charAt(x);
- if ((aChar < 0x0020) || (aChar > 0x007e)) {
- outBuffer.append('\\');
- outBuffer.append('u');
- outBuffer.append(toHex((aChar >> 12) & 0xF));
- outBuffer.append(toHex((aChar >> 8) & 0xF));
- outBuffer.append(toHex((aChar >> 4) & 0xF));
- outBuffer.append(toHex(aChar & 0xF));
- } else {
- outBuffer.append(aChar);
- }
- }
- return outBuffer.toString();
- }
-
- /**
- * Converts a nibble to a hex character
- * @param nibble the nibble to convert.
- * @return a converted character
- */
- private char toHex(int nibble) {
- char hexChar = HEX_DIGITS[(nibble & 0xF)];
- if (!config.isUnicodeEscapeUppercase()) {
- return Character.toLowerCase(hexChar);
- }
- return hexChar;
- }
-
- /**
- * Appends a value to resource bundle content.
- * @param text the resource bundle content so far
- * @param value the value to add
- * @param equalIndex the equal sign position
- * @param active is the value active or not
- */
- private void appendValue(
- StringBuffer text, String value,
- int equalIndex, boolean active) {
- if (value != null) {
- // Escape potential leading spaces.
- if (value.startsWith(" ")) { //$NON-NLS-1$
- value = "\\" + value; //$NON-NLS-1$
- }
- int lineLength = config.getWrapLineLength() - 1;
- int valueStartPos = equalIndex;
- if (config.isSpacesAroundEqualsEnabled()) {
- valueStartPos += 3;
- } else {
- valueStartPos += 1;
- }
-
- // Break line after escaped new line
- if (config.isNewLineNice()) {
- value = value.replaceAll(
- "(\\\\r\\\\n|\\\\r|\\\\n)", //$NON-NLS-1$
- "$1\\\\" + SYSTEM_LINE_SEP); //$NON-NLS-1$
- }
- // Wrap lines
- if (config.isWrapLinesEnabled() && valueStartPos < lineLength) {
- StringBuffer valueBuf = new StringBuffer(value);
- while (valueBuf.length() + valueStartPos > lineLength
- || valueBuf.indexOf("\n") != -1) { //$NON-NLS-1$
- int endPos = Math.min(
- valueBuf.length(), lineLength - valueStartPos);
- String line = valueBuf.substring(0, endPos);
- int breakPos = line.indexOf(SYSTEM_LINE_SEP);
- if (breakPos != -1) {
- endPos = breakPos + SYSTEM_LINE_SEP.length();
- saveValue(text, valueBuf.substring(0, endPos));
- //text.append(valueBuf.substring(0, endPos));
- } else {
- breakPos = line.lastIndexOf(' ');
- if (breakPos != -1) {
- endPos = breakPos + 1;
- saveValue(text, valueBuf.substring(0, endPos));
- //text.append(valueBuf.substring(0, endPos));
- text.append("\\"); //$NON-NLS-1$
- text.append(SYSTEM_LINE_SEP);
- }
- }
- valueBuf.delete(0, endPos);
- // Figure out starting position for next line
- if (!config.isWrapAlignEqualsEnabled()) {
- valueStartPos = config.getWrapIndentLength();
- }
-
- if (!active && valueStartPos > 0) {
- text.append("##"); //$NON-NLS-1$
- }
-
- for (int i = 0; i < valueStartPos; i++) {
- text.append(' ');
- }
- }
- text.append(valueBuf);
- } else {
- saveValue(text, value);
- //text.append(value);
- }
- }
- }
-
- /**
- * Appends a key to resource bundle content.
- * @param text the resource bundle content so far
- * @param key the key to add
- * @param equalIndex the equal sign position
- * @param active is the key active or not
- */
- private void appendKey(
- StringBuffer text, String key, int equalIndex, boolean active) {
-
- if (!active) {
- text.append("##"); //$NON-NLS-1$
- }
-
- // Escape and persist the rest
- saveKey(text, key);
-// text.append(key);
- for (int i = 0; i < equalIndex - key.length(); i++) {
- text.append(' ');
- }
- if (config.isSpacesAroundEqualsEnabled()) {
- text.append(" = "); //$NON-NLS-1$
- } else {
- text.append("="); //$NON-NLS-1$
- }
- }
-
-
- private void saveKey(StringBuffer buf, String str) {
- saveText(buf, str, SPECIAL_KEY_SAVE_CHARS);
- }
- private void saveValue(StringBuffer buf, String str) {
- saveText(buf, str, SPECIAL_VALUE_SAVE_CHARS);
- }
-
- /**
- * Saves some text in a given buffer after converting special characters.
- * @param buf the buffer to store the text into
- * @param str the value to save
- * @param escapeChars characters to escape
- */
- private void saveText(
- StringBuffer buf, String str, String escapeChars) {
- int len = str.length();
- for(int x = 0; x < len; x++) {
- char aChar = str.charAt(x);
- if (escapeChars.indexOf(aChar) != -1) {
- buf.append('\\');
- }
- buf.append(aChar);
- }
- }
-
- /**
- * Gets the group from a resource bundle key.
- * @param key the key to get a group from
- * @return key group
- */
- private String getKeyGroup(String key) {
- String sep = config.getGroupLevelSeparator();
- int depth = config.getGroupLevelDepth();
- int endIndex = 0;
- int levelFound = 0;
-
- for (int i = 0; i < depth; i++) {
- int sepIndex = key.indexOf(sep, endIndex);
- if (sepIndex != -1) {
- endIndex = sepIndex + 1;
- levelFound++;
- }
- }
- if (levelFound != 0) {
- if (levelFound < depth) {
- return key;
- }
- return key.substring(0, endIndex - 1);
- }
- return null;
- }
-
- /**
- * Gets the position where the equal sign should be located for
- * the given group.
- * @param key resource bundle key
- * @param group resource bundle key group
- * @param messagesBundle resource bundle
- * @return position
- */
- private int getEqualIndex(
- String key, String group, IMessagesBundle messagesBundle) {
- int equalIndex = -1;
- boolean alignEquals = config.isAlignEqualsEnabled();
- boolean groupKeys = config.isGroupKeysEnabled();
- boolean groupAlignEquals = config.isGroupAlignEqualsEnabled();
-
- // Exit now if we are not aligning equals
- if (!alignEquals || groupKeys && !groupAlignEquals
- || groupKeys && group == null) {
- return key.length();
- }
-
- // Get equal index
- String[] keys = messagesBundle.getKeys();
- for (int i = 0; i < keys.length; i++) {
- String iterKey = keys[i];
- if (!groupKeys || groupAlignEquals && iterKey.startsWith(group)) {
- int index = iterKey.length();
- if (index > equalIndex) {
- equalIndex = index;
- }
- }
- }
- return equalIndex;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/strategy/IMessagesBundleGroupStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
deleted file mode 100644
index 7b20f66f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/strategy/IMessagesBundleGroupStrategy.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.strategy;
-
-import java.util.Locale;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessageException;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-
-
-/**
- * This class holds the algorithms required to abstract the internal nature
- * of a <code>MessagesBundleGroup</code>.
- * @author Pascal Essiembre ([email protected])
- * @see IMessagesResource
- */
-public interface IMessagesBundleGroupStrategy {
- //TODO think of a better name for this interface?
-
- /**
- * Creates a name that attempts to uniquely identifies a messages bundle
- * group. It is not a strict requirement that the name be unique,
- * but doing facilitates users interaction with a message bundle group
- * in a given user-facing implementation.<P>
- * This method is called at construction time of a
- * <code>MessagesBundleGroup</code>.
- * @return messages bundle group name
- */
- String createMessagesBundleGroupName();
-
- String createMessagesBundleId();
-
- /**
- * Load all bundles making up a messages bundle group from the underlying
- * source.
- * This method is called at construction time of a
- * <code>MessagesBundleGroup</code>.
- * @return all bundles making a bundle group
- * @throws MessageException problem loading bundles
- */
- MessagesBundle[] loadMessagesBundles() throws MessageException;
-
- /**
- * Creates a new bundle for the given <code>Locale</code>. If the
- * <code>Locale</code> is <code>null</code>, the default system
- * <code>Locale</code> is assumed.
- * @param locale locale for which to create the messages bundle
- * @return a new messages bundle
- * @throws MessageException problem creating a new messages bundle
- */
- MessagesBundle createMessagesBundle(Locale locale) throws MessageException;
-
- String getProjectName();
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/strategy/PropertiesFileGroupStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/strategy/PropertiesFileGroupStrategy.java
deleted file mode 100644
index 61619e16..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/strategy/PropertiesFileGroupStrategy.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.strategy;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessageException;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundle;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.PropertiesFileResource;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.IPropertiesSerializerConfig;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-
-
-/**
- * MessagesBundleGroup strategy for standard Java properties file structure.
- * That is, all *.properties files of the same base name within the same
- * directory. This implementation works on files outside the Eclipse
- * workspace.
- * @author Pascal Essiembre
- */
-public class PropertiesFileGroupStrategy implements IMessagesBundleGroupStrategy {
-
- /** Empty bundle array. */
- private static final MessagesBundle[] EMPTY_MESSAGES =
- new MessagesBundle[] {};
-
- /** File being open, triggering the creation of a bundle group. */
- private File file;
- /** MessagesBundle group base name. */
- private final String baseName;
- /** File extension. */
- private final String fileExtension;
- /** Pattern used to match files in this strategy. */
- private final String fileMatchPattern;
- /** Properties file serializer configuration. */
- private final IPropertiesSerializerConfig serializerConfig;
- /** Properties file deserializer configuration. */
- private final IPropertiesDeserializerConfig deserializerConfig;
-
-
- /**
- * Constructor.
- * @param file file from which to derive the group
- */
- public PropertiesFileGroupStrategy(
- File file,
- IPropertiesSerializerConfig serializerConfig,
- IPropertiesDeserializerConfig deserializerConfig) {
- super();
- this.serializerConfig = serializerConfig;
- this.deserializerConfig = deserializerConfig;
- this.file = file;
- this.fileExtension = file.getName().replaceFirst(
- "(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$
-
- String patternCore =
- "((_[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$
- + fileExtension + ")$"; //$NON-NLS-1$
-
- // Compute and cache name
- String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
- this.baseName = file.getName().replaceFirst(
- namePattern, "$1"); //$NON-NLS-1$
-
- // File matching pattern
- this.fileMatchPattern =
- "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy
- * #getMessagesBundleGroupName()
- */
- public String createMessagesBundleGroupName() {
- return baseName + "[...]." + fileExtension; //$NON-NLS-1$
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy
- * #loadMessagesBundles()
- */
- public MessagesBundle[] loadMessagesBundles() throws MessageException {
- File[] resources = null;
- File parentDir = file.getParentFile();
- if (parentDir != null) {
- resources = parentDir.listFiles();
- }
- Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
- if (resources != null) {
- for (int i = 0; i < resources.length; i++) {
- File resource = resources[i];
- String resourceName = resource.getName();
- if (resource.isFile()
- && resourceName.matches(fileMatchPattern)) {
- // Build local title
- String localeText = resourceName.replaceFirst(
- fileMatchPattern, "$2"); //$NON-NLS-1$
- Locale locale = BabelUtils.parseLocale(localeText);
- bundles.add(createBundle(locale, resource));
- }
- }
- }
- return bundles.toArray(EMPTY_MESSAGES);
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy
- * #createBundle(java.util.Locale)
- */
- public MessagesBundle createMessagesBundle(Locale locale) {
- // TODO Implement me (code exists in SourceForge version)
- return null;
- }
-
- /**
- * Creates a resource bundle for an existing resource.
- * @param locale locale for which to create a bundle
- * @param resource resource used to create bundle
- * @return an initialized bundle
- */
- protected MessagesBundle createBundle(Locale locale, File resource)
- throws MessageException {
- try {
- //TODO have the text de/serializer tied to Eclipse preferences,
- //singleton per project, and listening for changes
- return new MessagesBundle(new PropertiesFileResource(
- locale,
- new PropertiesSerializer(serializerConfig),
- new PropertiesDeserializer(deserializerConfig),
- resource));
- } catch (FileNotFoundException e) {
- throw new MessageException(
- "Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
- }
- }
-
- public String createMessagesBundleId() {
- String path = file.getAbsolutePath();
- int index = path.indexOf("src");
- String pathBeforeSrc = path.substring(0, index - 1);
- int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
- String projectName = path.substring(lastIndexOf + 1, index - 1);
- String relativeFilePath = path.substring(index, path.length());
-
- IFile f = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(relativeFilePath);
-
- return getResourceBundleId(f);
- }
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
- public 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 String getProjectName() {
- IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation();
- IPath fullPath = null;
- if (this.file.getAbsolutePath().contains(path.toOSString())) {
- fullPath = new Path(this.file.getAbsolutePath());
- } else {
- fullPath = new Path(path.toOSString() + this.file.getAbsolutePath());
- }
-
- IFile file = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .getFileForLocation(fullPath);
-
- return ResourcesPlugin.getWorkspace().getRoot().getProject(file.getFullPath().segments()[0]).getName();
- }
-
-// public static String getResourceBundleId (IResource resource) {
-// String packageFragment = "";
-//
-// IJavaElement propertyFile = JavaCore.create(resource.getParent());
-// if (propertyFile != null && propertyFile instanceof IPackageFragment)
-// packageFragment = ((IPackageFragment) propertyFile).getElementName();
-//
-// return (packageFragment.length() > 0 ? packageFragment + "." : "") +
-// getResourceBundleName(resource);
-// }
-//
-// public 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$
-// }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/AbstractKeyTreeModel.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/AbstractKeyTreeModel.java
deleted file mode 100644
index 55b61cba..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/AbstractKeyTreeModel.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.tree;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroupAdapter;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-
-
-/**
- * Hierarchical representation of all keys making up a
- * {@link MessagesBundleGroup}.
- *
- * Key tree model, using a delimiter to separate key sections
- * into nodes. For instance, a dot (.) delimiter on the following key...<p>
- * <code>person.address.street</code><P>
- * ... will result in the following node hierarchy:<p>
- * <pre>
- * person
- * address
- * street
- * </pre>
- *
- * @author Pascal Essiembre
- */
-public class AbstractKeyTreeModel implements IAbstractKeyTreeModel {
-
- private List<IKeyTreeModelListener> listeners = new ArrayList<IKeyTreeModelListener>();
- private Comparator<IKeyTreeNode> comparator;
-
- private KeyTreeNode rootNode = new KeyTreeNode(null, null, null, null);
-
- private String delimiter;
- private MessagesBundleGroup messagesBundleGroup;
-
- protected static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[]{};
-
- /**
- * Defaults to ".".
- */
- public AbstractKeyTreeModel(MessagesBundleGroup messagesBundleGroup) {
- this(messagesBundleGroup, "."); //$NON-NLS-1$
- }
-
- /**
- * Constructor.
- * @param messagesBundleGroup {@link MessagesBundleGroup} instance
- * @param delimiter key section delimiter
- */
- public AbstractKeyTreeModel(
- MessagesBundleGroup messagesBundleGroup, String delimiter) {
- super();
- this.messagesBundleGroup = messagesBundleGroup;
- this.delimiter = delimiter;
- createTree();
-
- messagesBundleGroup.addMessagesBundleGroupListener(
- new MessagesBundleGroupAdapter() {
- public void keyAdded(String key) {
- createTreeNodes(key);
- }
- public void keyRemoved(String key) {
- removeTreeNodes(key);
- }
- });
- }
-
- /**
- * Adds a key tree model listener.
- * @param listener key tree model listener
- */
- public void addKeyTreeModelListener(IKeyTreeModelListener listener) {
- listeners.add(0, listener);
- }
-
- /**
- * Removes a key tree model listener.
- * @param listener key tree model listener
- */
- public void removeKeyTreeModelListener(IKeyTreeModelListener listener) {
- listeners.remove(listener);
- }
-
- /**
- * Notify all listeners that a node was added.
- * @param node added node
- */
- protected void fireNodeAdded(KeyTreeNode node) {
- for (IKeyTreeModelListener listener : listeners) {
- listener.nodeAdded(node);
- }
- }
- /**
- * Notify all listeners that a node was removed.
- * @param node removed node
- */
- protected void fireNodeRemoved(KeyTreeNode node) {
- for (IKeyTreeModelListener listener : listeners) {
- listener.nodeRemoved(node);
- }
- }
-
- /**
- * Gets all nodes on a branch, starting (and including) with parent node.
- * This has the same effect of calling <code>getChildren(KeyTreeNode)</code>
- * recursively on all children.
- * @param parentNode root of a branch
- * @return all nodes on a branch
- */
- // TODO inline and remove this method.
- public KeyTreeNode[] getBranch(KeyTreeNode parentNode) {
- return parentNode.getBranch().toArray(new KeyTreeNode[]{});
- }
-
- /**
- * Accepts the visitor, visiting the given node argument, along with all
- * its children. Passing a <code>null</code> node will
- * walk the entire tree.
- * @param visitor the object to visit
- * @param node the starting key tree node
- */
- public void accept(IKeyTreeVisitor visitor, IKeyTreeNode node) {
- if (node == null) {
- return;
- }
-
- if (node != null) {
- visitor.visitKeyTreeNode(node);
- }
- IKeyTreeNode[] nodes = getChildren(node);
- for (int i = 0; i < nodes.length; i++) {
- accept(visitor, nodes[i]);
- }
- }
-
- /**
- * Gets the child nodes of a given key tree node.
- * @param node the node from which to get children
- * @return child nodes
- */
- public IKeyTreeNode[] getChildren(IKeyTreeNode node) {
- if (node == null) {
- return null;
- }
-
- IKeyTreeNode[] nodes = node.getChildren();
- if (getComparator() != null) {
- Arrays.sort(nodes, getComparator());
- }
- return nodes;
- }
-
- /**
- * Gets the comparator.
- * @return the comparator
- */
- public Comparator<IKeyTreeNode> getComparator() {
- return comparator;
- }
-
- /**
- * Sets the node comparator for sorting sibling nodes.
- * @param comparator node comparator
- */
- public void setComparator(Comparator<IKeyTreeNode> comparator) {
- this.comparator = comparator;
- }
-
- /**
- * Depth first for the first leaf node that is not filtered.
- * It makes the entire branch not not filtered
- *
- * @param filter The leaf filter.
- * @param node
- * @return true if this node or one of its descendant is in the filter (ie is displayed)
- */
- public boolean isBranchFiltered(IKeyTreeNodeLeafFilter filter, IKeyTreeNode node) {
- if (!((KeyTreeNode)node).hasChildren()) {
- return filter.isFilteredLeaf(node);
- } else {
- //depth first:
- for (IKeyTreeNode childNode : ((KeyTreeNode)node).getChildrenInternal()) {
- if (isBranchFiltered(filter, childNode)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Gets the delimiter.
- * @return delimiter
- */
- public String getDelimiter() {
- return delimiter;
- }
- /**
- * Sets the delimiter.
- * @param delimiter delimiter
- */
- public void setDelimiter(String delimiter) {
- this.delimiter = delimiter;
- }
-
- /**
- * Gets the key tree root nodes.
- * @return key tree root nodes
- */
- public IKeyTreeNode[] getRootNodes() {
- return getChildren(rootNode);
- }
-
- public IKeyTreeNode getRootNode() {
- return rootNode;
- }
-
- /**
- * Gets the parent node of the given node.
- * @param node node from which to get parent
- * @return parent node
- */
- public IKeyTreeNode getParent(IKeyTreeNode node) {
- return node.getParent();
- }
-
- /**
- * Gets the messages bundle group that this key tree represents.
- * @return messages bundle group
- */
- public MessagesBundleGroup getMessagesBundleGroup() {
- //TODO consider moving this method (and part of constructor) to super
- return messagesBundleGroup;
- }
-
- private void createTree() {
- rootNode = new KeyTreeNode(null, null, null, messagesBundleGroup);
- String[] keys = messagesBundleGroup.getMessageKeys();
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
- createTreeNodes(key);
- }
- }
-
- private void createTreeNodes(String bundleKey) {
- StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
- KeyTreeNode node = rootNode;
- String bundleKeyPart = ""; //$NON-NLS-1$
- while (tokens.hasMoreTokens()) {
- String name = tokens.nextToken();
- bundleKeyPart += name;
- KeyTreeNode child = (KeyTreeNode) node.getChild(name);
- if (child == null) {
- child = new KeyTreeNode(node, name, bundleKeyPart, messagesBundleGroup);
- fireNodeAdded(child);
- }
- bundleKeyPart += delimiter;
- node = child;
- }
- node.setUsedAsKey();
- }
- private void removeTreeNodes(String bundleKey) {
- if (bundleKey == null) {
- return;
- }
- StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter);
- KeyTreeNode node = rootNode;
- while (tokens.hasMoreTokens()) {
- String name = tokens.nextToken();
- node = (KeyTreeNode) node.getChild(name);
- if (node == null) {
- System.err.println(
- "No RegEx node matching bundleKey to remove"); //$NON-NLS-1$
- return;
- }
- }
- KeyTreeNode parentNode = (KeyTreeNode) node.getParent();
- parentNode.removeChild(node);
- fireNodeRemoved(node);
- while (parentNode != rootNode) {
- if (!parentNode.hasChildren() && !messagesBundleGroup.isMessageKey(
- parentNode.getMessageKey())) {
- ((KeyTreeNode)parentNode.getParent()).removeChild(parentNode);
- fireNodeRemoved(parentNode);
- }
- parentNode = (KeyTreeNode)parentNode.getParent();
- }
- }
-
-
- public interface IKeyTreeNodeLeafFilter {
- /**
- * @param leafNode A leaf node. Must not be called if the node has children
- * @return true if this node should be filtered.
- */
- boolean isFilteredLeaf(IKeyTreeNode leafNode);
- }
-
- public IKeyTreeNode getChild(String key) {
- return returnNodeWithKey(key, rootNode);
- }
-
- private IKeyTreeNode returnNodeWithKey(String key, IKeyTreeNode node) {
-
- if (!key.equals(node.getMessageKey())) {
- for (IKeyTreeNode n : node.getChildren()) {
- IKeyTreeNode returnNode = returnNodeWithKey(key, n);
- if (returnNode == null) {
- continue;
- } else {
- return returnNode;
- }
- }
- } else {
- return node;
- }
- return null;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/IKeyTreeModelListener.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/IKeyTreeModelListener.java
deleted file mode 100644
index 1448413f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/IKeyTreeModelListener.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.tree;
-
-/**
- * Listener notified of changes to a {@link IKeyTreeModel}.
- * @author Pascal Essiembre
- */
-public interface IKeyTreeModelListener {
-
- /**
- * Invoked when a key tree node is added.
- * @param node key tree node
- */
- void nodeAdded(KeyTreeNode node);
- /**
- * Invoked when a key tree node is remove.
- * @param node key tree node
- */
- void nodeRemoved(KeyTreeNode node);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/KeyTreeNode.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/KeyTreeNode.java
deleted file mode 100644
index 72aca88e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/KeyTreeNode.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.tree;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.util.BabelUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Class representing a node in the tree of keys.
- *
- * @author Pascal Essiembre
- */
-public class KeyTreeNode implements Comparable<KeyTreeNode>, IKeyTreeNode {
-
- public static final KeyTreeNode[] EMPTY_KEY_TREE_NODES =
- new KeyTreeNode[] {};
-
- /**
- * the parent node, if any, which will have a <code>messageKey</code> field
- * the same as this object but with the last component (following the
- * last period) removed
- */
- private IKeyTreeNode parent;
-
- /**
- * the name, being the part of the full key that follows the last period
- */
- private final String name;
-
- /**
- * the full key, being a sequence of names separated by periods with the
- * last name being the name given by the <code>name</code> field of this
- * object
- */
- private String messageKey;
-
- private final Map<String, IKeyTreeNode> children = new TreeMap<String, IKeyTreeNode>();
-
- private boolean usedAsKey = false;
-
- private IMessagesBundleGroup messagesBundleGroup;
-
- /**
- * Constructor.
- * @param parent parent node
- * @param name node name
- * @param messageKey messages bundle key
- */
- public KeyTreeNode(
- IKeyTreeNode parent, String name, String messageKey, IMessagesBundleGroup messagesBundleGroup) {
- super();
- this.parent = parent;
- this.name = name;
- this.messageKey = messageKey;
- if (parent != null) {
- parent.addChild(this);
- }
- this.messagesBundleGroup = messagesBundleGroup;
- }
-
- /**
- * @return the name, being the part of the full key that follows the last period
- */
- public String getName() {
- return name;
- }
-
- /**
- * @return the parent node, if any, which will have a <code>messageKey</code> field
- * the same as this object but with the last component (following the
- * last period) removed
- */
- public IKeyTreeNode getParent() {
- return parent;
- }
-
- /**
- * @return the full key, being a sequence of names separated by periods with the
- * last name being the name given by the <code>name</code> field of this
- * object
- */
- public String getMessageKey() {
- return messageKey;
- }
-
- /**
- * Gets all notes from root to this node.
- * @return all notes from root to this node
- */
- /*default*/ IKeyTreeNode[] getPath() {
- List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>();
- IKeyTreeNode node = this;
- while (node != null && node.getName() != null) {
- nodes.add(0, node);
- node = node.getParent();
- }
- return nodes.toArray(EMPTY_KEY_TREE_NODES);
- }
-
- public IKeyTreeNode[] getChildren() {
- return children.values().toArray(EMPTY_KEY_TREE_NODES);
- }
- /*default*/ boolean hasChildren() {
- return !children.isEmpty();
- }
- public IKeyTreeNode getChild(String childName) {
- return children.get(childName);
- }
-
- /**
- * @return the children without creating a new object
- */
- Collection<IKeyTreeNode> getChildrenInternal() {
- return children.values();
- }
-
- /**
- * @see java.lang.Comparable#compareTo(java.lang.Object)
- */
- public int compareTo(KeyTreeNode node) {
- // TODO this is wrong. For example, menu.label and textbox.label are indicated as equal,
- // which means they overwrite each other in the tree set!!!
- if (parent == null && node.parent != null) {
- return -1;
- }
- if (parent != null && node.parent == null) {
- return 1;
- }
- return name.compareTo(node.name);
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof KeyTreeNode)) {
- return false;
- }
- KeyTreeNode node = (KeyTreeNode) obj;
- return BabelUtils.equals(name, node.name)
- && BabelUtils.equals(parent, node.parent);
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return messageKey;
-// return "KeyTreeNode=[[parent=" + parent //$NON-NLS-1$
-// + "][name=" + name //$NON-NLS-1$
-// + "][messageKey=" + messageKey + "]]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void addChild(IKeyTreeNode childNode) {
- children.put(childNode.getName(), childNode);
- }
- public void removeChild(KeyTreeNode childNode) {
- children.remove(childNode.getName());
- //TODO remove parent on child node?
- }
-
- // TODO: remove this, or simplify it using method getDescendants
- public Collection<KeyTreeNode> getBranch() {
- Collection<KeyTreeNode> childNodes = new ArrayList<KeyTreeNode>();
- childNodes.add(this);
- for (IKeyTreeNode childNode : this.getChildren()) {
- childNodes.addAll(((KeyTreeNode)childNode).getBranch());
- }
- return childNodes;
- }
-
- public Collection<IKeyTreeNode> getDescendants() {
- Collection<IKeyTreeNode> descendants = new ArrayList<IKeyTreeNode>();
- for (IKeyTreeNode child : children.values()) {
- descendants.add(child);
- descendants.addAll(((KeyTreeNode)child).getDescendants());
- }
- return descendants;
- }
-
- /**
- * Marks this node as representing an actual key.
- * <P>
- * For example, if the bundle contains two keys:
- * <UL>
- * <LI>foo.bar</LI>
- * <LI>foo.bar.tooltip</LI>
- * </UL>
- * This will create three nodes, foo, which has a child
- * node called bar, which has a child node called tooltip.
- * However foo is not an actual key but is only a parent node.
- * foo.bar is an actual key even though it is also a parent node.
- */
- public void setUsedAsKey() {
- usedAsKey = true;
- }
-
- public boolean isUsedAsKey() {
- return usedAsKey;
- }
-
- public IMessagesBundleGroup getMessagesBundleGroup() {
- return this.messagesBundleGroup;
- }
-
- public void setParent(IKeyTreeNode parentNode) {
- this.parent = parentNode;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/IKeyCheck.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/IKeyCheck.java
deleted file mode 100644
index aa3c9cd2..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/IKeyCheck.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.tree.visitor;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup;
-
-/**
- * All purpose key testing. Use this interface to establish whether
- * a message key within a {@link MessagesBundleGroup} is answering
- * successfully to any condition.
- * @author Pascal Essiembre
- */
-public interface IKeyCheck {
-
- /**
- * Checks whether a key meets the implemented condition.
- * @param messagesBundleGroup messages bundle group
- * @param key message key to test
- * @return <code>true</code> if condition is successfully tested
- */
- boolean checkKey(MessagesBundleGroup messagesBundleGroup, String key);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/KeyCheckVisitor.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/KeyCheckVisitor.java
deleted file mode 100644
index 274d8e87..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/KeyCheckVisitor.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.tree.visitor;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.MessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rap.babel.core.message.tree.KeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-
-
-/**
- * Visitor for going to a tree (or tree branch), and aggregating information
- * about executed checks.
- * @author Pascal Essiembre ([email protected])
- */
-public class KeyCheckVisitor implements IKeyTreeVisitor {
-
- private static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[] {};
-
- private IKeyCheck keyCheck;
- private final MessagesBundleGroup messagesBundleGroup;
-
- private final Collection<IKeyTreeNode> passedNodes = new ArrayList<IKeyTreeNode>();
- private final Collection<IKeyTreeNode> failedNodes = new ArrayList<IKeyTreeNode>();
-
- /**
- * Constructor.
- */
- public KeyCheckVisitor(
- MessagesBundleGroup messagesBundleGroup, IKeyCheck keyCheck) {
- super();
- this.keyCheck = keyCheck;
- this.messagesBundleGroup = messagesBundleGroup;
- }
- /**
- * Constructor.
- */
- public KeyCheckVisitor(MessagesBundleGroup messagesBundleGroup) {
- super();
- this.messagesBundleGroup = messagesBundleGroup;
- }
-
- /**
- * @see org.eclipse.babel.core.message.tree.visitor.IKeyTreeVisitor
- * #visitKeyTreeNode(
- * org.eclipselabs.tapiji.translator.rap.babel.core.message.tree.KeyTreeNode)
- */
- public void visitKeyTreeNode(IKeyTreeNode node) {
- if (keyCheck == null) {
- return;
- }
- if (keyCheck.checkKey(messagesBundleGroup, node.getMessageKey())) {
- passedNodes.add(node);
- } else {
- failedNodes.add(node);
- }
- }
-
- /**
- * Gets all nodes that returned true upon invoking a {@link IKeyCheck}.
- * @return all successful nodes
- */
- public KeyTreeNode[] getPassedNodes() {
- return passedNodes.toArray(EMPTY_NODES);
- }
- /**
- * Gets all nodes that returned false upon invoking a {@link IKeyCheck}.
- * @return all failing nodes
- */
- public KeyTreeNode[] getFailedNodes() {
- return failedNodes.toArray(EMPTY_NODES);
- }
-
- /**
- * Resets all passed and failed nodes.
- */
- public void reset() {
- passedNodes.clear();
- failedNodes.clear();
- }
-
- /**
- * Sets the key check for this visitor.
- * @param newKeyCheck new key check
- * @param reset whether to reset the passed and failed nodes.
- */
- public void setKeyCheck(IKeyCheck newKeyCheck, boolean reset) {
- if (reset) {
- reset();
- }
- this.keyCheck = newKeyCheck;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/NodePathRegexVisitor.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/NodePathRegexVisitor.java
deleted file mode 100644
index 13d8660e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/message/tree/visitor/NodePathRegexVisitor.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.message.tree.visitor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-
-/**
- * Visitor for finding keys matching the given regular expression.
- * @author Pascal Essiembre ([email protected])
- */
-public class NodePathRegexVisitor implements IKeyTreeVisitor {
-
- /** Holder for matching keys. */
- private List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>();
- private final String regex;
-
- /**
- * Constructor.
- */
- public NodePathRegexVisitor(String regex) {
- super();
- this.regex = regex;
- }
-
- /**
- * @see org.eclipse.babel.core.message.tree.visitor.IKeyTreeVisitor
- * #visitKeyTreeNode(org.eclipselabs.tapiji.translator.rap.babel.core.message.tree.KeyTreeNode)
- */
- public void visitKeyTreeNode(IKeyTreeNode node) {
- if (node.getMessageKey().matches(regex)) {
- nodes.add(node);
- }
- }
-
- /**
- * Gets matching key tree nodes.
- * @return matching key tree nodes
- */
- public List<IKeyTreeNode> getKeyTreeNodes() {
- return nodes;
- }
-
- /**
- * Gets matching key tree node paths.
- * @return matching key tree node paths
- */
- public List<String> getKeyTreeNodePaths() {
- List<String> paths = new ArrayList<String>(nodes.size());
- for (IKeyTreeNode node : nodes) {
- paths.add(node.getMessageKey());
- }
- return paths;
- }
-
-
- /**
- * Gets the first item matched.
- * @return first item matched, or <code>null</code> if none was found
- */
- public IKeyTreeNode getKeyTreeNode() {
- if (nodes.size() > 0) {
- return nodes.get(0);
- }
- return null;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/BabelUtils.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/BabelUtils.java
deleted file mode 100644
index 1ff92abb..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/BabelUtils.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.util;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.StringTokenizer;
-
-/**
- * Utility methods of all kinds used across the Babel API.
- * @author Pascal Essiembre
- */
-public final class BabelUtils {
-
- //TODO find a better sport for these methods?
-
- public static final String[] EMPTY_STRINGS = new String[] {};
-
- /**
- * Constructor.
- */
- private BabelUtils() {
- super();
- }
-
- /**
- * Null-safe testing of two objects for equality.
- * @param o1 object 1
- * @param o2 object 2
- * @return <code>true</code> if to objects are equal or if they are both
- * <code>null</code>.
- */
- public static boolean equals(Object o1, Object o2) {
- return (o1 == null && o2 == null || o1 != null && o1.equals(o2));
- }
-
- /**
- * Joins an array by the given separator.
- * @param array the array to join
- * @param separator the joining separator
- * @return joined string
- */
- public static String join(Object[] array, String separator) {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < array.length; i++) {
- Object item = array[i];
- if (item != null) {
- if (buf.length() > 0) {
- buf.append(separator);
- }
- buf.append(item);
- }
- }
- return buf.toString();
- }
-
-
- /**
- * Parses a string into a locale. The string is expected to be of the
- * same format of the string obtained by calling Locale.toString().
- * @param localeString string representation of a locale
- * @return a locale or <code>null</code> if string is empty or null
- */
- public static Locale parseLocale(String localeString) {
- if (localeString == null || localeString.trim().length() == 0) {
- return null;
- }
- StringTokenizer tokens =
- new StringTokenizer(localeString, "_"); //$NON-NLS-1$
- List<String> localeSections = new ArrayList<String>();
- while (tokens.hasMoreTokens()) {
- localeSections.add(tokens.nextToken());
- }
- Locale locale = null;
- switch (localeSections.size()) {
- case 1:
- locale = new Locale(localeSections.get(0));
- break;
- case 2:
- locale = new Locale(
- localeSections.get(0),
- localeSections.get(1));
- break;
- case 3:
- locale = new Locale(
- localeSections.get(0),
- localeSections.get(1),
- localeSections.get(2));
- break;
- default:
- break;
- }
- return locale;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/FileChangeListener.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/FileChangeListener.java
deleted file mode 100644
index 5d13b1a2..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/FileChangeListener.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.util;
-
-import java.io.File;
-
-/**
- * Listener interested in {@link File} changes.
- * @author Pascal Essiembre
- */
-public interface FileChangeListener {
- /**
- * Invoked when a file changes.
- * @param fileName name of changed file.
- */
- public void fileChanged(File file);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/FileMonitor.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/FileMonitor.java
deleted file mode 100644
index b59db3a0..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/FileMonitor.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.core.util;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.URL;
-import java.util.Hashtable;
-import java.util.Timer;
-import java.util.TimerTask;
-
-
-/**
- * Class monitoring a {@link File} for changes.
- * @author Pascal Essiembre
- */
-public class FileMonitor {
-
- private static final FileMonitor instance = new FileMonitor();
-
- private Timer timer;
- private Hashtable<String,FileMonitorTask> timerEntries;
-
- /**
- * Gets the file monitor instance.
- * @return file monitor instance
- */
- public static FileMonitor getInstance() {
- return instance;
- }
-
- /**
- * Constructor.
- */
- private FileMonitor() {
- // Create timer, run timer thread as daemon.
- timer = new Timer(true);
- timerEntries = new Hashtable<String,FileMonitorTask>();
- }
-
- /**
- * Adds a monitored file with a {@link FileChangeListener}.
- * @param listener listener to notify when the file changed.
- * @param fileName name of the file to monitor.
- * @param period polling period in milliseconds.
- */
- public void addFileChangeListener(
- FileChangeListener listener, String fileName, long period)
- throws FileNotFoundException {
- addFileChangeListener(listener, new File(fileName), period);
- }
-
- /**
- * Adds a monitored file with a FileChangeListener.
- * @param listener listener to notify when the file changed.
- * @param fileName name of the file to monitor.
- * @param period polling period in milliseconds.
- */
- public void addFileChangeListener(
- FileChangeListener listener, File file, long period)
- throws FileNotFoundException {
- removeFileChangeListener(listener, file);
- FileMonitorTask task = new FileMonitorTask(listener, file);
- timerEntries.put(file.toString() + listener.hashCode(), task);
- timer.schedule(task, period, period);
- }
-
- /**
- * Remove the listener from the notification list.
- * @param listener the listener to be removed.
- */
- public void removeFileChangeListener(FileChangeListener listener,
- String fileName) {
- removeFileChangeListener(listener, new File(fileName));
- }
-
- /**
- * Remove the listener from the notification list.
- * @param listener the listener to be removed.
- */
- public void removeFileChangeListener(
- FileChangeListener listener, File file) {
- FileMonitorTask task = timerEntries.remove(
- file.toString() + listener.hashCode());
- if (task != null) {
- task.cancel();
- }
- }
-
- /**
- * Fires notification that a file changed.
- * @param listener file change listener
- * @param file the file that changed
- */
- protected void fireFileChangeEvent(
- FileChangeListener listener, File file) {
- listener.fileChanged(file);
- }
-
- /**
- * File monitoring task.
- */
- class FileMonitorTask extends TimerTask {
- FileChangeListener listener;
- File monitoredFile;
- long lastModified;
-
- public FileMonitorTask(FileChangeListener listener, File file)
- throws FileNotFoundException {
- this.listener = listener;
- this.lastModified = 0;
- monitoredFile = file;
- if (!monitoredFile.exists()) { // but is it on CLASSPATH?
- URL fileURL =
- listener.getClass().getClassLoader().getResource(
- file.toString());
- if (fileURL != null) {
- monitoredFile = new File(fileURL.getFile());
- } else {
- throw new FileNotFoundException("File Not Found: " + file);
- }
- }
- this.lastModified = monitoredFile.lastModified();
- }
-
- public void run() {
- long lastModified = monitoredFile.lastModified();
- if (lastModified != this.lastModified) {
- this.lastModified = lastModified;
- fireFileChangeEvent(this.listener, monitoredFile);
- }
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/PDEUtils.java b/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/PDEUtils.java
deleted file mode 100644
index 46f7548a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.core/src/org/eclipselabs/tapiji/translator/rap/babel/core/util/PDEUtils.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * 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.eclipselabs.tapiji.translator.rap.babel.core.util;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.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.eclipselabs.tapiji.translator.rap.babel.editor/.project b/org.eclipselabs.tapiji.translator.rap.babel.editor/.project
deleted file mode 100644
index 3bb11780..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.translator.rap.babel.editor</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap.babel.editor/META-INF/MANIFEST.MF
deleted file mode 100644
index f659a03b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,9 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Babel Editor Plug-in
-Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap.babel.editor
-Bundle-Version: 1.0.0.qualifier
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Require-Bundle: org.eclipse.rap.ui;bundle-version="1.5.0",
- org.eclipse.rap.ui.forms;bundle-version="1.5.0",
- org.eclipse.rap.ui.views;bundle-version="1.5.0"
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/OpenLocalizationEditorHandler.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/OpenLocalizationEditorHandler.java
deleted file mode 100644
index f38b7d78..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/OpenLocalizationEditorHandler.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.eclipselabs.pde.nls.internal.ui.editor.LocalizationEditor;
-import org.eclipselabs.pde.nls.internal.ui.editor.LocalizationEditorInput;
-
-public class OpenLocalizationEditorHandler extends AbstractHandler {
-
- public OpenLocalizationEditorHandler() {
- }
-
- /*
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
- IWorkbenchPage page = window.getActivePage();
- page.openEditor(new LocalizationEditorInput(), LocalizationEditor.ID);
- } catch (PartInitException e) {
- throw new RuntimeException(e);
- }
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java
deleted file mode 100644
index 79556026..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.dialogs;
-
-import java.util.ArrayList;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipselabs.pde.nls.internal.ui.parser.LocaleUtil;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-public class ConfigureColumnsDialog extends Dialog {
-
- private class ColumnField {
- Text text;
- ToolItem clearButton;
- }
-
- private ArrayList<ColumnField> fields = new ArrayList<ColumnField>();
-
- private ArrayList<String> result = new ArrayList<String>();
- private String[] initialValues;
- private Color errorColor;
-
- private Image clearImage;
-
- public ConfigureColumnsDialog(Shell parentShell, String[] initialValues) {
- super(parentShell);
- setShellStyle(getShellStyle() | SWT.RESIZE);
- this.initialValues = initialValues;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#open()
- */
- @Override
- public int open() {
- return super.open();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Configure Columns");
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
- GridLayout gridLayout = (GridLayout) composite.getLayout();
- gridLayout.numColumns = 3;
-
- Label label = new Label(composite, SWT.NONE);
- label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- label.setText("Enter \"key\", \"default\" or locale (e.g. \"de\" or \"zh_TW\"):");
- label.setLayoutData(GridDataFactory.fillDefaults().hint(300, SWT.DEFAULT).span(3, 1).create());
-
- fields.add(createLanguageField(composite, "Column &1:"));
- fields.add(createLanguageField(composite, "Column &2:"));
- fields.add(createLanguageField(composite, "Column &3:"));
- fields.add(createLanguageField(composite, "Column &4:"));
-
- if (initialValues != null) {
- for (int i = 0; i < 4 && i < initialValues.length; i++) {
- fields.get(i).text.setText(initialValues[i]);
- }
- }
-
- ModifyListener modifyListener = new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate();
- }
- };
- for (ColumnField field : fields) {
- field.text.addModifyListener(modifyListener);
- }
- errorColor = new Color(Display.getCurrent(), 0xff, 0x7f, 0x7f);
-
- return composite;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createContents(Composite parent) {
- Control contents = super.createContents(parent);
- validate();
- return contents;
- }
-
- private ColumnField createLanguageField(Composite parent, String labelText) {
- Label label = new Label(parent, SWT.NONE);
- label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- label.setText(labelText);
-
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
-
- if (clearImage == null)
- clearImage = MessagesEditorPlugin.getImageDescriptor("elcl16/clear_co.gif").createImage(); //$NON-NLS-1$
-
- ToolBar toolbar = new ToolBar(parent, SWT.FLAT);
- ToolItem item = new ToolItem(toolbar, SWT.PUSH);
- item.setImage(clearImage);
- item.setToolTipText("Clear");
- item.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- for (ColumnField field : fields) {
- if (field.clearButton == e.widget) {
- field.text.setText(""); //$NON-NLS-1$
- }
- }
- }
- });
-
- ColumnField field = new ColumnField();
- field.text = text;
- field.clearButton = item;
- return field;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- @Override
- protected void okPressed() {
- for (ColumnField field : fields) {
- String text = field.text.getText().trim();
- if (text.length() > 0) {
- result.add(text);
- }
- }
- super.okPressed();
- errorColor.dispose();
- clearImage.dispose();
- }
-
- public String[] getResult() {
- return result.toArray(new String[result.size()]);
- }
-
- protected void validate() {
- boolean isValid = true;
- for (ColumnField field : fields) {
- String text = field.text.getText();
- if (text.equals("") || text.equals("key") || text.equals("default")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- field.text.setBackground(null);
- } else {
- try {
- LocaleUtil.parseLocale(text);
- field.text.setBackground(null);
- } catch (IllegalArgumentException e) {
- field.text.setBackground(errorColor);
- isValid = false;
- }
- }
- }
- Button okButton = getButton(IDialogConstants.OK_ID);
- okButton.setEnabled(isValid);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java
deleted file mode 100644
index 2520df8f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-public class EditMultiLineEntryDialog extends Dialog {
-
- private Text textWidget;
- private String text;
- private boolean readOnly;
-
- protected EditMultiLineEntryDialog(Shell parentShell, String initialInput, boolean readOnly) {
- super(parentShell);
- this.readOnly = readOnly;
- setShellStyle(getShellStyle() | SWT.RESIZE);
- text = initialInput;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Edit Resource Bundle Entry");
- }
-
- public String getValue() {
- return text;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
-
- int readOnly = this.readOnly ? SWT.READ_ONLY : 0;
- Text text = new Text(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | readOnly);
- text.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).hint(350, 150).create());
- text.setText(text == null ? "" : this.text);
-
- textWidget = text;
-
- return composite;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- @Override
- protected void okPressed() {
- text = textWidget.getText();
- super.okPressed();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
deleted file mode 100644
index 0fcbdd94..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesIFileResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundle;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundleKey;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-public class EditResourceBundleEntriesDialog extends Dialog {
-
- private class LocaleField {
- ResourceBundle bundle;
- Label label;
- Text text;
- Locale locale;
- String oldValue;
- boolean isReadOnly;
- Button button;
- }
-
- private ResourceBundleKey resourceBundleKey;
- protected ArrayList<LocaleField> fields = new ArrayList<LocaleField>();
- private final Locale[] locales;
- private Color errorColor;
-
- /**
- * @param locales the locales to edit
- */
- public EditResourceBundleEntriesDialog(Shell parentShell, Locale[] locales) {
- super(parentShell);
- this.locales = locales;
- setShellStyle(getShellStyle() | SWT.RESIZE);
- }
-
- public void setResourceBundleKey(ResourceBundleKey resourceBundleKey) {
- this.resourceBundleKey = resourceBundleKey;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#open()
- */
- @Override
- public int open() {
- if (resourceBundleKey == null)
- throw new RuntimeException("Resource bundle key not set.");
- return super.open();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Edit Resource Bundle Entries");
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
- GridLayout gridLayout = (GridLayout) composite.getLayout();
- gridLayout.numColumns = 3;
-
- Label keyLabel = new Label(composite, SWT.NONE);
- keyLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- keyLabel.setText("&Key:");
-
- int style = SWT.SINGLE | SWT.LEAD | SWT.BORDER | SWT.READ_ONLY;
- Text keyText = new Text(composite, style);
- keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- keyText.setText(resourceBundleKey.getName());
-
- new Label(composite, SWT.NONE); // spacer
-
- for (Locale locale : locales) {
- if (locale.getLanguage().equals("")) { //$NON-NLS-1$
- fields.add(createLocaleField(composite, locale, "&Default Bundle:"));
- } else {
- fields.add(createLocaleField(composite, locale, "&" + locale.getDisplayName() + ":"));
- }
- }
-
- // Set focus on first editable field
- if (fields.size() > 0) {
- for (int i = 0; i < fields.size(); i++) {
- if (fields.get(i).text.getEditable()) {
- fields.get(i).text.setFocus();
- break;
- }
- }
- }
-
- Label label = new Label(composite, SWT.NONE);
- label.setLayoutData(GridDataFactory.fillDefaults().span(3, 1).create());
- label.setText("Note: The following escape sequences are allowed: \\r, \\n, \\t, \\\\");
-
- ModifyListener modifyListener = new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate();
- }
- };
- for (LocaleField field : fields) {
- field.text.addModifyListener(modifyListener);
- }
- errorColor = new Color(Display.getCurrent(), 0xff, 0x7f, 0x7f);
-
- return composite;
- }
-
- private LocaleField createLocaleField(Composite parent, Locale locale, String localeLabel) {
- ResourceBundle bundle = resourceBundleKey.getFamily().getBundle(locale);
-
- Label label = new Label(parent, SWT.NONE);
- label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- label.setText(localeLabel);
-
- boolean readOnly = bundle == null || bundle.isReadOnly();
- int style = SWT.SINGLE | SWT.LEAD | SWT.BORDER | (readOnly ? SWT.READ_ONLY : 0);
- Text text = new Text(parent, style);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
-
- String value = null;
- if (bundle != null) {
- try {
- value = bundle.getString(resourceBundleKey.getName());
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (value == null) {
- if (readOnly) {
- value = "(Key does not exist)";
- } else {
- value = ""; // TODO Indicate that the entry is missing: perhaps red background
- }
- }
- text.setText(escape(value));
- } else {
- text.setText("(Resource bundle not found)");
- }
-
- Button button = new Button(parent, SWT.PUSH);
- button.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- button.setText("..."); //$NON-NLS-1$
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- for (LocaleField field : fields) {
- if (e.widget == field.button) {
- EditMultiLineEntryDialog dialog = new EditMultiLineEntryDialog(
- getShell(),
- unescape(field.text.getText()),
- field.isReadOnly);
- if (dialog.open() == Window.OK) {
- field.text.setText(escape(dialog.getValue()));
- }
- }
- }
- }
- });
-
- LocaleField field = new LocaleField();
- field.bundle = bundle;
- field.label = label;
- field.text = text;
- field.locale = locale;
- field.oldValue = value;
- field.isReadOnly = readOnly;
- field.button = button;
- return field;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- @Override
- protected void okPressed() {
- for (LocaleField field : fields) {
- if (field.isReadOnly)
- continue;
- String key = resourceBundleKey.getName();
- String value = unescape(field.text.getText());
- boolean hasChanged = (field.oldValue == null && !value.equals("")) //$NON-NLS-1$
- || (field.oldValue != null && !field.oldValue.equals(value));
- if (hasChanged) {
- try {
- Object resource = field.bundle.getUnderlyingResource();
- if (resource instanceof IFile) {
- MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
- IMessagesResource messagesResource = new PropertiesIFileResource(
- field.locale,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- (IFile) resource, MessagesEditorPlugin.getDefault());
- MessagesBundle bundle = new MessagesBundle(messagesResource);
-
- Message message = new Message(key, field.locale);
- message.setText(value);
- bundle.addMessage(message);
-
- // This commented out code is how the update was done before this code was merged
- // into the Babel Message Editor. This code should be removed.
-
-// InputStream inputStream;
-// IFile file = (IFile) resource;
-//
-// inputStream = file.getContents();
-// RawBundle rawBundle;
-// try {
-// rawBundle = RawBundle.createFrom(inputStream);
-// rawBundle.put(key, value);
-// } catch (Exception e) {
-// openError("Value could not be saved: " + value, e);
-// return;
-// }
-// StringWriter stringWriter = new StringWriter();
-// rawBundle.writeTo(stringWriter);
-// byte[] bytes = stringWriter.toString().getBytes("ISO-8859-1"); //$NON-NLS-1$
-// ByteArrayInputStream newContents = new ByteArrayInputStream(bytes);
-// file.setContents(newContents, false, false, new NullProgressMonitor());
- } else {
- // Unexpected type of resource
- throw new RuntimeException("Not yet implemented."); //$NON-NLS-1$
- }
- field.bundle.put(key, value);
- } catch (Exception e) {
- openError("Value could not be saved: " + value, e);
- return;
- }
- }
- }
- super.okPressed();
- errorColor.dispose();
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsStrategy()
- */
- @Override
- protected int getDialogBoundsStrategy() {
- return DIALOG_PERSISTLOCATION | DIALOG_PERSISTSIZE;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
- */
- @Override
- protected IDialogSettings getDialogBoundsSettings() {
- IDialogSettings settings = MessagesEditorPlugin.getDefault().getDialogSettings();
- String sectionName = "EditResourceBundleEntriesDialog"; //$NON-NLS-1$
- IDialogSettings section = settings.getSection(sectionName);
- if (section == null)
- section = settings.addNewSection(sectionName);
- return section;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getInitialSize()
- */
- @Override
- protected Point getInitialSize() {
- Point initialSize = super.getInitialSize();
- // Make sure that all locales are visible
- Point size = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
- if (initialSize.y < size.y)
- initialSize.y = size.y;
- return initialSize;
- }
-
- protected void validate() {
- boolean isValid = true;
- for (LocaleField field : fields) {
- try {
- unescape(field.text.getText());
- field.text.setBackground(null);
- } catch (IllegalArgumentException e) {
- field.text.setBackground(errorColor);
- isValid = false;
- }
- }
- Button okButton = getButton(IDialogConstants.OK_ID);
- okButton.setEnabled(isValid);
- }
-
- private void openError(String message, Exception e) {
- IStatus status;
- if (e instanceof CoreException) {
- CoreException coreException = (CoreException) e;
- status = coreException.getStatus();
- } else {
- status = new Status(IStatus.ERROR, "<dummy>", e.getMessage(), e); //$NON-NLS-1$
- }
- e.printStackTrace();
- ErrorDialog.openError(getParentShell(), "Error", message, status);
- }
-
- /**
- * Escapes line separators, tabulators and double backslashes.
- *
- * @param str
- * @return the escaped string
- */
- public static String escape(String str) {
- StringBuilder builder = new StringBuilder(str.length() + 10);
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- switch (c) {
- case '\r' :
- builder.append("\\r"); //$NON-NLS-1$
- break;
- case '\n' :
- builder.append("\\n"); //$NON-NLS-1$
- break;
- case '\t' :
- builder.append("\\t"); //$NON-NLS-1$
- break;
- case '\\' :
- builder.append("\\\\"); //$NON-NLS-1$
- break;
- default :
- builder.append(c);
- break;
- }
- }
- return builder.toString();
- }
-
- /**
- * Unescapes line separators, tabulators and double backslashes.
- *
- * @param str
- * @return the unescaped string
- * @throws IllegalArgumentException when an invalid or unexpected escape is encountered
- */
- public static String unescape(String str) {
- StringBuilder builder = new StringBuilder(str.length() + 10);
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- if (c == '\\') {
- switch (str.charAt(i + 1)) {
- case 'r' :
- builder.append('\r');
- break;
- case 'n' :
- builder.append('\n');
- break;
- case 't' :
- builder.append('\t');
- break;
- case '\\' :
- builder.append('\\');
- break;
- default :
- throw new IllegalArgumentException("Invalid escape sequence.");
- }
- i++;
- } else {
- builder.append(c);
- }
- }
- return builder.toString();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/FilterOptions.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/FilterOptions.java
deleted file mode 100644
index 01ffd95f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/FilterOptions.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.dialogs;
-
-public class FilterOptions {
-
- public boolean filterPlugins;
- public String[] pluginPatterns;
- public boolean keysWithMissingEntriesOnly;
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java
deleted file mode 100644
index 5b23859f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-public class FilterOptionsDialog extends Dialog {
-
- private static final String SEPARATOR = ","; //$NON-NLS-1$
-
- private Button enablePluginPatterns;
- private Button keysWithMissingEntriesOnly;
- private Text pluginPatterns;
-
- private FilterOptions initialOptions;
- private FilterOptions result;
-
- public FilterOptionsDialog(Shell shell) {
- super(shell);
- }
-
- public void setInitialFilterOptions(FilterOptions initialfilterOptions) {
- this.initialOptions = initialfilterOptions;
- }
-
- /*
- * @see org.eclipse.ui.dialogs.SelectionDialog#configureShell(org.eclipse.swt.widgets.Shell)
- */
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText("Filters");
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
-
- // Checkbox
- enablePluginPatterns = new Button(composite, SWT.CHECK);
- enablePluginPatterns.setFocus();
- enablePluginPatterns.setText("Filter by plug-in id patterns (separated by comma):");
- enablePluginPatterns.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- pluginPatterns.setEnabled(enablePluginPatterns.getSelection());
- }
- });
- enablePluginPatterns.setSelection(initialOptions.filterPlugins);
-
- // Pattern field
- pluginPatterns = new Text(composite, SWT.SINGLE | SWT.BORDER);
- GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
- data.widthHint = convertWidthInCharsToPixels(59);
- pluginPatterns.setLayoutData(data);
- pluginPatterns.setEnabled(initialOptions.filterPlugins);
- if (initialOptions.pluginPatterns != null) {
- StringBuilder builder = new StringBuilder();
- String[] patterns = initialOptions.pluginPatterns;
- for (String pattern : patterns) {
- if (builder.length() > 0) {
- builder.append(SEPARATOR);
- builder.append(" ");
- }
- builder.append(pattern);
- }
- pluginPatterns.setText(builder.toString());
- }
-
- keysWithMissingEntriesOnly = new Button(composite, SWT.CHECK);
- keysWithMissingEntriesOnly.setText("Keys with missing entries only");
- keysWithMissingEntriesOnly.setSelection(initialOptions.keysWithMissingEntriesOnly);
-
- applyDialogFont(parent);
- return parent;
- }
-
- protected void okPressed() {
- String patterns = pluginPatterns.getText();
- result = new FilterOptions();
- result.filterPlugins = enablePluginPatterns.getSelection();
- String[] split = patterns.split(SEPARATOR);
- for (int i = 0; i < split.length; i++) {
- split[i] = split[i].trim();
- }
- result.pluginPatterns = split;
- result.keysWithMissingEntriesOnly = keysWithMissingEntriesOnly.getSelection();
- super.okPressed();
- }
-
- public FilterOptions getResult() {
- return result;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditor.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditor.java
deleted file mode 100644
index 82e90e91..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditor.java
+++ /dev/null
@@ -1,1088 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.editor;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.layout.TableColumnLayout;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILazyContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IPropertyListener;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ContributionItemFactory;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.ui.internal.misc.StringMatcher;
-import org.eclipse.ui.part.EditorPart;
-import org.eclipse.ui.part.IShowInSource;
-import org.eclipse.ui.part.ShowInContext;
-import org.eclipselabs.pde.nls.internal.ui.dialogs.ConfigureColumnsDialog;
-import org.eclipselabs.pde.nls.internal.ui.dialogs.EditResourceBundleEntriesDialog;
-import org.eclipselabs.pde.nls.internal.ui.dialogs.FilterOptions;
-import org.eclipselabs.pde.nls.internal.ui.dialogs.FilterOptionsDialog;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundle;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundleFamily;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundleKey;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundleKeyList;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundleModel;
-import org.eclipselabs.pde.nls.internal.ui.parser.LocaleUtil;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-// TODO Fix restriction and remove warning
-@SuppressWarnings("restriction")
-public class LocalizationEditor extends EditorPart {
-
- private final class LocalizationLabelProvider extends ColumnLabelProvider {
-
- private final Object columnConfig;
-
- public LocalizationLabelProvider(Object columnConfig) {
- this.columnConfig = columnConfig;
- }
-
- public String getText(Object element) {
- ResourceBundleKey key = (ResourceBundleKey) element;
- if (columnConfig == KEY)
- return key.getName();
- Locale locale = (Locale) columnConfig;
- String value;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- value = null;
- MessagesEditorPlugin.log(e);
- }
- if (value == null)
- value = "";
- return value;
- }
- }
-
- private class EditEntryAction extends Action {
- public EditEntryAction() {
- super("&Edit", IAction.AS_PUSH_BUTTON);
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- ResourceBundleKey key = getSelectedEntry();
- if (key == null) {
- return;
- }
- Shell shell = Display.getCurrent().getActiveShell();
- Locale[] locales = getLocales();
- EditResourceBundleEntriesDialog dialog = new EditResourceBundleEntriesDialog(shell, locales);
- dialog.setResourceBundleKey(key);
- if (dialog.open() == Window.OK) {
- updateLabels();
- }
- }
- }
-
- private class ConfigureColumnsAction extends Action {
- public ConfigureColumnsAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/conf_columns.gif"));
- setToolTipText("Configure Columns");
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell = Display.getCurrent().getActiveShell();
- String[] values = new String[columnConfigs.length];
- for (int i = 0; i < columnConfigs.length; i++) {
- String config = columnConfigs[i].toString();
- if (config.equals("")) //$NON-NLS-1$
- config = "default"; //$NON-NLS-1$
- values[i] = config;
- }
- ConfigureColumnsDialog dialog = new ConfigureColumnsDialog(shell, values);
- if (dialog.open() == Window.OK) {
- String[] result = dialog.getResult();
- Object[] newConfigs = new Object[result.length];
- for (int i = 0; i < newConfigs.length; i++) {
- if (result[i].equals("key")) { //$NON-NLS-1$
- newConfigs[i] = KEY;
- } else if (result[i].equals("default")) { //$NON-NLS-1$
- newConfigs[i] = new Locale("");
- } else {
- newConfigs[i] = LocaleUtil.parseLocale(result[i]);
- }
- }
- setColumns(newConfigs);
- }
- }
- }
-
- private class EditFilterOptionsAction extends Action {
- public EditFilterOptionsAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/filter_obj.gif"));
- setToolTipText("Edit Filter Options");
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell = Display.getCurrent().getActiveShell();
- FilterOptionsDialog dialog = new FilterOptionsDialog(shell);
- dialog.setInitialFilterOptions(filterOptions);
- if (dialog.open() == Window.OK) {
- filterOptions = dialog.getResult();
- refresh();
- updateFilterLabel();
- }
- }
- }
-
- private class RefreshAction extends Action {
- public RefreshAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/refresh.gif"));
- setToolTipText("Refresh");
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- MessagesEditorPlugin.disposeModel();
- entryList = new ResourceBundleKeyList(new ResourceBundleKey[0]);
- tableViewer.getTable().setItemCount(0);
- updateLabels();
- refresh();
- }
- }
-
- private class BundleStringComparator implements Comparator<ResourceBundleKey> {
- private final Locale locale;
- public BundleStringComparator(Locale locale) {
- this.locale = locale;
- }
- public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
- String value1 = null;
- String value2 = null;
- try {
- value1 = o1.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- try {
- value2 = o2.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (value1 == null)
- value1 = ""; //$NON-NLS-1$
- if (value2 == null)
- value2 = ""; //$NON-NLS-1$
- return value1.compareToIgnoreCase(value2);
- }
- }
-
- private class ExportAction extends Action {
- public ExportAction() {
- super(null, IAction.AS_PUSH_BUTTON); //$NON-NLS-1$
- setImageDescriptor(MessagesEditorPlugin.getImageDescriptor("elcl16/export.gif"));
- setToolTipText("Export Current View to CSV or HTML File");
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell = Display.getCurrent().getActiveShell();
- FileDialog dialog = new FileDialog(shell);
- dialog.setText("Export File");
- dialog.setFilterExtensions(new String[] {"*.*", "*.htm; *.html", "*.txt; *.csv"});
- dialog.setFilterNames(new String[] {"All Files (*.*)", "HTML File (*.htm; *.html)",
- "Tabulator Separated File (*.txt; *.csv)"});
- final String filename = dialog.open();
- if (filename != null) {
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- public void run() {
- File file = new File(filename);
- try {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(file),
- "UTF8")); //$NON-NLS-1$
- boolean isHtml = filename.endsWith(".htm") || filename.endsWith(".html"); //$NON-NLS-1$ //$NON-NLS-2$
- if (isHtml) {
- writer.write("" //$NON-NLS-1$
- + "<html>\r\n" //$NON-NLS-1$
- + "<head>\r\n" //$NON-NLS-1$
- + "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" //$NON-NLS-1$
- + "<style>\r\n" //$NON-NLS-1$
- + "table {width:100%;}\r\n" //$NON-NLS-1$
- + "td.sep {height:10px;background:#C0C0C0;}\r\n" //$NON-NLS-1$
- + "</style>\r\n" //$NON-NLS-1$
- + "</head>\r\n" //$NON-NLS-1$
- + "<body>\r\n" //$NON-NLS-1$
- + "<table width=\"100%\" border=\"1\">\r\n"); //$NON-NLS-1$
- }
-
- int size = entryList.getSize();
- Object[] configs = LocalizationEditor.this.columnConfigs;
- int valueCount = 0;
- int missingCount = 0;
- for (int i = 0; i < size; i++) {
- ResourceBundleKey key = entryList.getKey(i);
- if (isHtml) {
- writer.write("<table border=\"1\">\r\n"); //$NON-NLS-1$
- }
- for (int j = 0; j < configs.length; j++) {
- if (isHtml) {
- writer.write("<tr><td>"); //$NON-NLS-1$
- }
- Object config = configs[j];
- if (!isHtml && j > 0)
- writer.write("\t"); //$NON-NLS-1$
- if (config == KEY) {
- writer.write(key.getName());
- } else {
- Locale locale = (Locale) config;
- String value;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- value = null;
- MessagesEditorPlugin.log(e);
- }
- if (value == null) {
- value = ""; //$NON-NLS-1$
- missingCount++;
- } else {
- valueCount++;
- }
- writer.write(EditResourceBundleEntriesDialog.escape(value));
- }
- if (isHtml) {
- writer.write("</td></tr>\r\n"); //$NON-NLS-1$
- }
- }
- if (isHtml) {
- writer.write("<tr><td class=\"sep\"> </td></tr>\r\n"); //$NON-NLS-1$
- writer.write("</table>\r\n"); //$NON-NLS-1$
- } else {
- writer.write("\r\n"); //$NON-NLS-1$
- }
- }
- if (isHtml) {
- writer.write("</body>\r\n" + "</html>\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- writer.close();
- Shell shell = Display.getCurrent().getActiveShell();
- MessageDialog.openInformation(
- shell,
- "Finished",
- "File written successfully.\n\nNumber of entries written: "
- + entryList.getSize()
- + "\nNumber of translations: "
- + valueCount
- + " ("
- + missingCount
- + " missing)");
- } catch (IOException e) {
- Shell shell = Display.getCurrent().getActiveShell();
- ErrorDialog.openError(shell, "Error", "Error saving file.", new Status(
- IStatus.ERROR,
- MessagesEditorPlugin.PLUGIN_ID,
- e.getMessage(),
- e));
- }
- }
- });
- }
- }
- }
-
- public static final String ID = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
-
- protected static final Object KEY = "key"; // used to indicate the key column
-
- private static final String PREF_SECTION_NAME = "org.eclipse.pde.nls.ui.LocalizationEditor"; //$NON-NLS-1$
- private static final String PREF_SORT_ORDER = "sortOrder"; //$NON-NLS-1$
- private static final String PREF_COLUMNS = "columns"; //$NON-NLS-1$
- private static final String PREF_FILTER_OPTIONS_FILTER_PLUGINS = "filterOptions_filterPlugins"; //$NON-NLS-1$
- private static final String PREF_FILTER_OPTIONS_PLUGIN_PATTERNS = "filterOptions_pluginPatterns"; //$NON-NLS-1$
- private static final String PREF_FILTER_OPTIONS_MISSING_ONLY = "filterOptions_missingOnly"; //$NON-NLS-1$
-
- // Actions
- private EditFilterOptionsAction editFiltersAction;
- private ConfigureColumnsAction selectLanguagesAction;
- private RefreshAction refreshAction;
- private ExportAction exportAction;
-
- // Form
- protected FormToolkit toolkit = new FormToolkit(Display.getCurrent());
- private Form form;
- private Image formImage;
-
- // Query
- protected Composite queryComposite;
- protected Text queryText;
-
- // Results
- private Section resultsSection;
- private Composite tableComposite;
- protected TableViewer tableViewer;
- protected Table table;
- protected ArrayList<TableColumn> columns = new ArrayList<TableColumn>();
-
- // Data and configuration
- protected LocalizationEditorInput input;
- protected ResourceBundleKeyList entryList;
- protected FilterOptions filterOptions;
-
- /**
- * Column configuration. Values may be either <code>KEY</code> or a {@link Locale}.
- */
- protected Object[] columnConfigs;
- /**
- * Either <code>KEY</code> or a {@link Locale}.
- */
- protected Object sortOrder;
-
- private String lastQuery = "";
- protected Job searchJob;
-
- private ISchedulingRule mutexRule = new ISchedulingRule() {
- public boolean contains(ISchedulingRule rule) {
- return rule == this;
- }
- public boolean isConflicting(ISchedulingRule rule) {
- return rule == this;
- }
- };
-
- private Label filteredLabel;
-
- public LocalizationEditor() {
- }
-
- public ResourceBundleKey getSelectedEntry() {
- IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
- if (selection.size() == 1) {
- return (ResourceBundleKey) selection.getFirstElement();
- }
- return null;
- }
-
- public String getQueryText() {
- return queryText.getText();
- }
-
- @Override
- public void createPartControl(Composite parent) {
- GridData gd;
- GridLayout gridLayout;
-
- form = toolkit.createForm(parent);
- form.setSeparatorVisible(true);
- form.setText("Localization");
-
- form.setImage(formImage = MessagesEditorPlugin.getImageDescriptor("obj16/nls_editor.gif").createImage()); //$NON-NLS-1$
- toolkit.adapt(form);
- toolkit.paintBordersFor(form);
- final Composite body = form.getBody();
- gridLayout = new GridLayout();
- gridLayout.numColumns = 1;
- body.setLayout(gridLayout);
- toolkit.paintBordersFor(body);
- toolkit.decorateFormHeading(form);
-
- queryComposite = toolkit.createComposite(body);
- gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
- queryComposite.setLayoutData(gd);
- gridLayout = new GridLayout(5, false);
- gridLayout.marginHeight = 0;
- queryComposite.setLayout(gridLayout);
- toolkit.paintBordersFor(queryComposite);
-
- // Form toolbar
- editFiltersAction = new EditFilterOptionsAction();
- selectLanguagesAction = new ConfigureColumnsAction();
- refreshAction = new RefreshAction();
- exportAction = new ExportAction();
- IToolBarManager toolBarManager = form.getToolBarManager();
- toolBarManager.add(refreshAction);
- toolBarManager.add(editFiltersAction);
- toolBarManager.add(selectLanguagesAction);
- toolBarManager.add(exportAction);
- form.updateToolBar();
-
- toolkit.createLabel(queryComposite, "Search:");
-
- // Query text
- queryText = toolkit.createText(queryComposite, "", SWT.WRAP | SWT.SINGLE); //$NON-NLS-1$
- queryText.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == SWT.ARROW_DOWN) {
- table.setFocus();
- } else if (e.keyCode == SWT.ESC) {
- queryText.setText(""); //$NON-NLS-1$
- }
- }
- });
- queryText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- executeQuery();
-
- Object[] listeners = getListeners();
- for (int i = 0; i < listeners.length; i++) {
- IPropertyListener listener = (IPropertyListener) listeners[i];
- listener.propertyChanged(this, PROP_TITLE);
- }
- }
- });
- gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
- queryText.setLayoutData(gd);
- toolkit.adapt(queryText, true, true);
-
- ToolBarManager toolBarManager2 = new ToolBarManager(SWT.FLAT);
- toolBarManager2.createControl(queryComposite);
- ToolBar control = toolBarManager2.getControl();
- toolkit.adapt(control);
-
- // Results section
- resultsSection = toolkit.createSection(body, ExpandableComposite.TITLE_BAR
- | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
- resultsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
- resultsSection.setText("Localization Strings");
- toolkit.adapt(resultsSection);
-
- final Composite resultsComposite = toolkit.createComposite(resultsSection, SWT.NONE);
- toolkit.adapt(resultsComposite);
- final GridLayout gridLayout2 = new GridLayout();
- gridLayout2.marginTop = 1;
- gridLayout2.marginWidth = 1;
- gridLayout2.marginHeight = 1;
- gridLayout2.horizontalSpacing = 0;
- resultsComposite.setLayout(gridLayout2);
-
- filteredLabel = new Label(resultsSection, SWT.NONE);
- filteredLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
- filteredLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
- filteredLabel.setText(""); //$NON-NLS-1$
-
- toolkit.paintBordersFor(resultsComposite);
- resultsSection.setClient(resultsComposite);
- resultsSection.setTextClient(filteredLabel);
-
- tableComposite = toolkit.createComposite(resultsComposite, SWT.NONE);
- tableComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
- toolkit.adapt(tableComposite);
- tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // Table
- createTableViewer();
-
- registerContextMenu();
-
- // Set default configuration
- filterOptions = new FilterOptions();
- filterOptions.filterPlugins = false;
- filterOptions.pluginPatterns = new String[0];
- filterOptions.keysWithMissingEntriesOnly = false;
- sortOrder = KEY;
- columnConfigs = new Object[] {KEY, new Locale(""), new Locale("de")}; //$NON-NLS-1$ //$NON-NLS-2$
-
- // Load configuration
- try {
- loadSettings();
- } catch (Exception e) {
- // Ignore
- }
-
- updateColumns();
- updateFilterLabel();
- table.setSortDirection(SWT.UP);
- }
-
- protected void updateFilterLabel() {
- if (filterOptions.filterPlugins || filterOptions.keysWithMissingEntriesOnly) {
- filteredLabel.setText("(filtered)");
- } else {
- filteredLabel.setText(""); //$NON-NLS-1$
- }
- filteredLabel.getParent().layout(true);
- }
-
- private void loadSettings() {
- // TODO Move this to the preferences?
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault().getDialogSettings();
- IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
- if (section == null)
- return;
-
- // Sort order
- String sortOrderString = section.get(PREF_SORT_ORDER);
- if (sortOrderString != null) {
- if (sortOrderString.equals(KEY)) {
- sortOrder = KEY;
- } else {
- try {
- sortOrder = LocaleUtil.parseLocale(sortOrderString);
- } catch (IllegalArgumentException e) {
- // Should never happen
- }
- }
- }
-
- // Columns
- String columns = section.get(PREF_COLUMNS);
- if (columns != null) {
- String[] cols = columns.substring(1, columns.length() - 1).split(","); //$NON-NLS-1$
- columnConfigs = new Object[cols.length];
- for (int i = 0; i < cols.length; i++) {
- String value = cols[i].trim();
- if (value.equals(KEY)) {
- columnConfigs[i] = KEY;
- } else if (value.equals("default")) { //$NON-NLS-1$
- columnConfigs[i] = new Locale(""); //$NON-NLS-1$
- } else {
- try {
- columnConfigs[i] = LocaleUtil.parseLocale(value);
- } catch (IllegalArgumentException e) {
- columnConfigs[i] = null;
- }
- }
- }
- }
-
- // Filter options
- String filterOptions = section.get(PREF_FILTER_OPTIONS_FILTER_PLUGINS);
- this.filterOptions.filterPlugins = "true".equals(filterOptions); //$NON-NLS-1$
- String patterns = section.get(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS);
- if (patterns != null) {
- String[] split = patterns.substring(1, patterns.length() - 1).split(","); //$NON-NLS-1$
- for (int i = 0; i < split.length; i++) {
- split[i] = split[i].trim();
- }
- this.filterOptions.pluginPatterns = split;
- }
- this.filterOptions.keysWithMissingEntriesOnly = "true".equals(section.get(PREF_FILTER_OPTIONS_MISSING_ONLY)); //$NON-NLS-1$
-
- // TODO Save column widths
- }
-
- private void saveSettings() {
- IDialogSettings dialogSettings = MessagesEditorPlugin.getDefault().getDialogSettings();
- IDialogSettings section = dialogSettings.getSection(PREF_SECTION_NAME);
- if (section == null) {
- section = dialogSettings.addNewSection(PREF_SECTION_NAME);
- }
- // Sort order
- section.put(PREF_SORT_ORDER, sortOrder.toString());
-
- // Columns
- section.put(PREF_COLUMNS, Arrays.toString(columnConfigs));
-
- // Filter options
- section.put(PREF_FILTER_OPTIONS_FILTER_PLUGINS, filterOptions.filterPlugins);
- section.put(PREF_FILTER_OPTIONS_PLUGIN_PATTERNS, Arrays.toString(filterOptions.pluginPatterns));
- section.put(PREF_FILTER_OPTIONS_MISSING_ONLY, filterOptions.keysWithMissingEntriesOnly);
- }
-
- private void createTableViewer() {
- table = new Table(tableComposite, SWT.VIRTUAL | SWT.FULL_SELECTION | SWT.MULTI);
- tableViewer = new TableViewer(table);
- table.setHeaderVisible(true);
- toolkit.adapt(table);
- toolkit.paintBordersFor(table);
- toolkit.adapt(table, true, true);
-
- tableViewer.setContentProvider(new ILazyContentProvider() {
- public void updateElement(int index) {
- tableViewer.replace(entryList.getKey(index), index);
- }
- public void dispose() {
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- });
- tableViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- new EditEntryAction().run();
- }
- });
- }
-
- private void registerContextMenu() {
- MenuManager menuManager = new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuManager.setRemoveAllWhenShown(true);
- menuManager.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager menu) {
- fillContextMenu(menu);
- }
- });
- Menu contextMenu = menuManager.createContextMenu(table);
- table.setMenu(contextMenu);
- getSite().registerContextMenu(menuManager, getSite().getSelectionProvider());
- }
-
- protected void fillContextMenu(IMenuManager menu) {
- int selectionCount = table.getSelectionCount();
- if (selectionCount == 1) {
- menu.add(new EditEntryAction());
- menu.add(new Separator());
- }
- MenuManager showInSubMenu = new MenuManager("&Show In");
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- IContributionItem item = ContributionItemFactory.VIEWS_SHOW_IN.create(window);
- showInSubMenu.add(item);
- menu.add(showInSubMenu);
- }
-
- @Override
- public void setFocus() {
- queryText.setFocus();
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- setSite(site);
- setInput(input);
- this.input = (LocalizationEditorInput) input;
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#dispose()
- */
- @Override
- public void dispose() {
- saveSettings();
- if (formImage != null) {
- formImage.dispose();
- formImage = null;
- }
- MessagesEditorPlugin.disposeModel();
- }
-
- protected void executeQuery() {
- String pattern = queryText.getText();
- lastQuery = pattern;
- executeQuery(pattern);
- }
-
- protected void executeQuery(final String pattern) {
- if (searchJob != null) {
- searchJob.cancel();
- }
- searchJob = new Job("Localization Editor Search...") {
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- form.setBusy(true);
- }
- });
-
- String keyPattern = pattern;
- if (!pattern.endsWith("*")) { //$NON-NLS-1$
- keyPattern = pattern.concat("*"); //$NON-NLS-1$
- }
- String strPattern = keyPattern;
- if (strPattern.length() > 0 && !strPattern.startsWith("*")) { //$NON-NLS-1$
- strPattern = "*".concat(strPattern); //$NON-NLS-1$
- }
-
- ResourceBundleModel model = MessagesEditorPlugin.getModel(new NullProgressMonitor());
- Locale[] locales = getLocales();
-
- // Collect keys
- ResourceBundleKey[] keys;
- if (!filterOptions.filterPlugins
- || filterOptions.pluginPatterns == null
- || filterOptions.pluginPatterns.length == 0) {
-
- // Ensure the bundles are loaded
- for (Locale locale : locales) {
- try {
- model.loadBundles(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- }
-
- try {
- keys = model.getAllKeys();
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- keys = new ResourceBundleKey[0];
- }
- } else {
- String[] patterns = filterOptions.pluginPatterns;
- StringMatcher[] matchers = new StringMatcher[patterns.length];
- for (int i = 0; i < matchers.length; i++) {
- matchers[i] = new StringMatcher(patterns[i], true, false);
- }
-
- int size = 0;
- ResourceBundleFamily[] allFamilies = model.getFamilies();
- ArrayList<ResourceBundleFamily> families = new ArrayList<ResourceBundleFamily>();
- for (int i = 0; i < allFamilies.length; i++) {
- ResourceBundleFamily family = allFamilies[i];
- String pluginId = family.getPluginId();
- for (StringMatcher matcher : matchers) {
- if (matcher.match(pluginId)) {
- families.add(family);
- break;
- }
- }
-
- }
- for (ResourceBundleFamily family : families) {
- size += family.getKeyCount();
- }
-
- ArrayList<ResourceBundleKey> filteredKeys = new ArrayList<ResourceBundleKey>(size);
- for (ResourceBundleFamily family : families) {
- // Ensure the bundles are loaded
- for (Locale locale : locales) {
- try {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.load();
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- }
-
- ResourceBundleKey[] familyKeys = family.getKeys();
- for (ResourceBundleKey key : familyKeys) {
- filteredKeys.add(key);
- }
- }
- keys = filteredKeys.toArray(new ResourceBundleKey[filteredKeys.size()]);
- }
-
- // Filter keys
- ArrayList<ResourceBundleKey> filtered = new ArrayList<ResourceBundleKey>();
-
- StringMatcher keyMatcher = new StringMatcher(keyPattern, true, false);
- StringMatcher strMatcher = new StringMatcher(strPattern, true, false);
- for (ResourceBundleKey key : keys) {
- if (monitor.isCanceled())
- return Status.OK_STATUS;
-
- // Missing entries
- if (filterOptions.keysWithMissingEntriesOnly) {
- boolean hasMissingEntry = false;
- // Check all columns for missing values
- for (Object config : columnConfigs) {
- if (config == KEY)
- continue;
- Locale locale = (Locale) config;
- String value = null;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (value == null || value.length() == 0) {
- hasMissingEntry = true;
- break;
- }
- }
- if (!hasMissingEntry)
- continue;
- }
-
- // Match key
- if (keyMatcher.match(key.getName())) {
- filtered.add(key);
- continue;
- }
-
- // Match entries
- for (Object config : columnConfigs) {
- if (config == KEY)
- continue;
- Locale locale = (Locale) config;
- String value = null;
- try {
- value = key.getValue(locale);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- if (strMatcher.match(value)) {
- filtered.add(key);
- break;
- }
- }
- }
-
- ResourceBundleKey[] array = filtered.toArray(new ResourceBundleKey[filtered.size()]);
- if (sortOrder == KEY) {
- Arrays.sort(array, new Comparator<ResourceBundleKey>() {
- public int compare(ResourceBundleKey o1, ResourceBundleKey o2) {
- return o1.getName().compareToIgnoreCase(o2.getName());
- }
- });
- } else {
- Locale locale = (Locale) sortOrder;
- Arrays.sort(array, new BundleStringComparator(locale));
- }
- entryList = new ResourceBundleKeyList(array);
-
- if (monitor.isCanceled())
- return Status.OK_STATUS;
-
- final ResourceBundleKeyList entryList2 = entryList;
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- form.setBusy(false);
- if (entryList2 != null) {
- entryList = entryList2;
- }
- setSearchResult(entryList);
- }
- });
- return Status.OK_STATUS;
- }
- };
- searchJob.setSystem(true);
- searchJob.setRule(mutexRule);
- searchJob.schedule();
- }
-
- protected void updateTableLayout() {
- table.getParent().layout(true, true);
- }
-
- protected void setSearchResult(ResourceBundleKeyList entryList) {
- table.removeAll();
- if (entryList != null) {
- table.setItemCount(entryList.getSize());
- } else {
- table.setItemCount(0);
- }
- updateTableLayout();
- }
-
- public void refresh() {
- executeQuery(lastQuery);
- }
-
- public void updateLabels() {
- table.redraw();
- table.update();
- }
-
- /**
- * @param columnConfigs an array containing <code>KEY</code> and {@link Locale} values
- */
- public void setColumns(Object[] columnConfigs) {
- this.columnConfigs = columnConfigs;
- updateColumns();
- }
-
- public void updateColumns() {
- for (TableColumn column : columns) {
- column.dispose();
- }
- columns.clear();
-
- TableColumnLayout tableColumnLayout = new TableColumnLayout();
- tableComposite.setLayout(tableColumnLayout);
-
- HashSet<Locale> localesToUnload = new HashSet<Locale>(4);
- Locale[] currentLocales = getLocales();
- for (Locale locale : currentLocales) {
- localesToUnload.add(locale);
- }
-
- // Create columns
- for (Object config : columnConfigs) {
- if (config == null)
- continue;
-
- final TableViewerColumn viewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
- TableColumn column = viewerColumn.getColumn();
- if (config == KEY) {
- column.setText("Key");
- } else {
- Locale locale = (Locale) config;
- if (locale.getLanguage().equals("")) { //$NON-NLS-1$
- column.setText("Default Bundle");
- } else {
- String displayName = locale.getDisplayName();
- if (displayName.equals("")) //$NON-NLS-1$
- displayName = locale.toString();
- column.setText(displayName);
- localesToUnload.remove(locale);
- }
- }
-
- viewerColumn.setLabelProvider(new LocalizationLabelProvider(config));
- tableColumnLayout.setColumnData(column, new ColumnWeightData(33));
- columns.add(column);
- column.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int size = columns.size();
- for (int i = 0; i < size; i++) {
- TableColumn column = columns.get(i);
- if (column == e.widget) {
- Object config = columnConfigs[i];
- sortOrder = config;
- table.setSortColumn(column);
- table.setSortDirection(SWT.UP);
- refresh();
- break;
- }
- }
- }
- });
- }
-
- // Update sort order
- List<Object> configs = Arrays.asList(columnConfigs);
- if (!configs.contains(sortOrder)) {
- sortOrder = KEY; // fall back to default sort order
- }
- int index = configs.indexOf(sortOrder);
- if (index != -1)
- table.setSortColumn(columns.get(index));
-
- refresh();
- }
-
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
- */
- @SuppressWarnings("unchecked")
- @Override
- public Object getAdapter(Class adapter) {
- if (IShowInSource.class == adapter) {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- ResourceBundleKey entry = getSelectedEntry();
- if (entry == null)
- return null;
- ResourceBundle bundle = entry.getParent().getBundle(new Locale(""));
- if (bundle == null)
- return null;
- Object resource = bundle.getUnderlyingResource();
- return new ShowInContext(resource, new StructuredSelection(resource));
- }
- };
- }
- return super.getAdapter(adapter);
- }
-
- /**
- * Returns the currently displayed locales.
- *
- * @return the currently displayed locales
- */
- public Locale[] getLocales() {
- ArrayList<Locale> locales = new ArrayList<Locale>(columnConfigs.length);
- for (Object config : columnConfigs) {
- if (config instanceof Locale) {
- Locale locale = (Locale) config;
- locales.add(locale);
- }
- }
- return locales.toArray(new Locale[locales.size()]);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditorInput.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditorInput.java
deleted file mode 100644
index 1ab72460..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditorInput.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.editor;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPersistableElement;
-
-public class LocalizationEditorInput implements IEditorInput, IPersistableElement {
-
- public LocalizationEditorInput() {
- }
-
- /*
- * @see org.eclipse.ui.IEditorInput#exists()
- */
- public boolean exists() {
- return true;
- }
-
- /*
- * @see org.eclipse.ui.IEditorInput#getImageDescriptor()
- */
- public ImageDescriptor getImageDescriptor() {
- return ImageDescriptor.getMissingImageDescriptor();
- }
-
- /*
- * @see org.eclipse.ui.IEditorInput#getName()
- */
- public String getName() {
- return "Localization Editor";
- }
-
- /*
- * @see org.eclipse.ui.IEditorInput#getPersistable()
- */
- public IPersistableElement getPersistable() {
- return this;
- }
-
- /*
- * @see org.eclipse.ui.IEditorInput#getToolTipText()
- */
- public String getToolTipText() {
- return getName();
- }
-
- /*
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- @SuppressWarnings("unchecked")
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- /*
- * @see org.eclipse.ui.IPersistableElement#getFactoryId()
- */
- public String getFactoryId() {
- return LocalizationEditorInputFactory.FACTORY_ID;
- }
-
- /*
- * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)
- */
- public void saveState(IMemento memento) {
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java
deleted file mode 100644
index a1bd053f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.editor;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IElementFactory;
-import org.eclipse.ui.IMemento;
-
-public class LocalizationEditorInputFactory implements IElementFactory {
-
- public static final String FACTORY_ID = "org.eclipse.pde.nls.ui.LocalizationEditorInputFactory"; //$NON-NLS-1$
-
- public LocalizationEditorInputFactory() {
- }
-
- /*
- * @see org.eclipse.ui.IElementFactory#createElement(org.eclipse.ui.IMemento)
- */
- public IAdaptable createElement(IMemento memento) {
- return new LocalizationEditorInput();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundle.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundle.java
deleted file mode 100644
index 094d5835..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundle.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.model;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJarEntryResource;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * A <code>ResourceBundle</code> represents a single <code>.properties</code> file.
- * <p>
- * <code>ResourceBundle</code> implements lazy loading. A bundle will be loaded
- * automatically when its entries are accessed. It can through the parent model by
- * calling {@link ResourceBundleModel#unloadBundles(Locale)} with the proper locale.
- * </p>
- */
-public class ResourceBundle extends ResourceBundleElement {
-
- private static boolean debug = false;
-
- /**
- * The bundle's locale.
- */
- private Locale locale;
- /**
- * The underlying resource. Either an {@link IFile} or an {@link IJarEntryResource}.
- */
- private Object resource;
-
- private HashMap<String, String> entries;
-
- public ResourceBundle(ResourceBundleFamily parent, Object resource, Locale locale) {
- super(parent);
- this.resource = resource;
- this.locale = locale;
- if (locale == null)
- throw new IllegalArgumentException("Locale may not be null.");
- }
-
- /**
- * Returns the family to which this bundle belongs.
- *
- * @return the family to which this bundle belongs
- */
- public ResourceBundleFamily getFamily() {
- return (ResourceBundleFamily) super.getParent();
- }
-
- /**
- * Returns the locale.
- *
- * @return the locale
- */
- public Locale getLocale() {
- return locale;
- }
-
- public String getString(String key) throws CoreException {
- load();
- return entries.get(key);
- }
-
- /**
- * Returns the underlying resource. This may be an {@link IFile}
- * or an {@link IJarEntryResource}.
- *
- * @return the underlying resource (an {@link IFile} or an {@link IJarEntryResource})
- */
- public Object getUnderlyingResource() {
- return resource;
- }
-
- protected boolean isLoaded() {
- return entries != null;
- }
-
- public void load() throws CoreException {
- if (isLoaded())
- return;
- entries = new HashMap<String, String>();
-
- if (resource instanceof IFile) {
- if (debug) {
- System.out.println("Loading " + resource + "...");
- }
- IFile file = (IFile) resource;
- InputStream inputStream = file.getContents();
- Properties properties = new Properties();
- try {
- properties.load(inputStream);
- putAll(properties);
- } catch (IOException e) {
- MessagesEditorPlugin.log("Error reading property file.", e);
- }
- } else if (resource instanceof IJarEntryResource) {
- IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
- InputStream inputStream = jarEntryResource.getContents();
- Properties properties = new Properties();
- try {
- properties.load(inputStream);
- putAll(properties);
- } catch (IOException e) {
- MessagesEditorPlugin.log("Error reading property file.", e);
- }
- } else {
- MessagesEditorPlugin.log("Unknown resource type.", new RuntimeException());
- }
- }
-
- protected void unload() {
- entries = null;
- }
-
- public boolean isReadOnly() {
- if (resource instanceof IJarEntryResource)
- return true;
- if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- return file.isReadOnly() || file.isLinked();
- }
- return false;
- }
-
- protected void putAll(Properties properties) throws CoreException {
- Set<Entry<Object, Object>> entrySet = properties.entrySet();
- Iterator<Entry<Object, Object>> iter = entrySet.iterator();
- ResourceBundleFamily family = getFamily();
- while (iter.hasNext()) {
- Entry<Object, Object> next = iter.next();
- Object key = next.getKey();
- Object value = next.getValue();
- if (key instanceof String && value instanceof String) {
- String stringKey = (String) key;
- entries.put(stringKey, (String) value);
- family.addKey(stringKey);
- }
- }
- }
-
- public void put(String key, String value) throws CoreException {
- load();
- ResourceBundleFamily family = getFamily();
- entries.put(key, value);
- family.addKey(key);
- }
-
- public String[] getKeys() throws CoreException {
- load();
- Set<String> keySet = entries.keySet();
- return keySet.toArray(new String[keySet.size()]);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleElement.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleElement.java
deleted file mode 100644
index ed1730ae..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleElement.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.model;
-
-public abstract class ResourceBundleElement {
-
- private final ResourceBundleElement parent;
-
- public ResourceBundleElement(ResourceBundleElement parent) {
- this.parent = parent;
- }
-
- public ResourceBundleElement getParent() {
- return parent;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleFamily.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleFamily.java
deleted file mode 100644
index aca115b5..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleFamily.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.model;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Locale;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-
-/**
- * A <code>ResourceBundleFamily</code> represents a group of resource bundles
- * that belong together. Member resource bundles may reside in the same project as the
- * default resource bundle, or in case of a plugin project, in a separate fragment
- * project.
- */
-public class ResourceBundleFamily extends ResourceBundleElement {
-
- /**
- * The project name of the default bundle.
- */
- private String projectName;
- /**
- * The plugin id of the default bundle, or <code>null</code> if not a plugin or fragment project.
- */
- private String pluginId;
- /**
- * The package name or path.
- */
- private String packageName;
- /**
- * The base name that all family members have in common.
- */
- private String baseName;
- /**
- * The members that belong to this resource bundle family (excluding the default bundle).
- */
- private ArrayList<ResourceBundle> members = new ArrayList<ResourceBundle>();
- /**
- * A collection of known keys.
- */
- private HashMap<String, ResourceBundleKey> keys = new HashMap<String, ResourceBundleKey>();
-
- public ResourceBundleFamily(ResourceBundleModel parent, String projectName, String pluginId,
- String packageName, String baseName) {
- super(parent);
- this.projectName = projectName;
- this.pluginId = pluginId;
- this.packageName = packageName;
- this.baseName = baseName;
- }
-
- public String getProjectName() {
- return projectName;
- }
-
- public String getPluginId() {
- return pluginId;
- }
-
- public String getPackageName() {
- return packageName;
- }
-
- public String getBaseName() {
- return baseName;
- }
-
- public ResourceBundle[] getBundles() {
- return members.toArray(new ResourceBundle[members.size()]);
- }
-
- public ResourceBundle getBundle(Locale locale) {
- for (ResourceBundle bundle : members) {
- if (bundle.getLocale().equals(locale)) {
- return bundle;
- }
- }
- return null;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- if (pluginId != null) {
- return baseName.hashCode() ^ pluginId.hashCode();
- } else {
- return baseName.hashCode() ^ projectName.hashCode();
- }
- }
-
- protected void addBundle(ResourceBundle bundle) throws CoreException {
- Assert.isTrue(bundle.getParent() == this);
- members.add(bundle);
- }
-
- protected void addKey(String key) {
- if (keys.get(key) == null) {
- keys.put(key, new ResourceBundleKey(this, key));
- }
- }
-
- public ResourceBundleKey[] getKeys() {
- Collection<ResourceBundleKey> values = keys.values();
- return values.toArray(new ResourceBundleKey[values.size()]);
- }
-
- public int getKeyCount() {
- return keys.size();
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "projectName=" + projectName + ", packageName=" + packageName + ", baseName=" + baseName;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleKey.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleKey.java
deleted file mode 100644
index 77eeca4a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleKey.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.model;
-
-import java.util.Locale;
-
-import org.eclipse.core.runtime.CoreException;
-
-/**
- * A <code>ResourceBundleKey</code> represents a key used in one or more bundles of
- * a {@link ResourceBundleFamily}.
- */
-public class ResourceBundleKey extends ResourceBundleElement {
-
- private String key;
-
- public ResourceBundleKey(ResourceBundleFamily parent, String key) {
- super(parent);
- this.key = key;
- }
-
- /*
- * @see org.eclipse.nls.ui.model.ResourceBundleElement#getParent()
- */
- @Override
- public ResourceBundleFamily getParent() {
- return (ResourceBundleFamily) super.getParent();
- }
-
- public ResourceBundleFamily getFamily() {
- return getParent();
- }
-
- public String getName() {
- return key;
- }
-
- public String getValue(Locale locale) throws CoreException {
- ResourceBundle bundle = getFamily().getBundle(locale);
- if (bundle == null)
- return null;
- return bundle.getString(key);
- }
-
- public boolean hasValue(Locale locale) throws CoreException {
- return getValue(locale) != null;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "ResourceBundleKey {" + key + "}";
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleKeyList.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleKeyList.java
deleted file mode 100644
index a5485495..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleKeyList.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.model;
-
-public class ResourceBundleKeyList {
-
- private final ResourceBundleKey[] keys;
-
- public ResourceBundleKeyList(ResourceBundleKey[] keys) {
- this.keys = keys;
- }
-
- public ResourceBundleKey getKey(int index) {
- return keys[index];
- }
-
- public int getSize() {
- return keys.length;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleModel.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleModel.java
deleted file mode 100644
index 82ebc9b6..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/model/ResourceBundleModel.java
+++ /dev/null
@@ -1,520 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.model;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJarEntryResource;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.pde.core.plugin.IFragmentModel;
-import org.eclipse.pde.core.plugin.IPluginModelBase;
-import org.eclipse.pde.core.plugin.PluginRegistry;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * A <code>ResourceBundleModel</code> is the host for all {@link ResourceBundleFamily} elements.
- */
-public class ResourceBundleModel extends ResourceBundleElement {
-
- private static final String PROPERTIES_SUFFIX = ".properties"; //$NON-NLS-1$
-
- private static final String JAVA_NATURE = "org.eclipse.jdt.core.javanature"; //$NON-NLS-1$
-
- private ArrayList<ResourceBundleFamily> bundleFamilies = new ArrayList<ResourceBundleFamily>();
-
- /**
- * The locales for which all bundles have been loaded.
- */
- // TODO Perhaps we should add reference counting to prevent unexpected unloading of bundles
- private HashSet<Locale> loadedLocales = new HashSet<Locale>();
-
- public ResourceBundleModel(IProgressMonitor monitor) {
- super(null);
- try {
- populateFromWorkspace(monitor);
- } catch (CoreException e) {
- MessagesEditorPlugin.log(e);
- }
- }
-
- /**
- * Returns all resource bundle families contained in this model.
- *
- * @return all resource bundle families contained in this model
- */
- public ResourceBundleFamily[] getFamilies() {
- return bundleFamilies.toArray(new ResourceBundleFamily[bundleFamilies.size()]);
- }
-
- public ResourceBundleFamily[] getFamiliesForPluginId(String pluginId) {
- ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
- for (ResourceBundleFamily family : bundleFamilies) {
- if (family.getPluginId().equals(pluginId)) {
- found.add(family);
- }
- }
- return found.toArray(new ResourceBundleFamily[found.size()]);
- }
-
- public ResourceBundleFamily[] getFamiliesForProjectName(String projectName) {
- ArrayList<ResourceBundleFamily> found = new ArrayList<ResourceBundleFamily>();
- for (ResourceBundleFamily family : bundleFamilies) {
- if (family.getProjectName().equals(projectName)) {
- found.add(family);
- }
- }
- return found.toArray(new ResourceBundleFamily[found.size()]);
- }
-
- public ResourceBundleFamily[] getFamiliesForProject(IProject project) {
- return getFamiliesForProjectName(project.getName());
- }
-
- /**
- * Returns an array of all currently known bundle keys. This always includes
- * the keys from the default bundles and may include some additional keys
- * from bundles that have been loaded sometime and that contain keys not found in
- * a bundle's default bundle. When a bundle is unloaded, these additional keys
- * will not be removed from the model.
- *
- * @return the array of bundles keys
- * @throws CoreException
- */
- public ResourceBundleKey[] getAllKeys() throws CoreException {
- Locale root = new Locale("", "", "");
-
- // Ensure default bundle is loaded and count keys
- int size = 0;
- for (ResourceBundleFamily family : bundleFamilies) {
- ResourceBundle bundle = family.getBundle(root);
- if (bundle != null)
- bundle.load();
- size += family.getKeyCount();
- }
-
- ArrayList<ResourceBundleKey> allKeys = new ArrayList<ResourceBundleKey>(size);
- for (ResourceBundleFamily family : bundleFamilies) {
- ResourceBundleKey[] keys = family.getKeys();
- for (ResourceBundleKey key : keys) {
- allKeys.add(key);
- }
- }
-
- return allKeys.toArray(new ResourceBundleKey[allKeys.size()]);
- }
-
- /**
- * Loads all the bundles for the given locale into memory.
- *
- * @param locale the locale of the bundles to load
- * @throws CoreException
- */
- public void loadBundles(Locale locale) throws CoreException {
- ResourceBundleFamily[] families = getFamilies();
- for (ResourceBundleFamily family : families) {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.load();
- }
- loadedLocales.add(locale);
- }
-
- /**
- * Unloads all the bundles for the given locale from this model. The default
- * bundle cannot be unloaded. Such a request will be ignored.
- *
- * @param locale the locale of the bundles to unload
- */
- public void unloadBundles(Locale locale) {
- if ("".equals(locale.getLanguage()))
- return; // never unload the default bundles
-
- ResourceBundleFamily[] families = getFamilies();
- for (ResourceBundleFamily family : families) {
- ResourceBundle bundle = family.getBundle(locale);
- if (bundle != null)
- bundle.unload();
- }
- loadedLocales.remove(locale);
- }
-
- private void populateFromWorkspace(IProgressMonitor monitor) throws CoreException {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IProject[] projects = root.getProjects();
- for (IProject project : projects) {
- try {
- if (!project.isOpen())
- continue;
-
- IJavaProject javaProject = (IJavaProject) project.getNature(JAVA_NATURE);
-
- // Plugin and fragment projects
- IPluginModelBase pluginModel = PluginRegistry.findModel(project);
- String pluginId = null;
- if (pluginModel != null) {
- // Get plugin id
- pluginId = pluginModel.getBundleDescription().getName(); // OSGi bundle name
- if (pluginId == null) {
- pluginId = pluginModel.getPluginBase().getId(); // non-OSGi plug-in id
- }
- boolean isFragment = pluginModel instanceof IFragmentModel;
- if (isFragment) {
- IFragmentModel fragmentModel = (IFragmentModel) pluginModel;
- pluginId = fragmentModel.getFragment().getPluginId();
- }
-
- // Look for additional 'nl' resources
- IFolder nl = project.getFolder("nl"); //$NON-NLS-1$
- if (isFragment && nl.exists()) {
- IResource[] members = nl.members();
- for (IResource member : members) {
- if (member instanceof IFolder) {
- IFolder langFolder = (IFolder) member;
- String language = langFolder.getName();
-
- // Collect property files
- IFile[] propertyFiles = collectPropertyFiles(langFolder);
- for (IFile file : propertyFiles) {
- // Compute path name
- IPath path = file.getProjectRelativePath();
- String country = ""; //$NON-NLS-1$
- String packageName = null;
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
-
- // Segment 0: 'nl'
- // Segment 1: language code
- // Segment 2: (country code)
- int begin = 2;
- if (segmentCount > 2 && isCountry(path.segment(2))) {
- begin = 3;
- country = path.segment(2);
- }
-
- for (int i = begin; i < segmentCount - 1; i++) {
- if (i > begin)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
-
- String baseName = getBaseName(file.getName());
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
- }
- }
- }
- }
-
- // Collect property files
- if (isFragment || javaProject == null) {
- IFile[] propertyFiles = collectPropertyFiles(project);
- for (IFile file : propertyFiles) {
- IPath path = file.getProjectRelativePath();
- int segmentCount = path.segmentCount();
-
- if (segmentCount > 0 && path.segment(0).equals("nl")) //$NON-NLS-1$
- continue; // 'nl' resource have been processed above
-
- // Guess package name
- String packageName = null;
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < segmentCount - 1; i++) {
- if (i > 0)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
-
- String baseName = getBaseName(file.getName());
- String language = getLanguage(file.getName());
- String country = getCountry(file.getName());
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
- }
- }
-
- }
-
- // Look for resource bundles in Java packages (output folders, e.g. 'bin', will be ignored)
- if (javaProject != null) {
- IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
- for (IClasspathEntry entry : classpathEntries) {
- if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- IPath path = entry.getPath();
- IFolder folder = workspace.getRoot().getFolder(path);
- IFile[] propertyFiles = collectPropertyFiles(folder);
-
- for (IFile file : propertyFiles) {
- String name = file.getName();
- String baseName = getBaseName(name);
- String language = getLanguage(name);
- String country = getCountry(name);
- IPackageFragment pf = javaProject.findPackageFragment(file.getParent()
- .getFullPath());
- String packageName = pf.getElementName();
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
-
- addBundle(family, getLocale(language, country), file);
- }
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- IPackageFragmentRoot[] findPackageFragmentRoots = javaProject.findPackageFragmentRoots(entry);
- for (IPackageFragmentRoot packageFragmentRoot : findPackageFragmentRoots) {
- IJavaElement[] children = packageFragmentRoot.getChildren();
- for (IJavaElement child : children) {
- IPackageFragment pf = (IPackageFragment) child;
- Object[] nonJavaResources = pf.getNonJavaResources();
-
- for (Object resource : nonJavaResources) {
- if (resource instanceof IJarEntryResource) {
- IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
- String name = jarEntryResource.getName();
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- String baseName = getBaseName(name);
- String language = getLanguage(name);
- String country = getCountry(name);
- String packageName = pf.getElementName();
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
-
- addBundle(
- family,
- getLocale(language, country),
- jarEntryResource);
- }
- }
- }
- }
- }
- }
- }
-
- // Collect non-Java resources
- Object[] nonJavaResources = javaProject.getNonJavaResources();
- ArrayList<IFile> files = new ArrayList<IFile>();
- for (Object resource : nonJavaResources) {
- if (resource instanceof IContainer) {
- IContainer container = (IContainer) resource;
- collectPropertyFiles(container, files);
- } else if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- String name = file.getName();
- if (isIgnoredFilename(name))
- continue;
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- files.add(file);
- }
- }
- }
- for (IFile file : files) {
-
- // Convert path to package name format
- IPath path = file.getProjectRelativePath();
- String packageName = null;
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < segmentCount - 1; i++) {
- if (i > 0)
- builder.append('.');
- builder.append(path.segment(i));
- }
- packageName = builder.toString();
- }
-
- String baseName = getBaseName(file.getName());
- String language = getLanguage(file.getName());
- String country = getCountry(file.getName());
-
- ResourceBundleFamily family = getOrCreateFamily(
- project.getName(),
- pluginId,
- packageName,
- baseName);
- addBundle(family, getLocale(language, country), file);
- }
-
- }
- } catch (Exception e) {
- MessagesEditorPlugin.log(e);
- }
- }
- }
-
- private IFile[] collectPropertyFiles(IContainer container) throws CoreException {
- ArrayList<IFile> files = new ArrayList<IFile>();
- collectPropertyFiles(container, files);
- return files.toArray(new IFile[files.size()]);
- }
-
- private void collectPropertyFiles(IContainer container, ArrayList<IFile> files) throws CoreException {
- IResource[] members = container.members();
- for (IResource resource : members) {
- if (!resource.exists())
- continue;
- if (resource instanceof IContainer) {
- IContainer childContainer = (IContainer) resource;
- collectPropertyFiles(childContainer, files);
- } else if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- String name = file.getName();
- if (file.getProjectRelativePath().segmentCount() == 0 && isIgnoredFilename(name))
- continue;
- if (name.endsWith(PROPERTIES_SUFFIX)) {
- files.add(file);
- }
- }
- }
- }
-
- private boolean isCountry(String name) {
- if (name == null || name.length() != 2)
- return false;
- char c1 = name.charAt(0);
- char c2 = name.charAt(1);
- return 'A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z';
- }
-
- private Locale getLocale(String language, String country) {
- if (language == null)
- language = ""; //$NON-NLS-1$
- if (country == null)
- country = ""; //$NON-NLS-1$
- return new Locale(language, country);
- }
-
- private void addBundle(ResourceBundleFamily family, Locale locale, Object resource) throws CoreException {
- ResourceBundle bundle = new ResourceBundle(family, resource, locale);
- if ("".equals(locale.getLanguage()))
- bundle.load();
- family.addBundle(bundle);
- }
-
- private String getBaseName(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(0, len - 6);
- } else {
- return name.substring(0, len - 3);
- }
- }
- return name;
- }
-
- private String getLanguage(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(len - 5, len - 3);
- } else {
- return name.substring(len - 2);
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- private String getCountry(String filename) {
- if (!filename.endsWith(PROPERTIES_SUFFIX))
- throw new IllegalArgumentException();
- String name = filename.substring(0, filename.length() - 11);
- int len = name.length();
- if (len > 3 && name.charAt(len - 3) == '_') {
- if (len > 6 && name.charAt(len - 6) == '_') {
- return name.substring(len - 2);
- } else {
- return ""; //$NON-NLS-1$
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- private ResourceBundleFamily getOrCreateFamily(String projectName, String pluginId, String packageName,
- String baseName) {
-
- // Ignore project name
- if (pluginId != null)
- projectName = null;
-
- for (ResourceBundleFamily family : bundleFamilies) {
- if (areEqual(family.getProjectName(), projectName)
- && areEqual(family.getPluginId(), pluginId)
- && areEqual(family.getPackageName(), packageName)
- && areEqual(family.getBaseName(), baseName)) {
- return family;
- }
- }
- ResourceBundleFamily family = new ResourceBundleFamily(
- this,
- projectName,
- pluginId,
- packageName,
- baseName);
- bundleFamilies.add(family);
- return family;
- }
-
- private boolean isIgnoredFilename(String filename) {
- return filename.equals("build.properties") || filename.equals("logging.properties"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private boolean areEqual(String str1, String str2) {
- return str1 == null && str2 == null || str1 != null && str1.equals(str2);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/CharArraySource.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/CharArraySource.java
deleted file mode 100644
index e769633d..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/CharArraySource.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.parser;
-
-import java.io.IOException;
-import java.io.Reader;
-
-/**
- * A scanner source that is backed by a character array.
- */
-public class CharArraySource implements IScannerSource {
-
- private char[] cbuf;
-
- /** The end position of this source. */
- private int end;
-
- private int[] lineEnds = new int[2048];
-
- /**
- * The current position at which the next character will be read.
- * The value <code>Integer.MAX_VALUE</code> indicates, that the end
- * of the source has been reached (the EOF character has been returned).
- */
- int currentPosition = 0;
-
- /** The number of the current line. (Line numbers are one-based.) */
- int currentLineNumber = 1;
-
- protected CharArraySource() {
- }
-
- /**
- * Constructs a scanner source from a char array.
- */
- public CharArraySource(char[] cbuf) {
- this.cbuf = cbuf;
- this.end = cbuf.length;
- }
-
- /**
- * Resets this source on the given array.
- *
- * @param cbuf the array to read from
- * @param begin where to begin reading
- * @param end where to end reading
- */
- protected void reset(char[] cbuf, int begin, int end) {
- if (cbuf == null) {
- this.cbuf = null;
- this.end = -1;
- currentPosition = -1;
- currentLineNumber = -1;
- lineEnds = null;
- } else {
- this.cbuf = cbuf;
- this.end = end;
- currentPosition = begin;
- currentLineNumber = 1;
- lineEnds = new int[2];
- }
- }
-
- /*
- * @see scanner.IScannerSource#charAt(int)
- */
- public int charAt(int index) {
- if (index < end) {
- return cbuf[index];
- } else {
- return -1;
- }
- }
-
- /*
- * @see scanner.IScannerSource#currentChar()
- */
- public int lookahead() {
- if (currentPosition < end) {
- return cbuf[currentPosition];
- } else {
- return -1;
- }
- }
-
- /*
- * @see scanner.IScannerSource#lookahead(int)
- */
- public int lookahead(int n) {
- int pos = currentPosition + n - 1;
- if (pos < end) {
- return cbuf[pos];
- } else {
- return -1;
- }
- }
-
- /*
- * @see core.IScannerSource#readChar()
- */
- public int readChar() {
- if (currentPosition < end) {
- return cbuf[currentPosition++];
- } else {
- currentPosition++;
- return -1;
- }
- }
-
- /*
- * @see core.IScannerSource#readChar(int)
- */
- public int readChar(int expected) {
- int c = readChar();
- if (c == expected) {
- return c;
- } else {
- String message = "Expected char '"
- + (char) expected
- + "' (0x"
- + hexDigit((expected >> 4) & 0xf)
- + hexDigit(expected & 0xf)
- + ") but got '" + (char) c + "' (0x" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + hexDigit((c >> 4) & 0xf)
- + hexDigit(c & 0xf)
- + ")"; //$NON-NLS-1$
- throw new LexicalErrorException(this, message);
- }
- }
-
- /*
- * @see scanner.IScannerSource#unreadChar()
- */
- public void unreadChar() {
- currentPosition--;
- }
-
- /*
- * @see core.IScannerSource#hasMoreChars()
- */
- public boolean hasMoreChars() {
- return currentPosition < end;
- }
-
- /*
- * @see scanner.IScannerSource#getPosition()
- */
- public int getPosition() {
- if (currentPosition < end)
- return currentPosition;
- else
- return end;
- }
-
- /*
- * @see core.IScannerSource#isAtLineBegin()
- */
- public boolean isAtLineBegin() {
- return currentPosition == lineEnds[currentLineNumber - 1];
- }
-
- /*
- * @see scanner.IScannerSource#getCurrentLineNumber()
- */
- public int getCurrentLineNumber() {
- return currentLineNumber;
- }
-
- /*
- * @see scanner.IScannerSource#getCurrentColumnNumber()
- */
- public int getCurrentColumnNumber() {
- return currentPosition - lineEnds[currentLineNumber - 1] + 1;
- }
-
- /*
- * @see scanner.IScannerSource#getLineEnds()
- */
- public int[] getLineEnds() {
- return lineEnds;
- }
- /*
- * @see scanner.IScannerSource#pushLineSeparator()
- */
- public void pushLineSeparator() {
- if (currentLineNumber >= lineEnds.length) {
- int[] newLineEnds = new int[lineEnds.length * 2];
- System.arraycopy(lineEnds, 0, newLineEnds, 0, lineEnds.length);
- lineEnds = newLineEnds;
- }
- lineEnds[currentLineNumber++] = currentPosition;
- }
-
- /*
- * @see scanner.IScannerSource#length()
- */
- public int length() {
- return cbuf.length;
- }
-
- /**
- * Returns a string that contains the characters of the source specified
- * by the range <code>beginIndex</code> and the current position as the
- * end index.
- *
- * @param beginIndex
- * @return the String
- */
- public String toString(int beginIndex) {
- return toString(beginIndex, currentPosition);
- }
-
- /*
- * @see scanner.IScannerSource#toString(int, int)
- */
- public String toString(int beginIndex, int endIndex) {
- return new String(cbuf, beginIndex, endIndex - beginIndex);
- }
-
- /**
- * Returns the original character array that backs the scanner source.
- * All subsequent changes to the returned array will affect the scanner
- * source.
- *
- * @return the array
- */
- public char[] getArray() {
- return cbuf;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "Line=" + getCurrentLineNumber() + ", Column=" + getCurrentColumnNumber(); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private static char hexDigit(int digit) {
- return "0123456789abcdef".charAt(digit); //$NON-NLS-1$
- }
-
- public static CharArraySource createFrom(Reader reader) throws IOException {
- StringBuffer buffer = new StringBuffer();
- int BUF_SIZE = 4096;
- char[] array = new char[BUF_SIZE];
- for (int read = 0; (read = reader.read(array, 0, BUF_SIZE)) > 0;) {
- buffer.append(array, 0, read);
- }
- char[] result = new char[buffer.length()];
- buffer.getChars(0, buffer.length(), result, 0);
- return new CharArraySource(result);
- }
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/IScannerSource.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/IScannerSource.java
deleted file mode 100644
index a7c96482..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/IScannerSource.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.parser;
-
-public interface IScannerSource {
-
- /**
- * Returns the character at the specified position.
- *
- * @param position the index of the character to be returned
- * @return the character at the specified position (0-based)
- */
- public int charAt(int position);
-
- /**
- * Returns the character that will be returned by the next call
- * to <code>readChar()</code>. Calling this method is equal to the
- * following calls:
- * <pre>
- * lookahead(1)
- * charAt(getPosition())
- * </pre>
- *
- * @return the character at the current position
- */
- public int lookahead();
-
- /**
- * Returns the character at the given lookahead position. Calling this
- * method is equal to the following call:
- * <pre>
- * charAt(currentPosition + n - 1)
- * </pre>
- *
- * @param n the number of characters to look ahead
- *
- * @return the character
- */
- public int lookahead(int n);
-
- /**
- * Reads a single character.
- *
- * @return the character read, or -1 if the end of the source
- * has been reached
- */
- public int readChar();
-
- /**
- * Reads a single character.
- *
- * @param expected the expected character; if the character read does not
- * match this character, a <code>LexcialErrorException</code> will be thrown
- * @return the character read, or -1 if the end of the source
- * has been reached
- */
- public int readChar(int expected);
-
- /**
- * Unreads a single character. The current position will be decreased
- * by 1. If -1 has been read multiple times, it will be unread multiple
- * times.
- */
- public void unreadChar();
-
- /**
- * Retruns the current position of the source.
- *
- * @return the position (0-based)
- */
- public int getPosition();
-
- /**
- * Returns <code>true</code> if the current position is at the beginning of a line.
- *
- * @return <code>true</code> if the current position is at the beginning of a line
- */
- public boolean isAtLineBegin();
-
- /**
- * Returns the current line number.
- *
- * @return the current line number (1-based)
- */
- public int getCurrentLineNumber();
-
- /**
- * Returns the current column number.
- *
- * @return the current column number (1-based)
- */
- public int getCurrentColumnNumber();
-
- /**
- * Records the next line end position. This method has to be called
- * just after the line separator has been read.
- *
- * @see IScannerSource#getLineEnds()
- */
- public void pushLineSeparator();
-
- /**
- * Returns an array of the line end positions recorded so far. Each value points
- * to first character following the line end (and is thus an exclusive index
- * to the line end). By definition the value <code>lineEnds[0]</code> is 0.
- * <code>lineEnds[1]</code> contains the line end position of the first line.
- *
- * @return an array containing the line end positions
- *
- * @see IScannerSource#pushLineSeparator()
- */
- public int[] getLineEnds();
-
- /**
- * Returns <code>true</code> if more characters are available.
- *
- * @return <code>true</code> if more characters are available
- */
- public boolean hasMoreChars();
-
- /**
- * Returns a String that contains the characters in the specified range
- * of the source.
- *
- * @param beginIndex the beginning index, inclusive
- * @param endIndex the ending index, exclusive
- * @return the newly created <code>String</code>
- */
- public String toString(int beginIndex, int endIndex);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/LexicalErrorException.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/LexicalErrorException.java
deleted file mode 100644
index b554b7fa..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/LexicalErrorException.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.parser;
-
-/**
- * Exception thrown by a scanner when encountering lexical errors.
- */
-public class LexicalErrorException extends RuntimeException {
-
- private int lineNumber;
- private int columnNumber;
-
- /**
- * Creates a <code>LexicalErrorException</code> without a detailed message.
- *
- * @param source the scanner source the error occured on
- */
- public LexicalErrorException(IScannerSource source) {
- this(source.getCurrentLineNumber(), source.getCurrentColumnNumber(), null);
- }
-
- /**
- * @param source the scanner source the error occured on
- * @param message the error message
- */
- public LexicalErrorException(IScannerSource source, String message) {
- this(source.getCurrentLineNumber(), source.getCurrentColumnNumber(), message);
- }
-
- /**
- * @param line the number of the line where the error occured
- * @param column the numer of the column where the error occured
- * @param message the error message
- */
- public LexicalErrorException(int line, int column, String message) {
- super("Lexical error (" + line + ", " + column + (message == null ? ")" : "): " + message)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- this.lineNumber = line;
- this.columnNumber = column;
- }
-
- /**
- * Returns the line number where the error occured.
- *
- * @return the line number where the error occured
- */
- public int getLineNumber() {
- return lineNumber;
- }
-
- /**
- * Returns the column number where the error occured.
- *
- * @return the column number where the error occured
- */
- public int getColumnNumber() {
- return columnNumber;
- }
-
- public static LexicalErrorException unexpectedCharacter(IScannerSource source, int c) {
- return new LexicalErrorException(source, "Unexpected character: '" //$NON-NLS-1$
- + (char) c
- + "' (0x" //$NON-NLS-1$
- + hexDigit((c >> 4) & 0xf)
- + hexDigit(c & 0xf)
- + ")"); //$NON-NLS-1$
- }
-
- private static char hexDigit(int digit) {
- return "0123456789abcdef".charAt(digit); //$NON-NLS-1$
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/LocaleUtil.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/LocaleUtil.java
deleted file mode 100644
index a6dd6013..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/LocaleUtil.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.parser;
-
-import java.util.Locale;
-import java.util.StringTokenizer;
-
-public class LocaleUtil {
-
- private LocaleUtil() {
- }
-
- public static Locale parseLocale(String name) throws IllegalArgumentException {
- String language = ""; //$NON-NLS-1$
- String country = ""; //$NON-NLS-1$
- String variant = ""; //$NON-NLS-1$
-
- StringTokenizer tokenizer = new StringTokenizer(name, "_"); //$NON-NLS-1$
- if (tokenizer.hasMoreTokens())
- language = tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- country = tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- variant = tokenizer.nextToken();
-
- if (!language.equals("") && language.length() != 2) //$NON-NLS-1$
- throw new IllegalArgumentException();
- if (!country.equals("") && country.length() != 2) //$NON-NLS-1$
- throw new IllegalArgumentException();
-
- if (!language.equals("")) { //$NON-NLS-1$
- char l1 = language.charAt(0);
- char l2 = language.charAt(1);
- if (!('a' <= l1 && l1 <= 'z' && 'a' <= l2 && l2 <= 'z'))
- throw new IllegalArgumentException();
- }
-
- if (!country.equals("")) { //$NON-NLS-1$
- char c1 = country.charAt(0);
- char c2 = country.charAt(1);
- if (!('A' <= c1 && c1 <= 'Z' && 'A' <= c2 && c2 <= 'Z'))
- throw new IllegalArgumentException();
- }
-
- return new Locale(language, country, variant);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/RawBundle.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/RawBundle.java
deleted file mode 100644
index 9537e0b9..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/pde/nls/internal/ui/parser/RawBundle.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Stefan M�cke 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:
- * Stefan M�cke - initial API and implementation
- *******************************************************************************/
-package org.eclipselabs.pde.nls.internal.ui.parser;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.util.ArrayList;
-
-/**
- * A class used to manipulate resource bundle files.
- */
-public class RawBundle {
-
- public static abstract class RawLine {
- String rawData;
- public RawLine(String rawData) {
- this.rawData = rawData;
- }
- public String getRawData() {
- return rawData;
- }
- }
- public static class CommentLine extends RawLine {
- public CommentLine(String line) {
- super(line);
- }
- }
- public static class EmptyLine extends RawLine {
- public EmptyLine(String line) {
- super(line);
- }
- }
- public static class EntryLine extends RawLine {
- String key;
- public EntryLine(String key, String lineData) {
- super(lineData);
- this.key = key;
- }
- }
-
- /**
- * The logical lines of the resource bundle.
- */
- private ArrayList<RawLine> lines = new ArrayList<RawLine>();
-
- public RawBundle() {
- }
-
- public EntryLine getEntryLine(String key) {
- for (RawLine line : lines) {
- if (line instanceof EntryLine) {
- EntryLine entryLine = (EntryLine) line;
- if (entryLine.key.equals(key))
- return entryLine;
- }
- }
- return null;
- }
-
- public void put(String key, String value) {
-
- // Find insertion position
- int size = lines.size();
- int pos = -1;
- for (int i = 0; i < size; i++) {
- RawLine line = lines.get(i);
- if (line instanceof EntryLine) {
- EntryLine entryLine = (EntryLine) line;
- int compare = key.compareToIgnoreCase(entryLine.key);
- if (compare < 0) {
- if (pos == -1) {
- pos = i; // possible insertion position
- }
- } else if (compare > 0) {
- continue;
- } else if (key.equals(entryLine.key)) {
- entryLine.rawData = key + "=" + escape(value) + "\r\n";
- return;
- } else {
- pos = i; // possible insertion position
- }
- }
- }
- if (pos == -1)
- pos = lines.size();
-
- // Append new entry
- lines.add(pos, new EntryLine(key, key + "=" + escape(value) + "\r\n"));
- }
-
- private String escape(String str) {
- StringBuilder builder = new StringBuilder();
- int len = str.length();
- for (int i = 0; i < len; i++) {
- char c = str.charAt(i);
- switch (c) {
- case ' ' :
- if (i == 0) {
- builder.append("\\ ");
- } else {
- builder.append(c);
- }
- break;
- case '\t' :
- builder.append("\\t");
- break;
- case '=' :
- case ':' :
- case '#' :
- case '!' :
- case '\\' :
- builder.append('\\').append(c);
- break;
- default :
- if (31 <= c && c <= 255) {
- builder.append(c);
- } else {
- builder.append("\\u");
- builder.append(hexDigit((c >> 12) & 0x0f));
- builder.append(hexDigit((c >> 8) & 0x0f));
- builder.append(hexDigit((c >> 4) & 0x0f));
- builder.append(hexDigit(c & 0x0f));
- }
- break;
- }
- }
- return builder.toString();
- }
-
- private static char hexDigit(int digit) {
- return "0123456789ABCDEF".charAt(digit); //$NON-NLS-1$
- }
-
- public void writeTo(OutputStream out) throws IOException {
- OutputStreamWriter writer = new OutputStreamWriter(out, "ISO-8859-1");
- writeTo(writer);
- }
-
- public void writeTo(Writer writer) throws IOException {
- for (RawLine line : lines) {
- writer.write(line.rawData);
- }
- }
-
- public static RawBundle createFrom(InputStream in) throws IOException {
- IScannerSource source = CharArraySource.createFrom(new InputStreamReader(in, "ISO-8859-1"));
- return RawBundle.createFrom(source);
- }
-
- public static RawBundle createFrom(Reader reader) throws IOException {
- IScannerSource source = CharArraySource.createFrom(reader);
- return RawBundle.createFrom(source);
- }
-
- public static RawBundle createFrom(IScannerSource source) throws IOException {
- RawBundle rawBundle = new RawBundle();
- StringBuilder builder = new StringBuilder();
-
- while (source.hasMoreChars()) {
- int begin = source.getPosition();
- skipAllOf(" \t\u000c", source);
-
- // Comment line
- if (source.lookahead() == '#' || source.lookahead() == '!') {
- skipToOneOf("\r\n", false, source);
- consumeLineSeparator(source);
- int end = source.getPosition();
- String line = source.toString(begin, end);
- rawBundle.lines.add(new CommentLine(line));
- continue;
- }
-
- // Empty line
- if (isAtLineEnd(source)) {
- consumeLineSeparator(source);
- int end = source.getPosition();
- String line = source.toString(begin, end);
- rawBundle.lines.add(new EmptyLine(line));
- continue;
- }
-
- // Entry line
- {
- // Key
- builder.setLength(0);
- loop : while (source.hasMoreChars()) {
- char c = (char) source.readChar();
- switch (c) {
- case ' ' :
- case '\t' :
- case '\u000c' :
- case '=' :
- case '\r' :
- case '\n' :
- break loop;
- case '\\' :
- source.unreadChar();
- builder.append(readEscapedChar(source));
- break;
- default :
- builder.append(c);
- break;
- }
- }
- String key = builder.toString();
-
- // Value
- int end = 0;
- loop : while (source.hasMoreChars()) {
- char c = (char) source.readChar();
- switch (c) {
- case '\r' :
- case '\n' :
- consumeLineSeparator(source);
- end = source.getPosition();
- break loop;
- case '\\' :
- if (isAtLineEnd(source)) {
- consumeLineSeparator(source);
- } else {
- source.unreadChar();
- readEscapedChar(source);
- }
- break;
- default :
- break;
- }
- }
- if (end == 0)
- end = source.getPosition();
-
- String lineData = source.toString(begin, end);
- EntryLine entryLine = new EntryLine(key, lineData);
- rawBundle.lines.add(entryLine);
- }
- }
-
- return rawBundle;
- }
-
- private static char readEscapedChar(IScannerSource source) {
- source.readChar('\\');
- char c = (char) source.readChar();
- switch (c) {
- case ' ' :
- case '=' :
- case ':' :
- case '#' :
- case '!' :
- case '\\' :
- return c;
- case 't' :
- return '\t';
- case 'n' :
- return '\n';
- case 'u' :
- int d1 = Character.digit(source.readChar(), 16);
- int d2 = Character.digit(source.readChar(), 16);
- int d3 = Character.digit(source.readChar(), 16);
- int d4 = Character.digit(source.readChar(), 16);
- if (d1 == -1 || d2 == -1 || d3 == -1 || d4 == -1)
- throw new LexicalErrorException(source, "Illegal escape sequence");
- return (char) (d1 << 12 | d2 << 8 | d3 << 4 | d4);
- default :
- throw new LexicalErrorException(source, "Unknown escape sequence");
- }
- }
-
- private static boolean isAtLineEnd(IScannerSource source) {
- return source.lookahead() == '\r' || source.lookahead() == '\n';
- }
-
- private static void consumeLineSeparator(IScannerSource source) {
- if (source.lookahead() == '\n') {
- source.readChar();
- source.pushLineSeparator();
- } else if (source.lookahead() == '\r') {
- source.readChar();
- if (source.lookahead() == '\n') {
- source.readChar();
- }
- source.pushLineSeparator();
- }
- }
-
- private static void skipToOneOf(String delimiters, boolean readDelimiter, IScannerSource source) {
- loop : while (source.hasMoreChars()) {
- int c = source.readChar();
- if (delimiters.indexOf(c) != -1) {
- if (!readDelimiter) {
- source.unreadChar();
- }
- break loop;
- }
- if (c == '\r') {
- source.readChar('\n');
- source.pushLineSeparator();
- }
- }
- }
-
- private static void skipAllOf(String string, IScannerSource source) {
- while (source.hasMoreChars() && string.indexOf(source.lookahead()) != -1) {
- source.readChar();
- }
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/IMessagesEditorChangeListener.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/IMessagesEditorChangeListener.java
deleted file mode 100644
index 6ea7e5d2..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/IMessagesEditorChangeListener.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public interface IMessagesEditorChangeListener {
-
- public static int SHOW_ALL = 0;
- public static int SHOW_ONLY_MISSING_AND_UNUSED = 1;
- public static int SHOW_ONLY_MISSING = 2;
- public static int SHOW_ONLY_UNUSED = 3;
-
- void keyTreeVisibleChanged(boolean visible);
-
- void showOnlyUnusedAndMissingChanged(int showFlag);
-
- void selectedKeyChanged(String oldKey, String newKey);
-
- void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel);
-
- void editorDisposed();
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditor.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditor.java
deleted file mode 100644
index 15fe8b8d..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditor.java
+++ /dev/null
@@ -1,435 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor;
-
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.ide.IGotoMarker;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.builder.ToggleNatureAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.bundle.MessagesBundleGroupFactory;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.I18NPage;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.EclipsePropertiesEditorResource;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.views.MessagesBundleGroupOutline;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-/**
- * Multi-page editor for editing resource bundles.
- */
-public class MessagesEditor extends MultiPageEditorPart
- implements IGotoMarker {
-
- /** Editor ID, as defined in plugin.xml. */
- public static final String EDITOR_ID =
- "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$
-
- private String selectedKey;
- private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>(2);
-
- /** MessagesBundle group. */
- private MessagesBundleGroup messagesBundleGroup;
-
- /** Page with key tree and text fields for all locales. */
- private I18NPage i18nPage;
- private final List<Locale> localesIndex = new ArrayList<Locale>();
- private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>();
-
- private MessagesBundleGroupOutline outline;
-
- private MessagesEditorMarkers markers;
-
-
- private AbstractKeyTreeModel keyTreeModel;
-
- /**
- * Creates a multi-page editor example.
- */
- public MessagesEditor() {
- super();
- outline = new MessagesBundleGroupOutline(this);
- }
-
- public MessagesEditorMarkers getMarkers() {
- return markers;
- }
-
- private IPropertyChangeListener preferenceListener;
-
- /**
- * The <code>MultiPageEditorExample</code> implementation of this method
- * checks that the input is an instance of <code>IFileEditorInput</code>.
- */
- public void init(IEditorSite site, IEditorInput editorInput)
- throws PartInitException {
-
- if (editorInput instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) editorInput).getFile();
- if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) {
- IProject p = file.getProject();
- if (p != null && p.isAccessible()) {
- ToggleNatureAction.addOrRemoveNatureOnProject(p, true, true);
- }
- }
- try {
- messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup(site, file);
- } catch (MessageException e) {
- throw new PartInitException(
- "Cannot create bundle group.", e); //$NON-NLS-1$
- }
- markers = new MessagesEditorMarkers(messagesBundleGroup);
- setPartName(messagesBundleGroup.getName());
- setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
- closeIfAreadyOpen(site, file);
- super.init(site, editorInput);
- //TODO figure out model to use based on preferences
- keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup);
-// markerManager = new RBEMarkerManager(this);
- } else {
- throw new PartInitException(
- "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$
- }
- }
-
-// public RBEMarkerManager getMarkerManager() {
-// return markerManager;
-// }
-
- /**
- * Creates the pages of the multi-page editor.
- */
- protected void createPages() {
- // Create I18N page
- i18nPage = new I18NPage(
- getContainer(), SWT.NONE, this);
- int index = addPage(i18nPage);
- setPageText(index, MessagesEditorPlugin.getString(
- "editor.properties")); //$NON-NLS-1$
- setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE));
-
- // Create text editor pages for each locales
- try {
- Locale[] locales = messagesBundleGroup.getLocales();
- //first: sort the locales.
- UIUtils.sortLocales(locales);
- //second: filter+sort them according to the filter preferences.
- locales = UIUtils.filterLocales(locales);
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup.getMessagesBundle(locale);
- IMessagesResource resource = messagesBundle.getResource();
- TextEditor textEditor = (TextEditor) resource.getSource();
- index = addPage(textEditor, textEditor.getEditorInput());
- setPageText(index, UIUtils.getDisplayName(
- messagesBundle.getLocale()));
- setPageImage(index,
- UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE));
- localesIndex.add(locale);
- textEditorsIndex.add(textEditor);
- }
- } catch (PartInitException e) {
- ErrorDialog.openError(getSite().getShell(),
- "Error creating text editor page.", //$NON-NLS-1$
- null, e.getStatus());
- }
- }
-
- /**
- * Called when the editor's pages need to be reloaded.
- * For example when the filters of locale is changed.
- * <p>
- * Currently this only reloads the index page.
- * TODO: remove and add the new locales? it actually looks quite hard to do.
- * </p>
- */
- public void reloadDisplayedContents() {
- super.removePage(0);
- int currentlyActivePage = super.getActivePage();
- i18nPage.dispose();
- i18nPage = new I18NPage(
- getContainer(), SWT.NONE, this);
- super.addPage(0, i18nPage);
- if (currentlyActivePage == 0) {
- super.setActivePage(currentlyActivePage);
- }
- }
-
- /**
- * Saves the multi-page editor's document.
- */
- public void doSave(IProgressMonitor monitor) {
- for (ITextEditor textEditor : textEditorsIndex) {
- textEditor.doSave(monitor);
- }
-
- try { // [alst] remove in near future
- Thread.sleep(200);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- RBManager.getInstance(messagesBundleGroup.getProjectName()).fireEditorSaved();
- }
-
- /**
- * @see org.eclipse.ui.ISaveablePart#doSaveAs()
- */
- public void doSaveAs() {
- // Save As not allowed.
- }
-
- /**
- * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
- */
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- /**
- * Change current page based on locale. If there is no editors associated
- * with current locale, do nothing.
- * @param locale locale used to identify the page to change to
- */
- public void setActivePage(Locale locale) {
- int index = localesIndex.indexOf(locale);
- if (index > -1) {
- setActivePage(index + 1);
- }
- }
-
- /**
- * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(
- * org.eclipse.core.resources.IMarker)
- */
- public void gotoMarker(IMarker marker) {
-// String key = marker.getAttribute(RBEMarker.KEY, "");
-// if (key != null && key.length() > 0) {
-// setActivePage(0);
-// setSelectedKey(key);
-// getI18NPage().selectLocale(BabelUtils.parseLocale(
-// marker.getAttribute(RBEMarker.LOCALE, "")));
-// } else {
- IResource resource = marker.getResource();
- Locale[] locales = messagesBundleGroup.getLocales();
- for (int i = 0; i < locales.length; i++) {
- IMessagesResource messagesResource =
- ((MessagesBundle) messagesBundleGroup.getMessagesBundle(locales[i])).getResource();
- if (messagesResource instanceof EclipsePropertiesEditorResource) {
- EclipsePropertiesEditorResource propFile =
- (EclipsePropertiesEditorResource) messagesResource;
- if (resource.equals(propFile.getResource())) {
- //ok we got the locale.
- //try to open the master i18n page and select the corresponding key.
- try {
- String key = (String) marker.getAttribute(IMarker.LOCATION);
- if (key != null && key.length() > 0) {
- getI18NPage().selectLocale(locales[i]);
- setActivePage(0);
- setSelectedKey(key);
- return;
- }
- } catch (Exception e) {
- e.printStackTrace();//something better.s
- }
- //it did not work... fall back to the text editor.
- setActivePage(locales[i]);
- IDE.gotoMarker(
- (IEditorPart) propFile.getSource(), marker);
- break;
- }
- }
- }
-// }
- }
-
- /**
- * Calculates the contents of page GUI page when it is activated.
- */
- protected void pageChange(int newPageIndex) {
- super.pageChange(newPageIndex);
-// if (newPageIndex == 0) {
-// resourceMediator.reloadProperties();
-// i18nPage.refreshTextBoxes();
-// }
- }
-
-
- /**
- * Is the given file a member of this resource bundle.
- * @param file file to test
- * @return <code>true</code> if file is part of bundle
- */
- public boolean isBundleMember(IFile file) {
-// return resourceMediator.isResource(file);
- return false;
- }
-
- private void closeIfAreadyOpen(IEditorSite site, IFile file) {
- IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages();
- for (int i = 0; i < pages.length; i++) {
- IWorkbenchPage page = pages[i];
- IEditorReference[] editors = page.getEditorReferences();
- for (int j = 0; j < editors.length; j++) {
- IEditorPart editor = editors[j].getEditor(false);
- if (editor instanceof MessagesEditor) {
- MessagesEditor rbe = (MessagesEditor) editor;
- if (rbe.isBundleMember(file)) {
- page.closeEditor(editor, true);
- }
- }
- }
- }
- }
-
-
-
- /**
- * @see org.eclipse.ui.IWorkbenchPart#dispose()
- */
- public void dispose() {
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.editorDisposed();
- }
- i18nPage.dispose();
- for (ITextEditor textEditor : textEditorsIndex) {
- textEditor.dispose();
- }
- }
-
-
- /**
- * @return Returns the selectedKey.
- */
- public String getSelectedKey() {
- return selectedKey;
- }
- /**
- * @param selectedKey The selectedKey to set.
- */
- public void setSelectedKey(String activeKey) {
- if ((selectedKey == null && activeKey != null)
- || (selectedKey != null && activeKey == null)
- || (selectedKey != null && !selectedKey.equals(activeKey))) {
- String oldKey = this.selectedKey;
- this.selectedKey = activeKey;
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.selectedKeyChanged(oldKey, activeKey);
- }
- }
- }
-
- public void addChangeListener(IMessagesEditorChangeListener listener) {
- changeListeners.add(0, listener);
- }
-
- public void removeChangeListener(IMessagesEditorChangeListener listener) {
- changeListeners.remove(listener);
- }
-
- public Collection<IMessagesEditorChangeListener> getChangeListeners() {
- return changeListeners;
- }
-
- /**
- * @return Returns the messagesBundleGroup.
- */
- public MessagesBundleGroup getBundleGroup() {
- return messagesBundleGroup;
- }
-
- /**
- * @return Returns the keyTreeModel.
- */
- public AbstractKeyTreeModel getKeyTreeModel() {
- return keyTreeModel;
- }
-
- /**
- * @param keyTreeModel The keyTreeModel to set.
- */
- public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) {
- if ((this.keyTreeModel == null && newKeyTreeModel != null)
- || (keyTreeModel != null && newKeyTreeModel == null)
- || (!keyTreeModel.equals(newKeyTreeModel))) {
- AbstractKeyTreeModel oldModel = this.keyTreeModel;
- this.keyTreeModel = newKeyTreeModel;
- for (IMessagesEditorChangeListener listener : changeListeners) {
- listener.keyTreeModelChanged(oldModel, newKeyTreeModel);
- }
- }
- }
-
- public I18NPage getI18NPage() {
- return i18nPage;
- }
-
- /** one of the SHOW_* constants defined in the {@link IMessagesEditorChangeListener} */
- private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL;
- /**
- * @return true when only unused and missing keys should be displayed. flase by default.
- */
- public int isShowOnlyUnusedAndMissingKeys() {
- return showOnlyMissingAndUnusedKeys;
- }
-
- public void setShowOnlyUnusedMissingKeys(int showFlag) {
- showOnlyMissingAndUnusedKeys = showFlag;
- for (IMessagesEditorChangeListener listener : getChangeListeners()) {
- listener.showOnlyUnusedAndMissingChanged(showFlag);
- }
- }
-
- public Object getAdapter(Class adapter) {
- Object obj = super.getAdapter(adapter);
- if (obj == null) {
- if (IContentOutlinePage.class.equals(adapter)) {
- return (outline);
- }
- }
- return (obj);
- }
-
- public ITextEditor getTextEditor(Locale locale) {
- int index = localesIndex.indexOf(locale);
- return textEditorsIndex.get(index);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorChangeAdapter.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorChangeAdapter.java
deleted file mode 100644
index f9cc20a1..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorChangeAdapter.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class MessagesEditorChangeAdapter implements IMessagesEditorChangeListener {
-
- /**
- *
- */
- public MessagesEditorChangeAdapter() {
- super();
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
- */
- public void keyTreeVisibleChanged(boolean visible) {
- // do nothing
- }
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean)
- */
- public void showOnlyUnusedAndMissingChanged(int showFilterFlag) {
- // do nothing
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener#selectedKeyChanged(java.lang.String, java.lang.String)
- */
- public void selectedKeyChanged(String oldKey, String newKey) {
- // do nothing
- }
-
- /* (non-Javadoc)
- * @see org.eclilpse.babel.editor.editor.IMessagesEditorChangeListener#keyTreeModelChanged(org.eclipse.babel.core.message.tree.IKeyTreeModel, org.eclipse.babel.core.message.tree.IKeyTreeModel)
- */
- public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
- // do nothing
- }
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener#editorDisposed()
- */
- public void editorDisposed() {
- // do nothing
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorContributor.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorContributor.java
deleted file mode 100644
index 8115d398..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorContributor.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.actions.FilterKeysAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.actions.KeyTreeVisibleAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.actions.NewLocaleAction;
-
-
-/**
- * Manages the installation/deinstallation of global actions for multi-page
- * editors. Responsible for the redirection of global actions to the active
- * editor.
- * Multi-page contributor replaces the contributors for the individual editors
- * in the multi-page editor.
- */
-public class MessagesEditorContributor
- extends MultiPageEditorActionBarContributor {
- private IEditorPart activeEditorPart;
-
- private KeyTreeVisibleAction toggleKeyTreeAction;
- private NewLocaleAction newLocaleAction;
- private IMenuManager resourceBundleMenu;
- private static String resourceBundleMenuID;
-
- /** singleton: probably not the cleanest way to access it from anywhere. */
- public static ActionGroup FILTERS = new FilterKeysActionGroup();
-
- /**
- * Creates a multi-page contributor.
- */
- public MessagesEditorContributor() {
- super();
- createActions();
- }
- /**
- * Returns the action registed with the given text editor.
- * @param editor eclipse text editor
- * @param actionID action id
- * @return IAction or null if editor is null.
- */
- protected IAction getAction(ITextEditor editor, String actionID) {
- return (editor == null ? null : editor.getAction(actionID));
- }
-
- /**
- * @see MultiPageEditorActionBarContributor
- * #setActivePage(org.eclipse.ui.IEditorPart)
- */
- public void setActivePage(IEditorPart part) {
- if (activeEditorPart == part) {
- return;
- }
-
- activeEditorPart = part;
-
- IActionBars actionBars = getActionBars();
- if (actionBars != null) {
-
- ITextEditor editor = (part instanceof ITextEditor)
- ? (ITextEditor) part : null;
-
- actionBars.setGlobalActionHandler(
- ActionFactory.DELETE.getId(),
- getAction(editor, ITextEditorActionConstants.DELETE));
- actionBars.setGlobalActionHandler(
- ActionFactory.UNDO.getId(),
- getAction(editor, ITextEditorActionConstants.UNDO));
- actionBars.setGlobalActionHandler(
- ActionFactory.REDO.getId(),
- getAction(editor, ITextEditorActionConstants.REDO));
- actionBars.setGlobalActionHandler(
- ActionFactory.CUT.getId(),
- getAction(editor, ITextEditorActionConstants.CUT));
- actionBars.setGlobalActionHandler(
- ActionFactory.COPY.getId(),
- getAction(editor, ITextEditorActionConstants.COPY));
- actionBars.setGlobalActionHandler(
- ActionFactory.PASTE.getId(),
- getAction(editor, ITextEditorActionConstants.PASTE));
- actionBars.setGlobalActionHandler(
- ActionFactory.SELECT_ALL.getId(),
- getAction(editor, ITextEditorActionConstants.SELECT_ALL));
- actionBars.setGlobalActionHandler(
- ActionFactory.FIND.getId(),
- getAction(editor, ITextEditorActionConstants.FIND));
- actionBars.setGlobalActionHandler(
- IDEActionFactory.BOOKMARK.getId(),
- getAction(editor, IDEActionFactory.BOOKMARK.getId()));
- actionBars.updateActionBars();
- }
- }
- private void createActions() {
-// sampleAction = new Action() {
-// public void run() {
-// MessageDialog.openInformation(null,
-// "ResourceBundle Editor Plug-in", "Sample Action Executed");
-// }
-// };
-// sampleAction.setText("Sample Action");
-// sampleAction.setToolTipText("Sample Action tool tip");
-// sampleAction.setImageDescriptor(
-// PlatformUI.getWorkbench().getSharedImages().
-// getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
-
- toggleKeyTreeAction = new KeyTreeVisibleAction();
- newLocaleAction = new NewLocaleAction();
-
-
-// toggleKeyTreeAction.setText("Show/Hide Key Tree");
-// toggleKeyTreeAction.setToolTipText("Click to show/hide the key tree");
-// toggleKeyTreeAction.setImageDescriptor(
-// PlatformUI.getWorkbench().getSharedImages().
-// getImageDescriptor(IDE.SharedImages.IMG_OPEN_MARKER));
-
- }
- /**
- * @see org.eclipse.ui.part.EditorActionBarContributor
- * #contributeToMenu(org.eclipse.jface.action.IMenuManager)
- */
- public void contributeToMenu(IMenuManager manager) {
-// System.out.println("active editor part:" +activeEditorPart);
-// System.out.println("menu editor:" + rbEditor);
- resourceBundleMenu = new MenuManager("&Messages", resourceBundleMenuID);
- manager.prependToGroup(IWorkbenchActionConstants.M_EDIT, resourceBundleMenu);
- resourceBundleMenu.add(toggleKeyTreeAction);
- resourceBundleMenu.add(newLocaleAction);
-
- FILTERS.fillContextMenu(resourceBundleMenu);
- }
- /**
- * @see org.eclipse.ui.part.EditorActionBarContributor
- * #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
- */
- public void contributeToToolBar(IToolBarManager manager) {
-// System.out.println("toolbar get page:" + getPage());
-// System.out.println("toolbar editor:" + rbEditor);
- manager.add(new Separator());
-// manager.add(sampleAction);
- manager.add(toggleKeyTreeAction);
- manager.add(newLocaleAction);
-
- ((FilterKeysActionGroup)FILTERS).fillActionBars(getActionBars());
- }
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.MultiPageEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
- */
- public void setActiveEditor(IEditorPart part) {
- super.setActiveEditor(part);
- MessagesEditor me = part instanceof MessagesEditor
- ? (MessagesEditor)part : null;
- toggleKeyTreeAction.setEditor(me);
- ((FilterKeysActionGroup) FILTERS).setActiveEditor(part);
- }
-
- /**
- * Groups the filter actions together.
- */
- private static class FilterKeysActionGroup extends ActionGroup {
- FilterKeysAction[] filtersAction = new FilterKeysAction[4];
-
- public FilterKeysActionGroup() {
- filtersAction[0] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ALL);
- filtersAction[1] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING);
- filtersAction[2] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED);
- filtersAction[3] = new FilterKeysAction(IMessagesEditorChangeListener.SHOW_ONLY_UNUSED);
- }
-
- public void fillActionBars(IActionBars actionBars) {
- for (int i = 0; i < filtersAction.length; i++) {
- actionBars.getToolBarManager().add(filtersAction[i]);
- }
- }
-
- public void fillContextMenu(IMenuManager menu) {
- MenuManager filters = new MenuManager("Filters");
- for (int i = 0; i < filtersAction.length; i++) {
- filters.add(filtersAction[i]);
- }
- menu.add(filters);
- }
-
- public void updateActionBars() {
- for (int i = 0; i < filtersAction.length;i++) {
- filtersAction[i].update();
- }
- }
- public void setActiveEditor(IEditorPart part) {
- MessagesEditor me = part instanceof MessagesEditor
- ? (MessagesEditor)part : null;
- for (int i = 0; i < filtersAction.length; i++) {
- filtersAction[i].setEditor(me);
- }
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorMarkers.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorMarkers.java
deleted file mode 100644
index 90dfbe11..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/MessagesEditorMarkers.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor;
-
-import java.beans.PropertyChangeEvent;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Observable;
-
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.MessagesBundleGroupAdapter;
-import org.eclipse.babel.core.message.checks.IMessageCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.IValidationMarkerStrategy;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.MessagesBundleGroupValidator;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.ValidationFailureEvent;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class MessagesEditorMarkers
- extends Observable implements IValidationMarkerStrategy {
-
-// private final Collection validationEvents = new ArrayList();
- private final MessagesBundleGroup messagesBundleGroup;
-
- // private Map<String,Set<ValidationFailureEvent>> markersIndex = new HashMap();
- /** index is the name of the key. value is the collection of markers on that key */
- private Map<String, Collection<IMessageCheck>> markersIndex = new HashMap<String, Collection<IMessageCheck>>();
-
- /**
- * Maps a localized key (a locale and key pair) to the collection of markers
- * for that key and that locale. If no there are no markers for the key and
- * locale then there will be no entry in the map.
- */
- private Map<String, Collection<IMessageCheck>> localizedMarkersMap = new HashMap<String, Collection<IMessageCheck>>();
-
- /**
- * @param messagesBundleGroup
- */
- public MessagesEditorMarkers(final MessagesBundleGroup messagesBundleGroup) {
- super();
- this.messagesBundleGroup = messagesBundleGroup;
- validate();
- messagesBundleGroup.addMessagesBundleGroupListener(
- new MessagesBundleGroupAdapter() {
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- resetMarkers();
- }
- public void messagesBundleChanged(
- MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- resetMarkers();
- }
- });
- }
- public void propertyChange(PropertyChangeEvent evt) {
- resetMarkers();
- }
- private void resetMarkers() {
- clear();
- validate();
- }
- });
- }
-
- private String buildLocalizedKey(Locale locale, String key) {
- //the '=' is hack to make sure no local=key can ever conflict
- //with another local=key: in other words
- //it makes a hash of the combination (key+locale).
- if (locale == null) {
- locale = UIUtils.ROOT_LOCALE;
- }
- return locale + "=" + key;
- }
-
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
- */
- public void markFailed(ValidationFailureEvent event) {
- Collection<IMessageCheck> markersForKey = markersIndex.get(event.getKey());
- if (markersForKey == null) {
- markersForKey = new HashSet<IMessageCheck>();
- markersIndex.put(event.getKey(), markersForKey);
- }
- markersForKey.add(event.getCheck());
-
- String localizedKey = buildLocalizedKey(event.getLocale(), event.getKey());
- markersForKey = localizedMarkersMap.get(localizedKey);
- if (markersForKey == null) {
- markersForKey = new HashSet<IMessageCheck>();
- localizedMarkersMap.put(localizedKey, markersForKey);
- }
- markersForKey.add(event.getCheck());
-
- //System.out.println("CREATE EDITOR MARKER");
- setChanged();
- }
-
- public void clear() {
- markersIndex.clear();
- localizedMarkersMap.clear();
- setChanged();
- notifyObservers(this);
- }
-
- public boolean isMarked(String key) {
- return markersIndex.containsKey(key);
- }
-
- public Collection<IMessageCheck> getFailedChecks(String key) {
- return markersIndex.get(key);
- }
-
- /**
- *
- * @param key
- * @param locale
- * @return the collection of markers for the locale and key; the return value may be
- * null if there are no markers
- */
- public Collection<IMessageCheck> getFailedChecks(final String key, final Locale locale) {
- return localizedMarkersMap.get(buildLocalizedKey(locale, key));
- }
-
- private void validate() {
- //TODO in a UI thread
- Locale[] locales = messagesBundleGroup.getLocales();
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- MessagesBundleGroupValidator.validate(messagesBundleGroup, locale, this);
- }
-
- /*
- * If anything has changed in this observable, notify the observers.
- *
- * Something will have changed if, for example, multiple keys have the
- * same text. Note that notifyObservers will in fact do nothing if
- * nothing in the above call to 'validate' resulted in a call to
- * setChange.
- */
- notifyObservers(null);
- }
-
- /**
- * @param key
- * @return true when the key has a missing or unused issue
- */
- public boolean isMissingOrUnusedKey(String key) {
- Collection<IMessageCheck> markers = getFailedChecks(key);
- return markers != null && markersContainMissing(markers);
- }
-
- /**
- * @param key
- * @param isMissingOrUnused true when it has been assesed already
- * that it is missing or unused
- * @return true when the key is unused
- */
- public boolean isUnusedKey(String key, boolean isMissingOrUnused) {
- if (!isMissingOrUnused) {
- return false;
- }
- Collection<IMessageCheck> markers = getFailedChecks(key, UIUtils.ROOT_LOCALE);
- //if we get a missing on the root locale, it means the
- //that some localized resources are referring to a key that is not in
- //the default locale anymore: in other words, assuming the
- //the code is up to date with the default properties
- //file, the key is now unused.
- return markers != null && markersContainMissing(markers);
- }
-
- private boolean markersContainMissing(Collection<IMessageCheck> markers) {
- for (IMessageCheck marker : markers) {
- if (marker == MissingValueCheck.MISSING_KEY) {
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/FilterKeysAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/FilterKeysAction.java
deleted file mode 100644
index 10a54f7b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/FilterKeysAction.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorContributor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- *
- * @author Hugues Malphettes
- */
-public class FilterKeysAction extends Action {
-
- private MessagesEditor editor;
- private final int flagToSet;
- private ChangeListener listener;
- /**
- * @param flagToSet The flag that will be set on unset
- */
- public FilterKeysAction(int flagToSet) {
- super("", IAction.AS_CHECK_BOX);
- this.flagToSet = flagToSet;
- listener = new ChangeListener();
- update();
- }
-
- private class ChangeListener extends MessagesEditorChangeAdapter {
- public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
- MessagesEditorContributor.FILTERS.updateActionBars();
- }
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- if (editor != null) {
- if (editor.isShowOnlyUnusedAndMissingKeys() != flagToSet) {
- editor.setShowOnlyUnusedMissingKeys(flagToSet);
- //listener.showOnlyUnusedAndMissingChanged(flagToSet)
- } else {
- editor.setShowOnlyUnusedMissingKeys(IMessagesEditorChangeListener.SHOW_ALL);
- //listener.showOnlyUnusedAndMissingChanged(IMessagesEditorChangeListener.SHOW_ALL)
- }
- }
- }
-
- public void update() {
- if (editor == null) {
- super.setEnabled(false);
- } else {
- super.setEnabled(true);
- }
-
- if (editor != null && editor.isShowOnlyUnusedAndMissingKeys() == flagToSet) {
- setChecked(true);
- } else {
- setChecked(false);
- }
- setText(getTextInternal());
- setToolTipText(getTooltipInternal());
- setImageDescriptor(UIUtils.getImageDescriptor(getImageKey()));
-
- }
-
- public String getImageKey() {
- switch (flagToSet) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return UIUtils.IMAGE_MISSING_TRANSLATION;
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return UIUtils.IMAGE_UNUSED_AND_MISSING_TRANSLATIONS;
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return UIUtils.IMAGE_UNUSED_TRANSLATION;
- case IMessagesEditorChangeListener.SHOW_ALL:
- default:
- return UIUtils.IMAGE_KEY;
- }
- }
-
- public String getTextInternal() {
- switch (flagToSet) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return "Show only missing translations";
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return "Show only missing or unused translations";
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return "Show only unused translations";
- case IMessagesEditorChangeListener.SHOW_ALL:
- default:
- return "Show all";
- }
- }
-
- private String getTooltipInternal() {
- return getTextInternal();
-// if (editor == null) {
-// return "no active editor";
-// }
-// switch (editor.isShowOnlyUnusedAndMissingKeys()) {
-// case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
-// return "Showing only keys with missing translation";
-// case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
-// return "Showing only keys with missing or unused translation";
-// case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
-// return "Showing only keys with missing translation";
-// case IMessagesEditorChangeListener.SHOW_ALL:
-// default:
-// return "Showing all keys";
-// }
- }
-
- public void setEditor(MessagesEditor editor) {
- if (editor == this.editor) {
- return;//no change
- }
- if (this.editor != null) {
- this.editor.removeChangeListener(listener);
- }
- this.editor = editor;
- update();
- if (editor != null) {
- editor.addChangeListener(listener);
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/KeyTreeVisibleAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/KeyTreeVisibleAction.java
deleted file mode 100644
index de9d9051..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/KeyTreeVisibleAction.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class KeyTreeVisibleAction extends Action {
-
- private MessagesEditor editor;
-
- /**
- *
- */
- public KeyTreeVisibleAction() {
- super("Show/Hide Key Tree", IAction.AS_CHECK_BOX);
-// setText();
- setToolTipText("Show/hide the key tree");
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_VIEW_LEFT));
- }
-
- //TODO RBEditor hold such an action registry. Then move this method to constructor
- public void setEditor(MessagesEditor editor) {
- this.editor = editor;
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void keyTreeVisibleChanged(boolean visible) {
- setChecked(visible);
- }
- });
- setChecked(editor.getI18NPage().isKeyTreeVisible());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- editor.getI18NPage().setKeyTreeVisible(
- !editor.getI18NPage().isKeyTreeVisible());
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/NewLocaleAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/NewLocaleAction.java
deleted file mode 100644
index 3346b224..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/actions/NewLocaleAction.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class NewLocaleAction extends Action {
-
- private MessagesEditor editor;
-
- /**
- *
- */
- public NewLocaleAction() {
- super("New &Locale...");
-// setText();
- setToolTipText("Add a new locale to the resource bundle.");
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_NEW_PROPERTIES_FILE));
-
-
-
- }
-
- //TODO RBEditor hold such an action registry. Then move this method to constructor
- public void setEditor(MessagesEditor editor) {
- this.editor = editor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/AnalyzerFactory.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/AnalyzerFactory.java
deleted file mode 100644
index baf5cb15..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/AnalyzerFactory.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2011,
- *
- * 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.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer;
-import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-
-
-public class AnalyzerFactory {
-
- public static ILevenshteinDistanceAnalyzer getLevenshteinDistanceAnalyzer () {
- return (ILevenshteinDistanceAnalyzer) LevenshteinDistanceAnalyzer.getInstance();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/EditorUtil.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/EditorUtil.java
deleted file mode 100644
index 66180613..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/EditorUtil.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.I18NPage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-public class EditorUtil {
-
- public static IKeyTreeNode getSelectedKeyTreeNode (IWorkbenchPage page) {
- MessagesEditor editor = (MessagesEditor)page.getActiveEditor();
- if (editor.getSelectedPage() instanceof I18NPage) {
- I18NPage p = (I18NPage) editor.getSelectedPage();
- ISelection selection = p.getSelection();
- if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
- return (IKeyTreeNode) ((IStructuredSelection) selection).getFirstElement();
- }
- }
- return null;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/KeyTreeFactory.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/KeyTreeFactory.java
deleted file mode 100644
index 53297b09..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/KeyTreeFactory.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-
-
-public class KeyTreeFactory {
-
- public static IAbstractKeyTreeModel createModel(IMessagesBundleGroup messagesBundleGroup) {
- return new AbstractKeyTreeModel((MessagesBundleGroup)messagesBundleGroup);
- }
-
- public static IValuedKeyTreeNode createKeyTree(IKeyTreeNode parent, String name, String id, IMessagesBundleGroup bundle) {
- return new ValuedKeyTreeNode(parent, name, id, bundle);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/MessagesBundleFactory.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/MessagesBundleFactory.java
deleted file mode 100644
index 4acf9bd8..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/MessagesBundleFactory.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.Locale;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesFileResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class MessagesBundleFactory {
-
- static Logger logger = Logger.getLogger(MessagesBundleFactory.class.getSimpleName());
-
-// public static IMessagesBundleGroup createBundleGroup(IResource resource) {
-// // TODO �berlegen welche Strategy wann ziehen soll
-// //zB
-// if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() == null ||
-// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() == null) {
-// File ioFile = new File(resource.getRawLocation().toFile().getPath());
-//
-// logger.log(Level.INFO, "createBundleGroup: " + resource.getName());
-//
-// return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile, MsgEditorPreferences.getInstance().getSerializerConfig(),
-// MsgEditorPreferences.getInstance().getDeserializerConfig()));
-// } else {
-// return MessagesBundleGroupFactory.createBundleGroup(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorSite(), (IFile)resource);
-// }
-//
-// }
-
- public static IMessage createMessage(String key, Locale locale) {
- String l = locale == null ? "[default]" : locale.toString();
- logger.log(Level.INFO, "createMessage, key: " + key + " locale: " + l);
-
- return new Message(key, locale);
- }
-
- public static IMessagesBundle createBundle(Locale locale, File resource)
- throws MessageException {
- try {
- //TODO have the text de/serializer tied to Eclipse preferences,
- //singleton per project, and listening for changes
-
- String l = locale == null ? "[default]" : locale.toString();
- logger.log(Level.INFO, "createBundle: " + resource.getName() + " locale: " + l);
-
- return new MessagesBundle(new PropertiesFileResource(
- locale,
- new PropertiesSerializer(MsgEditorPreferences.getInstance().getSerializerConfig()),
- new PropertiesDeserializer(MsgEditorPreferences.getInstance().getDeserializerConfig()),
- resource));
- } catch (FileNotFoundException e) {
- throw new MessageException(
- "Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/PropertiesGenerator.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/PropertiesGenerator.java
deleted file mode 100644
index 3a35d82c..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/PropertiesGenerator.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class PropertiesGenerator {
-
- public static final String GENERATED_BY = PropertiesSerializer.GENERATED_BY;
-
- public static String generate(IMessagesBundle messagesBundle) {
- PropertiesSerializer ps = new PropertiesSerializer(MsgEditorPreferences.getInstance().getSerializerConfig());
- return ps.serialize(messagesBundle);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/PropertiesParser.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/PropertiesParser.java
deleted file mode 100644
index 870b67ac..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/PropertiesParser.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.core.resources.IResource;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-
-public class PropertiesParser {
-
- public static IMessagesBundle parse(Locale locale, IResource resource) {
- PropertiesDeserializer pd = new PropertiesDeserializer(MsgEditorPreferences.getInstance().getDeserializerConfig());
-
- File file = resource.getRawLocation().toFile();
- File ioFile = new File(file.getPath());
- IMessagesBundle messagesBundle = MessagesBundleFactory.createBundle(locale, ioFile);
- pd.deserialize(messagesBundle, readFileAsString(file));
- return messagesBundle;
- }
-
- private static String readFileAsString(File filePath) {
- String content = "";
-
- if (!filePath.exists()) {
- return content;
- }
- BufferedReader fileReader = null;
- try {
- fileReader = new BufferedReader(new FileReader(filePath));
- String line = "";
-
- while ((line = fileReader.readLine()) != null) {
- content += line + "\n";
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (fileReader != null) {
- try {
- fileReader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- return content;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/ValuedKeyTreeNode.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/ValuedKeyTreeNode.java
deleted file mode 100644
index a7725707..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/api/ValuedKeyTreeNode.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.babel.editor.api;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-
-
-public class ValuedKeyTreeNode extends KeyTreeNode implements IValuedKeyTreeNode {
-
- public ValuedKeyTreeNode(IKeyTreeNode parent, String name, String messageKey,
- IMessagesBundleGroup messagesBundleGroup) {
- super(parent, name, messageKey, messagesBundleGroup);
- }
-
- private Map<Locale, String> values = new HashMap<Locale, String>();
- private Object info;
-
- public void initValues (Map<Locale, String> values) {
- this.values = values;
- }
-
- public void addValue (Locale locale, String value) {
- values.put(locale, value);
- }
-
- public String getValue (Locale locale) {
- return values.get(locale);
- }
-
- public Collection<String> getValues () {
- return values.values();
- }
-
- public void setInfo(Object info) {
- this.info = info;
- }
-
- public Object getInfo() {
- return info;
- }
-
- public Collection<Locale> getLocales () {
- List<Locale> locs = new ArrayList<Locale> ();
- for (Locale loc : values.keySet()) {
- locs.add(loc);
- }
- return locs;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/Builder.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/Builder.java
deleted file mode 100644
index f4507d38..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/Builder.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.builder;
-
-//import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.bundle.MessagesBundleGroupFactory;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.FileMarkerStrategy;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.IValidationMarkerStrategy;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.MessagesBundleGroupValidator;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class Builder extends IncrementalProjectBuilder {
-
- public static final String BUILDER_ID =
- "org.eclipse.babel.editor.rbeBuilder"; //$NON-NLS-1$
-
- private IValidationMarkerStrategy markerStrategy = new FileMarkerStrategy();
-
- class SampleDeltaVisitor implements IResourceDeltaVisitor {
- /**
- * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
- */
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
- switch (delta.getKind()) {
- case IResourceDelta.ADDED:
- // handle added resource
- System.out.println("RBE DELTA added");
- checkBundleResource(resource);
- break;
- case IResourceDelta.REMOVED:
- System.out.println("RBE DELTA Removed"); //$NON-NLS-1$
- RBManager.getInstance(delta.getResource().getProject()).notifyResourceRemoved(delta.getResource());
- // handle removed resource
- break;
- case IResourceDelta.CHANGED:
- System.out.println("RBE DELTA changed");
- // handle changed resource
- checkBundleResource(resource);
- break;
- }
- //return true to continue visiting children.
- return true;
- }
- }
-
- class SampleResourceVisitor implements IResourceVisitor {
- public boolean visit(IResource resource) {
- checkBundleResource(resource);
- //return true to continue visiting children.
- return true;
- }
- }
-
- /** list built during a single build of the properties files.
- * Contains the list of files that must be validated.
- * The validation is done only at the end of the visitor.
- * This way the visitor can add extra files to be visited.
- * For example: if the default properties file is
- * changed, it is a good idea to rebuild all
- * localized files in the same MessageBundleGroup even if themselves
- * were not changed. */
- private Set _resourcesToValidate;
-
- /**
- * Index built during a single build.
- * <p>
- * The values of that map are message bundles.
- * The key is a resource that belongs to that message bundle.
- * </p>
- */
- private Map<IFile,MessagesBundleGroup> _alreadBuiltMessageBundle;
-
-// /** one indexer per project we open and close it at the beginning and the end of each build. */
-// private Indexer _indexer = new Indexer();
-
- /**
- * @see org.eclipse.core.resources.IncrementalProjectBuilder#build(
- * int, java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
- */
- protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
- throws CoreException {
- try {
- _alreadBuiltMessageBundle = null;
- _resourcesToValidate = null;
- if (kind == FULL_BUILD) {
- fullBuild(monitor);
- } else {
- IResourceDelta delta = getDelta(getProject());
- if (delta == null) {
- fullBuild(monitor);
- } else {
- incrementalBuild(delta, monitor);
- }
- }
- } finally {
- try {
- finishBuild();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- //must dispose the message bundles:
- if (_alreadBuiltMessageBundle != null) {
- for (MessagesBundleGroup msgGrp : _alreadBuiltMessageBundle.values()) {
- try {
-// msgGrp.dispose(); // TODO: [alst] do we need this really?
- } catch (Throwable t) {
- //FIXME: remove this debugging:
- System.err.println(
- "error disposing message-bundle-group "
- + msgGrp.getName());
- //disregard crashes: we are doing our best effort to dispose things.
- }
- }
- _alreadBuiltMessageBundle = null;
- _resourcesToValidate = null;
- }
-// if (_indexer != null) {
-// try {
-// _indexer.close(true);
-// _indexer.clear();
-// } catch (CorruptIndexException e) {
-// e.printStackTrace();
-// } catch (IOException e) {
-// e.printStackTrace();
-// }
-// }
- }
- }
- return null;
- }
-
- /**
- * Collect the resource bundles to validate and
- * index the corresponding MessageBundleGroup(s).
- * @param resource The resource currently validated.
- */
- void checkBundleResource(IResource resource) {
- if (true)
- return; // TODO [alst]
- if (resource instanceof IFile && resource.getName().endsWith(
- ".properties")) { //$NON-NLS-1$ //TODO have customized?
- IFile file = (IFile) resource;
- if (file.isDerived()) {
- return;
- }
- //System.err.println("Looking at " + file.getFullPath());
- deleteMarkers(file);
- MessagesBundleGroup msgBundleGrp = null;
- if (_alreadBuiltMessageBundle == null) {
- _alreadBuiltMessageBundle = new HashMap<IFile,MessagesBundleGroup>();
- _resourcesToValidate = new HashSet();
- } else {
- msgBundleGrp = _alreadBuiltMessageBundle.get(file);
- }
- if (msgBundleGrp == null) {
- msgBundleGrp = MessagesBundleGroupFactory.createBundleGroup(null, file);
- if (msgBundleGrp != null) {
- //index the files for which this MessagesBundleGroup
- //should be used for the validation.
- //cheaper than creating a group for each on of those
- //files.
- boolean validateEntireGroup = false;
- for (IMessagesBundle msgBundle : msgBundleGrp.getMessagesBundles()) {
- Object src = ((MessagesBundle)msgBundle).getResource().getSource();
- //System.err.println(src + " -> " + msgBundleGrp);
- if (src instanceof IFile) {//when it is a read-only thing we don't index it.
- _alreadBuiltMessageBundle.put((IFile)src, msgBundleGrp);
- if (!validateEntireGroup && src == resource) {
- if (((MessagesBundle)msgBundle).getLocale() == null
- || ((MessagesBundle)msgBundle).getLocale().equals(UIUtils.ROOT_LOCALE)) {
- //ok the default properties have been changed.
- //make sure that all resources in this bundle group
- //are validated too:
- validateEntireGroup = true;
-
- //TODO: eventually something similar.
- //with foo_en.properties changed.
- //then foo_en_US.properties must be revalidated
- //and foo_en_CA.properties as well.
-
- }
- }
- }
- }
- if (validateEntireGroup) {
- for (IMessagesBundle msgBundle : msgBundleGrp.getMessagesBundles()) {
- Object src = ((MessagesBundle)msgBundle).getResource().getSource();
- _resourcesToValidate.add(src);
- }
- }
- }
- }
-
- _resourcesToValidate.add(resource);
-
- }
- }
-
- /**
- * Validates the message bundles collected by the visitor.
- * Makes sure we validate only once each message bundle and build only once each
- * MessageBundleGroup it belongs to.
- */
- private void finishBuild() {
- if (_resourcesToValidate != null) {
- for (Iterator it = _resourcesToValidate.iterator(); it.hasNext();) {
- IFile resource = (IFile)it.next();
- MessagesBundleGroup msgBundleGrp =
- _alreadBuiltMessageBundle.get(resource);
-
- if (msgBundleGrp != null) {
- //when null it is probably because it was skipped from
- //the group because the locale was filtered.
- try {
- // System.out.println("Validate " + resource); //$NON-NLS-1$
- //TODO check if there is a matching EclipsePropertiesEditorResource already open.
- //else, create MessagesBundle from PropertiesIFileResource
- MessagesBundle messagesBundle = msgBundleGrp.getMessagesBundle(resource);
- if (messagesBundle != null) {
- Locale locale = messagesBundle.getLocale();
- MessagesBundleGroupValidator.validate(msgBundleGrp, locale, markerStrategy);
- }//, _indexer);
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- // System.out.println("Not validating " + resource); //$NON-NLS-1$
- }
- }
- }
- }
-
- private void deleteMarkers(IFile file) {
- try {
-// System.out.println("Builder: deleteMarkers"); //$NON-NLS-1$
- file.deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false, IResource.DEPTH_ZERO);
- } catch (CoreException ce) {
- }
- }
-
- protected void fullBuild(final IProgressMonitor monitor)
- throws CoreException {
-// System.out.println("Builder: fullBuild"); //$NON-NLS-1$
- getProject().accept(new SampleResourceVisitor());
- }
-
- protected void incrementalBuild(IResourceDelta delta,
- IProgressMonitor monitor) throws CoreException {
-// System.out.println("Builder: incrementalBuild"); //$NON-NLS-1$
- delta.accept(new SampleDeltaVisitor());
- }
-
- protected void clean(IProgressMonitor monitor) throws CoreException {
- ResourcesPlugin.getWorkspace().getRoot()
- .deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false, IResource.DEPTH_INFINITE);
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/Nature.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/Nature.java
deleted file mode 100644
index 5c3c6c22..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/Nature.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.builder;
-
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.runtime.CoreException;
-
-public class Nature implements IProjectNature {
-
- /**
- * ID of this project nature
- */
- public static final String NATURE_ID = "org.eclipse.babel.editor.rbeNature";
-
- private IProject project;
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#configure()
- */
- public void configure() throws CoreException {
- IProjectDescription desc = project.getDescription();
- ICommand[] commands = desc.getBuildSpec();
-
- for (int i = 0; i < commands.length; ++i) {
- if (commands[i].getBuilderName().equals(Builder.BUILDER_ID)) {
- return;
- }
- }
-
- ICommand[] newCommands = new ICommand[commands.length + 1];
- System.arraycopy(commands, 0, newCommands, 0, commands.length);
- ICommand command = desc.newCommand();
- command.setBuilderName(Builder.BUILDER_ID);
- newCommands[newCommands.length - 1] = command;
- desc.setBuildSpec(newCommands);
- project.setDescription(desc, null);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#deconfigure()
- */
- public void deconfigure() throws CoreException {
- IProjectDescription description = getProject().getDescription();
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; ++i) {
- if (commands[i].getBuilderName().equals(Builder.BUILDER_ID)) {
- ICommand[] newCommands = new ICommand[commands.length - 1];
- System.arraycopy(commands, 0, newCommands, 0, i);
- System.arraycopy(commands, i + 1, newCommands, i,
- commands.length - i - 1);
- description.setBuildSpec(newCommands);
- return;
- }
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#getProject()
- */
- public IProject getProject() {
- return project;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
- */
- public void setProject(IProject project) {
- this.project = project;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureAction.java
deleted file mode 100644
index 41dcba21..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureAction.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.builder;
-
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-public class ToggleNatureAction implements IObjectActionDelegate {
-
- /**
- * Method call during the start up of the plugin or during
- * a change of the preference MsgEditorPreferences#ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS.
- * <p>
- * Goes through the list of opened projects and either remove all the
- * natures or add them all for each opened java project if the nature was not there.
- * </p>
- */
- public static void addOrRemoveNatureOnAllJavaProjects(boolean doAdd) {
- IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projs.length; i++) {
- IProject project = projs[i];
- addOrRemoveNatureOnProject(project, doAdd, true);
- }
- }
-
- /**
- *
- * @param project The project to setup if necessary
- * @param doAdd true to add, false to remove.
- * @param onlyJavaProject when true the nature will be added or removed
- * if and only if the project has a jdt-java nature
- */
- public static void addOrRemoveNatureOnProject(IProject project,
- boolean doAdd, boolean onlyJavaProject) {
- try {
- if (project.isAccessible() && (!onlyJavaProject ||
- UIUtils.hasNature(project, UIUtils.JDT_JAVA_NATURE))) {
- if (doAdd) {
- if (project.getNature(Nature.NATURE_ID) == null) {
- toggleNature(project);
- }
- } else {
- if (project.getNature(Nature.NATURE_ID) != null) {
- toggleNature(project);
- }
- }
- }
- } catch (CoreException ce) {
- ce.printStackTrace();//REMOVEME
- }
-
- }
-
-
- private ISelection selection;
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- public void run(IAction action) {
- if (selection instanceof IStructuredSelection) {
- for (Object element : ((IStructuredSelection) selection).toList()) {
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element)
- .getAdapter(IProject.class);
- }
- if (project != null) {
- toggleNature(project);
- }
- }
- }
- }
-
- /**
- * Called when the selection is changed.
- * Update the state of the action (enabled/disabled) and its label.
- */
- public void selectionChanged(IAction action, ISelection selection) {
- this.selection = selection;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
- * org.eclipse.ui.IWorkbenchPart)
- */
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- }
-
- /**
- * Toggles sample nature on a project
- *
- * @param project
- * to have sample nature added or removed
- */
- private static void toggleNature(IProject project) {
- try {
- IProjectDescription description = project.getDescription();
- String[] natures = description.getNatureIds();
-
- for (int i = 0; i < natures.length; ++i) {
- if (Nature.NATURE_ID.equals(natures[i])) {
- // Remove the nature
- String[] newNatures = new String[natures.length - 1];
- System.arraycopy(natures, 0, newNatures, 0, i);
- System.arraycopy(natures, i + 1, newNatures, i,
- natures.length - i - 1);
- description.setNatureIds(newNatures);
- project.setDescription(description, null);
- return;
- }
- }
-
- // Add the nature
- String[] newNatures = new String[natures.length + 1];
- System.arraycopy(natures, 0, newNatures, 0, natures.length);
- newNatures[natures.length] = Nature.NATURE_ID;
- System.out.println("New natures: " + BabelUtils.join(newNatures, ", "));
- description.setNatureIds(newNatures);
- project.setDescription(description, null);
- } catch (CoreException e) {
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureActionAdd.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureActionAdd.java
deleted file mode 100644
index fb9cc178..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureActionAdd.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.builder;
-
-
-/**
- * @author hmalphettes
- */
-public class ToggleNatureActionAdd extends ToggleNatureAction {
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureActionRemove.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureActionRemove.java
deleted file mode 100644
index a91aabed..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/builder/ToggleNatureActionRemove.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.builder;
-
-
-/**
- * @author hmalphettes
- */
-public class ToggleNatureActionRemove extends ToggleNatureAction {
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/BundleGroupRegistry.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/BundleGroupRegistry.java
deleted file mode 100644
index 01531afe..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/BundleGroupRegistry.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.bundle;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.core.resources.IResource;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class BundleGroupRegistry {
-
-
- public static MessagesBundleGroup getBundleGroup(IResource resource) {
- return null;//MessagesBundleGroupFactory.
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/DefaultBundleGroupStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/DefaultBundleGroupStrategy.java
deleted file mode 100644
index 2cb95c8e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/DefaultBundleGroupStrategy.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.bundle;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.MessageException;
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesIFileResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy;
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.EclipsePropertiesEditorResource;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesResource;
-
-
-/**
- * MessagesBundle group strategy for standard properties file structure. That is,
- * all *.properties files of the same base name within the same directory.
- * @author Pascal Essiembre
- */
-public class DefaultBundleGroupStrategy implements IMessagesBundleGroupStrategy {
-
- /** Class name of Properties file editor (Eclipse 3.1). */
- protected static final String PROPERTIES_EDITOR_CLASS_NAME =
- "org.eclipse.jdt.internal.ui.propertiesfileeditor." //$NON-NLS-1$
- + "PropertiesFileEditor"; //$NON-NLS-1$
-
- /** Empty bundle array. */
- protected static final MessagesBundle[] EMPTY_BUNDLES = new MessagesBundle[] {};
-
- /** Eclipse editor site. */
- protected IEditorSite site;
- /** File being open, triggering the creation of a bundle group. */
- private IFile file;
- /** MessagesBundle group base name. */
- private final String baseName;
- /** Pattern used to match files in this strategy. */
- private final String fileMatchPattern;
-
- /**
- * Constructor.
- * @param site editor site
- * @param file file opened
- */
- public DefaultBundleGroupStrategy(IEditorSite site, IFile file) {
- super();
- this.file = file;
- this.site = site;
-
- String patternCore =
- "((_[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$
- + file.getFileExtension() + ")$"; //$NON-NLS-1$
-
- // Compute and cache name
- String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
- this.baseName = file.getName().replaceFirst(
- namePattern, "$1"); //$NON-NLS-1$
-
- // File matching pattern
- this.fileMatchPattern =
- "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- /**
- * @see org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy
- * #createMessagesBundleGroupName()
- */
- public String createMessagesBundleGroupName() {
- return baseName + "[...]." + file.getFileExtension(); //$NON-NLS-1$
- }
-
- public String createMessagesBundleId() {
- return getResourceBundleId(file);
- }
-
- public static String getResourceBundleId (IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile).getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "") +
- getResourceBundleName(resource);
- }
-
- public 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$
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy
- * #loadMessagesBundles()
- */
- public MessagesBundle[] loadMessagesBundles() throws MessageException {
- Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
- collectBundlesInContainer(file.getParent(), bundles);
- return bundles.toArray(EMPTY_BUNDLES);
- }
-
- protected void collectBundlesInContainer(IContainer container,
- Collection<MessagesBundle> bundlesCollector) throws MessageException {
- if (!container.exists()) {
- return;
- }
- IResource[] resources = null;
- try {
- resources = container.members();
- } catch (CoreException e) {
- throw new MessageException(
- "Can't load resource bundles.", e); //$NON-NLS-1$
- }
-
- for (int i = 0; i < resources.length; i++) {
- IResource resource = resources[i];
- String resourceName = resource.getName();
- if (resource instanceof IFile
- && resourceName.matches(fileMatchPattern)) {
- // Build local title
- String localeText = resourceName.replaceFirst(
- fileMatchPattern, "$2"); //$NON-NLS-1$
- Locale locale = BabelUtils.parseLocale(localeText);
- if (UIUtils.isDisplayed(locale)) {
- bundlesCollector.add(createBundle(locale, resource));
- }
- }
- }
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy#createBundle(java.util.Locale)
- */
- public MessagesBundle createMessagesBundle(Locale locale) {
- // TODO Auto-generated method stub
- return null;
- }
-
- /**
- * Creates a resource bundle for an existing resource.
- * @param locale locale for which to create a bundle
- * @param resource resource used to create bundle
- * @return an initialized bundle
- */
- protected MessagesBundle createBundle(Locale locale, IResource resource)
- throws MessageException {
- try {
- MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
- //TODO have bundleResource created in a separate factory
- //shared between strategies
- IMessagesResource messagesResource;
- if (site == null) {
- //site is null during the build.
- messagesResource = new PropertiesIFileResource(
- locale,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- (IFile) resource, MessagesEditorPlugin.getDefault());
- } else {
- messagesResource = new EclipsePropertiesEditorResource(
- locale,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- createEditor(resource, locale));
- }
- return new MessagesBundle(messagesResource);
- } catch (PartInitException e) {
- throw new MessageException(
- "Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
- }
- }
-
- /**
- * Creates an Eclipse editor.
- * @param site
- * @param resource
- * @param locale
- * @return
- * @throws PartInitException
- */
- protected TextEditor createEditor(IResource resource, Locale locale)
- throws PartInitException {
-
- TextEditor textEditor = null;
- if (resource != null && resource instanceof IFile) {
- try {
- resource.refreshLocal(IResource.DEPTH_ZERO, null);
- } catch (CoreException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- IEditorInput newEditorInput =
- new FileEditorInput((IFile) resource);
- textEditor = null;
- try {
- // Use PropertiesFileEditor if available
- textEditor = (TextEditor) Class.forName(
- PROPERTIES_EDITOR_CLASS_NAME).newInstance();
- } catch (Exception e) {
- // Use default editor otherwise
- textEditor = new TextEditor();
- }
- textEditor.init(site, newEditorInput);
- }
- return textEditor;
- }
-
- /**
- * @return The file opened.
- */
- protected IFile getOpenedFile() {
- return file;
- }
-
- /**
- * @return The base name of the resource bundle.
- */
- protected String getBaseName() {
- return baseName;
- }
-
- public String getProjectName() {
- return ResourcesPlugin.getWorkspace().getRoot().getProject(file.getFullPath().segments()[0]).getName();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/MessagesBundleGroupFactory.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/MessagesBundleGroupFactory.java
deleted file mode 100644
index 6d9a8abf..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/MessagesBundleGroupFactory.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.bundle;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.ui.IEditorSite;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * @author Pascal Essiembre
- * @author Hugues Malphettes
- */
-//TODO make /*default*/ that only the registry would use
-public final class MessagesBundleGroupFactory {
-
- /**
- *
- */
- private MessagesBundleGroupFactory() {
- super();
- }
-
- /**
- * Creates a new bundle group, based on the given site and file. Currently,
- * only default bundle groups and Eclipse NL within a plugin are supported.
- * @param site
- * @param file
- * @return
- */
- public static MessagesBundleGroup createBundleGroup(IEditorSite site, IFile file) {
- /*
- * Check if NL is supported.
- */
- if (!MsgEditorPreferences.getInstance().isNLSupportEnabled()) {
- return createDefaultBundleGroup(site, file);
- }
-
- //check we are inside an eclipse plugin project where NL is supported at runtime:
- IProject proj = file.getProject();
- if (proj == null || !UIUtils.hasNature(proj, UIUtils.PDE_NATURE)) { //$NON-NLS-1$
- return createDefaultBundleGroup(site, file);
- }
-
- IFolder nl = getNLFolder(file);
-
- //look if we are inside a fragment plugin:
- String hostId = getHostPluginId(file);
- if (hostId != null) {
- //we are indeed inside a fragment.
- //use the appropriate strategy.
- //we are a priori not interested in
- //looking for the files of other languages
- //that might be in other fragments plugins.
- //this behavior could be changed.
- return new MessagesBundleGroup(
- new NLFragmentBundleGroupStrategy(site, file, hostId, nl));
- }
-
- if (site == null) {
- //this is during the build we are not interested in validating files
- //coming from other projects:
- //no need to look in other projects for related files.
- return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
- site, file, nl));
- }
-
- //if we are in a host plugin we might have fragments for it.
- //let's look for them so we can eventually load them all.
- //in this situation we are only looking for those fragments
- //inside the workspace and with files being developed there;
- //in other words: we don't look for read-only resources
- //located inside jars or the platform itself.
- IProject[] frags = collectTargetingFragments(file);
- if (frags != null) {
- return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
- site, file, nl, frags));
- }
-
- /*
- * Check if there is an NL directory
- * something like: nl/en/US/messages.properties
- * which is for eclipse runtime equivalent to: messages_en_US.properties
- */
- return new MessagesBundleGroup(new NLPluginBundleGroupStrategy(
- site, file, nl));
-
- }
-
- private static MessagesBundleGroup createDefaultBundleGroup(IEditorSite site, IFile file) {
- return new MessagesBundleGroup(
- new DefaultBundleGroupStrategy(site, file));
- }
-
-//reading plugin manifests related utility methods. TO BE MOVED TO CORE ?
-
- private static final String BUNDLE_NAME = "Bundle-SymbolicName:"; //$NON-NLS-1$
- private static final String FRAG_HOST = "Fragment-Host:"; //$NON-NLS-1$
- /**
- * @param file
- * @return The id of the host-plugin if the edited file is inside a
- * pde-project that is a fragment. null otherwise.
- */
- static String getHostPluginId(IResource file) {
- return getPDEManifestAttribute(file, FRAG_HOST);
- }
- /**
- * @param file
- * @return The id of the BUNDLE_NAME if the edited file is inside a
- * pde-project. null otherwise.
- */
- static String getBundleId(IResource file) {
- return getPDEManifestAttribute(file, BUNDLE_NAME);
- }
- /**
- * Fetches the IProject in which openedFile is located.
- * If the project is a PDE project, looks for the MANIFEST.MF file
- * Parses the file and returns the value corresponding to the key
- * The value is stripped of its eventual properties (version constraints and others).
- */
- static String getPDEManifestAttribute(IResource openedFile, String key) {
- IProject proj = openedFile.getProject();
- if (proj == null || !proj.isAccessible()) {
- return null;
- }
- if (!UIUtils.hasNature(proj, UIUtils.PDE_NATURE)) { //$NON-NLS-1$
- return null;
- }
- IResource mf = proj.findMember(new Path("META-INF/MANIFEST.MF")); //$NON-NLS-1$
- if (mf == null || mf.getType() != IResource.FILE) {
- return null;
- }
- //now look for the FragmentHost.
- //don't use the java.util.Manifest API to parse the manifest as sometimes,
- //eclipse tolerates faulty manifests where lines are more than 70 characters long.
- InputStream in = null;
- try {
- in = ((IFile)mf).getContents();
- //supposedly in utf-8. should not really matter for us
- Reader r = new InputStreamReader(in, "UTF-8");
- LineNumberReader lnr = new LineNumberReader(r);
- String line = lnr.readLine();
- while (line != null) {
- if (line.startsWith(key)) {
- String value = line.substring(key.length());
- int index = value.indexOf(';');
- if (index != -1) {
- //remove the versions constraints and other properties.
- value = value.substring(0, index);
- }
- return value.trim();
- }
- line = lnr.readLine();
- }
- lnr.close();
- r.close();
- } catch (IOException ioe) {
- //TODO: something!
- ioe.printStackTrace();
- } catch (CoreException ce) {
- //TODO: something!
- ce.printStackTrace();
- } finally {
- if (in != null) try { in.close(); } catch (IOException e) {}
- }
- return null;
- }
-
- /**
- * @see http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.
- *
- * @param openedFile
- * @return The nl folder that is a direct child of the project and an ancestor
- * of the opened file or null if no such thing.
- */
- protected static IFolder getNLFolder(IFile openedFile) {
- IContainer cont = openedFile.getParent();
- while (cont != null) {
- if (cont.getParent() != null
- && cont.getParent().getType() == IResource.PROJECT) {
- if (cont.getName().equals("nl")) {
- return (IFolder)cont;
- }
- return null;
- }
- cont = cont.getParent();
- }
- return null;
- }
-
- private static final IProject[] EMPTY_PROJECTS = new IProject[0];
-
- /**
- * Searches in the workspace for plugins that are fragment that target
- * the current pde plugin.
- *
- * @param openedFile
- * @return
- */
- protected static IProject[] collectTargetingFragments(IFile openedFile) {
- IProject thisProject = openedFile.getProject();
- if (thisProject == null) {
- return null;
- }
- Collection<IProject> projs = null;
- String bundleId = getBundleId(openedFile);
- try {
- //now look in the workspace for the host-plugin as a
- //developed project:
- IResource[] members =
- ((IContainer)thisProject.getParent()).members();
- for (int i = 0 ; i < members.length ; i++ ) {
- IResource childRes = members[i];
- if (childRes != thisProject
- && childRes.getType() == IResource.PROJECT) {
- String hostId = getHostPluginId(childRes);
- if (bundleId.equals(hostId)) {
- if (projs == null) {
- projs = new ArrayList<IProject>();
- }
- projs.add((IProject)childRes);
- }
- }
- }
- } catch (Exception e) {
-
- }
- return projs == null ? null
- : projs.toArray(EMPTY_PROJECTS);
- }
-
-
-
-}
-
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/NLFragmentBundleGroupStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
deleted file mode 100644
index c4d23b25..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/NLFragmentBundleGroupStrategy.java
+++ /dev/null
@@ -1,713 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.bundle;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.Reader;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Locale;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.resource.PropertiesIFileResource;
-import org.eclipse.babel.core.message.resource.PropertiesReadOnlyResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.resource.EclipsePropertiesEditorResource;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.osgi.framework.Bundle;
-
-/**
- * This strategy is used when a resource bundle that belongs to a plug-in fragment
- * project is loaded.
- * <p>
- * This class loads resource bundles following the default strategy. If no root
- * locale resource is found, it tries to locate that resource inside the
- * host plug-in of the fragment. The host plug-in is searched inside the workspace
- * first and if not found inside the Eclipse platform being run.
- * <p>
- * This is useful for the development of i18n packages for eclipse plug-ins: The
- * best practice is to define the root locale messages inside the plug-in itself
- * and to define the other locales in a fragment that host that plug-in. Thanks
- * to this strategy the root locale can be used by the user when the user edits
- * the messages defined in the fragment alone.
- *
- * @author Pascal Essiembre
- * @author Hugues Malphettes
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=214521">Bug 214521 - in the resource bundle editor take into account the resources of the "Host-Plugin" when opened bundle is in a plugin-fragment</a>
- */
-public class NLFragmentBundleGroupStrategy extends NLPluginBundleGroupStrategy {
-
-
- private final String _fragmentHostID;
-
- private boolean hostPluginInWorkspaceWasLookedFor = false;
- private IProject hostPluginInWorkspace;
-
-
- /**
- *
- */
- public NLFragmentBundleGroupStrategy(IEditorSite site, IFile file,
- String fragmentHostID, IFolder nlFolder) {
- super(site, file, nlFolder);
- _fragmentHostID = fragmentHostID;
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy#loadBundles()
- */
- public MessagesBundle[] loadMessagesBundles() {
- MessagesBundle[] defaultFiles = super.loadMessagesBundles();
- //look if the defaut properties is already in there.
- //if that is the case we don't try to load extra properties
- for (int i = 0 ; i < defaultFiles.length ; i++) {
- MessagesBundle mb = defaultFiles[i];
- if (UIUtils.ROOT_LOCALE.equals(mb.getLocale())
- || mb.getLocale() == null) {
- //... if this is the base one then no need to look any further.:
- return defaultFiles;
- }
- }
- try {
- MessagesBundle locatedBaseProperties = loadDefaultMessagesBundle();
- if (locatedBaseProperties != null) {
- MessagesBundle[] result =
- new MessagesBundle[defaultFiles.length+1];
- result[0] = locatedBaseProperties;
- System.arraycopy(
- defaultFiles, 0, result, 1, defaultFiles.length);
- return result;
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy
- * #createBundle(java.util.Locale)
- */
- public MessagesBundle createMessagesBundle(Locale locale) {
- return super.createMessagesBundle(locale);
- }
-
- /**
- * @see org.eclipse.babel.core.message.strategy.IMessagesBundleGroupStrategy
- * #createMessagesBundleGroupName()
- */
- public String createMessagesBundleGroupName() {
- return super.createMessagesBundleGroupName();
- }
-
-
-
- /**
- * @return The message bundle for the message.properties file associated to
- * the edited resource bundle once this code is executed by eclipse.
- * @throws CoreException
- * @throws IOException
- */
- private MessagesBundle loadDefaultMessagesBundle()
- throws IOException, CoreException {
- IEditorInput newEditorInput = null;
- IPath propertiesBasePath = getPropertiesPath();
- //look for the bundle with the given symbolic name.
- //first look into the workspace itself through the various pde projects
- String resourceLocationLabel = null;
-
- IProject developpedProject = getHostPluginProjectDevelopedInWorkspace();
- if (developpedProject != null) {
- IFile file = getPropertiesFile(
- developpedProject, propertiesBasePath);
- if (!file.exists()) {
- //try inside the jars:
- String[] jarredProps =
- getJarredPropertiesAndResourceLocationLabel(
- developpedProject, propertiesBasePath);
- if (jarredProps != null) {
- if (site == null) {
- //then we are currently executing a build,
- //not creating editors:
- MsgEditorPreferences prefs =
- MsgEditorPreferences.getInstance();
- return new MessagesBundle(
- new PropertiesReadOnlyResource(
- UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- jarredProps[0], jarredProps[1]));
- }
- newEditorInput = new DummyEditorInput(jarredProps[0],
- getPropertiesPath().lastSegment(),
- jarredProps[1]);
- resourceLocationLabel = jarredProps[1];
- }
- }
- //well if the file does not exist, it will be clear where we were
- //looking for it and that we could not find it
- if (site == null) {
- //then we are currently executing a build,
- //not creating editors:
- if (file.exists()) {
- MsgEditorPreferences prefs =
- MsgEditorPreferences.getInstance();
- return new MessagesBundle(new PropertiesIFileResource(
- UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()), file,
- MessagesEditorPlugin.getDefault()));
- } else {
- //during the build if the file does not exist. skip.
- return null;
- }
- }
- if (file.exists()) {
- newEditorInput = new FileEditorInput(file);
- }
- //assume there is no more than one version of the plugin
- //in the same workspace.
- }
-
- //second look into the current platform.
- if (newEditorInput == null) {
- InputStream in = null;
- String resourceName = null;
-
- try {
-
- Bundle bundle = Platform.getBundle(_fragmentHostID);
- if (bundle != null) {
- //at this point there are 2 strategies:
- //use the osgi apis to look into the bundle's resources
- //or grab the physical artifact behind the bundle and dive
- //into it.
- resourceName = propertiesBasePath.toString();
- URL url = bundle.getEntry(resourceName);
- if (url != null) {
- in = url.openStream();
- resourceLocationLabel = url.toExternalForm();
- } else {
- //it seems this is unused. at least
- //we might need to transform the path into the name of
- //the properties for the classloader here.
- url = bundle.getResource(resourceName);
- if (url != null) {
- in = url.openStream();
- resourceLocationLabel = url.toExternalForm();
- }
- }
- }
-
- if (in != null) {
- String contents = getContents(in);
- if (site == null) {
- //then we are currently executing a build,
- //not creating editors:
- MsgEditorPreferences prefs =
- MsgEditorPreferences.getInstance();
- return new MessagesBundle(
- new PropertiesReadOnlyResource(
- UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()),
- contents, resourceLocationLabel));
- }
- newEditorInput = new DummyEditorInput(contents,
- getPropertiesPath().lastSegment(),
- getPropertiesPath().toString());
- }
- } finally {
- if (in != null) try { in.close(); } catch (IOException ioe) {}
- }
- }
-
- // if we found something that we could factor into a text editor input
- // we create a text editor and the whole MessagesBundle.
- if (newEditorInput != null) {
- TextEditor textEditor = null;
- if (site != null) {
- //during a build the site is not there and we don't edit things
- //anyways.
- //we need a new type of PropertiesEditorResource. not based on
- //file and ifile and
- //editorinput.
- try {
- // Use PropertiesFileEditor if available
- textEditor = (TextEditor) Class.forName(
- PROPERTIES_EDITOR_CLASS_NAME).newInstance();
- } catch (Exception e) {
- // Use default editor otherwise
- textEditor = new TextEditor();
- }
- textEditor.init(site, newEditorInput);
- } else {
- System.err.println("the site " + site);
- }
-
- MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
- EclipsePropertiesEditorResource readOnly =
- new EclipsePropertiesEditorResource(UIUtils.ROOT_LOCALE,
- new PropertiesSerializer(prefs.getSerializerConfig()),
- new PropertiesDeserializer(prefs.getDeserializerConfig()), textEditor);
- if (resourceLocationLabel != null) {
- readOnly.setResourceLocationLabel(resourceLocationLabel);
- }
- return new MessagesBundle(readOnly);
- }
- // we did not find it.
- return null;
- }
-
- private String getContents(InputStream in) throws IOException {
- Reader reader = new BufferedReader(
- new InputStreamReader(in));
- //, "ISO 8859-1");need to find actual name
- int ch;
- StringBuffer buffer = new StringBuffer();
- while ((ch = reader.read()) > -1) {
- buffer.append((char)ch);
- }
- in.close();
- return buffer.toString();
- }
-
- /**
- * The resource bundle can be either with the rest of the classes or
- * with the bundle resources.
- * @return
- */
- protected boolean resourceBundleIsInsideClasses() {
- IProject thisProj = getOpenedFile().getProject();
- Collection<String> srcs = getSourceFolderPathes(thisProj);
- String thisPath = getOpenedFile().getProjectRelativePath().toString();
- if (srcs != null) {
- for (String srcPath : srcs) {
- if (thisPath.startsWith(srcPath)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * @return The path of the base properties file. Relative to a source folder
- * or the root of the project if there is no source folder.
- * <p>
- * For example if the properties file is for the package
- * org.eclipse.ui.workbench.internal.messages.properties
- * The path return is org/eclipse/ui/workbench/internal/messages/properties
- * </p>
- */
- protected IPath getPropertiesPath() {
- IPath projRelative = super.basePathInsideNL == null
- ? super.getOpenedFile().getParent().getProjectRelativePath()
- : new Path(super.basePathInsideNL);
- return removePathToSourceFolder(projRelative)
- .append(getBaseName() + ".properties"); //NON-NLS-1$
- }
-
- /**
- * @param hostPluginProject The project in the workspace that is the host
- * plugin
- * @param propertiesBasePath The result of getPropertiesPath();
- * @return
- */
- protected IFile getPropertiesFile(
- IProject hostPluginProject, IPath propertiesBasePath) {
- //first look directly in the plugin resources:
- IResource r = hostPluginProject.findMember(propertiesBasePath);
- if (r != null && r.getType() == IResource.FILE) {
- return (IFile)r;
- }
-
- //second look into the source folders.
- Collection<String> srcPathes = getSourceFolderPathes(hostPluginProject);
- if (srcPathes != null) {
- for (String srcPath : srcPathes) {
- IFolder srcFolder = hostPluginProject.getFolder(
- new Path(srcPath));
- if (srcFolder.exists()) {
- r = srcFolder.findMember(propertiesBasePath);
- if (r != null && r.getType() == IResource.FILE) {
- return (IFile)r;
- }
- }
- }
- }
- return hostPluginProject.getFile(propertiesBasePath);
- }
- /**
- * Returns the content of the properties if they were located inside a jar
- * inside the plugin.
- *
- * @param hostPluginProject
- * @param propertiesBasePath
- * @return The content and location label of the properties or null if
- * they could not be found.
- */
- private String[] getJarredPropertiesAndResourceLocationLabel(
- IProject hostPluginProject, IPath propertiesBasePath) {
- //third look into the jars:
- Collection<String> libPathes = getLibPathes(hostPluginProject);
- if (libPathes != null) {
- String entryName = propertiesBasePath.toString();
- for (String libPath : libPathes) {
- if (libPath.endsWith(".jar")) {
- IFile jar = hostPluginProject.getFile(new Path(libPath));
- if (jar.exists()) {
- File file = jar.getRawLocation().toFile();
- if (file.exists()) {
- JarFile jf = null;
- try {
- jf = new JarFile(file);
- JarEntry je = jf.getJarEntry(entryName);
- if (je != null) {
- String content =
- getContents(jf.getInputStream(je));
- String location =
- jar.getFullPath().toString()
- + "!/" + entryName;
- return new String[] {content, location};
- }
- } catch (IOException e) {
-
- } finally {
- if (jf != null) {
- try {
- jf.close();
- } catch (IOException e) {
- // swallow
- }
- }
- }
- }
- }
- }
- }
- }
-
- return null;//could not find it.
- }
-
- /**
- * Redo a little parser utility in order to not depend on pde.
- *
- * @param proj
- * @return The pathes of the source folders extracted from
- * the .classpath file
- */
- protected static Collection<String> getSourceFolderPathes(IProject proj) {
- return getClasspathEntryPathes(proj, "src"); //$NON-NLS-1$
- }
- /**
- * Redo a little parser utility in order to not depend on pde.
- *
- * @param proj
- * @return The pathes of the source folders extracted from the
- * .classpath file
- */
- protected Collection<String> getLibPathes(IProject proj) {
- return getClasspathEntryPathes(proj, "lib"); //$NON-NLS-1$
- }
- protected static Collection<String> getClasspathEntryPathes(
- IProject proj, String classpathentryKind) {
- IFile classpathRes = proj.getFile(".classpath");
- if (!classpathRes.exists()) {
- return null;
- }
- Collection<String> res = new ArrayList<String>();
-
- //<classpathentry kind="src" path="src"/>
- InputStream in = null;
- try {
- in = ((IFile)classpathRes).getContents();
- //supposedly in utf-8. should not really matter for us
- Reader r = new InputStreamReader(in, "UTF-8");
- LineNumberReader lnr = new LineNumberReader(r);
- String line = lnr.readLine();
- while (line != null) {
- if (line.indexOf("<classpathentry ") != -1
- && line.indexOf(" kind=\"" + classpathentryKind + "\" ")
- != -1) {
- int pathIndex = line.indexOf(" path=\"");
- if (pathIndex != -1) {
- int secondQuoteIndex = line.indexOf('\"',
- pathIndex + " path=\"".length());
- if (secondQuoteIndex != -1) {
- res.add(line.substring(
- pathIndex + " path=\"".length(),
- secondQuoteIndex));
- }
- }
- }
- line = lnr.readLine();
- }
- lnr.close();
- r.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) try { in.close(); } catch (IOException e) {}
- }
- return res;
- }
-
- /**
- * A dummy editor input represents text that may be shown in a
- * text editor, but cannot be saved as it does not relate to a modifiable
- * file.
- */
- private class DummyEditorInput implements IStorageEditorInput, IStorage {
-
- /**
- * the error messages as a Java inputStream.
- */
- private String _contents;
-
- /**
- * the name of the input
- */
- private String _name;
-
- /**
- * the tooltip text, optional
- */
- private String _toolTipText;
-
- /**
- * Simplified constructor that does not need
- * a tooltip, the name is used instead
- * @param contents
- * @param _name
- */
- public DummyEditorInput(
- String contents, String name, boolean isEditable) {
- this(contents, name, name);
- }
- /**
- * The complete constructor.
- * @param contents the contents to be given to the editor
- * @param _name the name of the input
- * @param tipText the text to be shown when a tooltip
- * is requested on the editor name part.
- */
- public DummyEditorInput(String contents, String name, String tipText) {
- super();
- _contents = contents;
- _name = name;
- _toolTipText = tipText;
- }
-
- /**
- * we return the instance itself.
- */
- public IStorage getStorage() throws CoreException {
- return this;
- }
-
- /**
- * the input never exists
- */
- public boolean exists() {
- return false;
- }
-
- /**
- * nothing in particular for now.
- */
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- /**
- * the name given in constructor
- */
- public String getName() {
- return _name;
- }
-
- /**
- * our input is not persistable.
- */
- public IPersistableElement getPersistable() {
- return null;
- }
-
- /**
- * returns the value passed as an argument in constructor.
- */
- public String getToolTipText() {
- return _toolTipText;
- }
-
- /**
- * we do not adapt much.
- */
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- // the methods to implement as an IStorage object
-
- /**
- * the contents
- */
- public InputStream getContents() throws CoreException {
- return new ByteArrayInputStream(_contents.getBytes());
- }
-
- /**
- * this is not used and should not impact the IDE.
- */
- public IPath getFullPath() {
- return null;
- }
-
- /**
- * the text is always readonly.
- */
- public boolean isReadOnly() {
- return true;
- }
- }
-
- /**
- * Called when using an nl structure.
- * We need to find out whether the variant is in fact a folder.
- * If we locate a folder inside the project with this name we assume it is
- * not a variant.
- * <p>
- * This method is overridden inside the NLFragment thing as we need to
- * check 2 projects over there:
- * the host-plugin project and the current project.
- * </p>
- * @param possibleVariant
- * @return
- */
- protected boolean isExistingFirstFolderForDefaultLocale(String folderName) {
- IProject thisProject = getOpenedFile().getProject();
- if (thisProject == null) {
- return false;
- }
- boolean res = thisProject.getFolder(folderName).exists();
- if (res) {
- //that is in the same plugin.
- return true;
- }
- IProject developpedProject =
- getHostPluginProjectDevelopedInWorkspace();
- if (developpedProject != null) {
- res = developpedProject.getFolder(folderName).exists();
- if (res) {
- //that is in the same plugin.
- return true;
- }
- //we don't need to look in the jar:
- //when this method is called it is because we
- //are looking inside the nl folder which is never inside a source
- //folder or inside a jar.
- return false;
- }
- //ok no project in the workspace with this.
- //maybe in the bundle
- Bundle bundle = getHostPluginBundleInPlatform();
- if (bundle != null) {
- if (bundle.getEntry(folderName) != null) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Look for the host plugin inside the workspace itself.
- * Caches the result.
- * @return
- */
- private IProject getHostPluginProjectDevelopedInWorkspace() {
- if (hostPluginInWorkspaceWasLookedFor) {
- return hostPluginInWorkspace;
- } else {
- hostPluginInWorkspaceWasLookedFor = true;
- }
-
- IProject thisProject = getOpenedFile().getProject();
- if (thisProject == null) {
- return null;
- }
- try {
- //now look in the workspace for the host-plugin as a
- //developed project:
- IResource[] members =
- ((IContainer)thisProject.getParent()).members();
- for (int i = 0 ; i < members.length ; i++ ) {
- IResource childRes = members[i];
- if (childRes != thisProject
- && childRes.getType() == IResource.PROJECT) {
- String bundle = MessagesBundleGroupFactory.getBundleId(childRes);
- if (_fragmentHostID.equals(bundle)) {
- hostPluginInWorkspace = (IProject)childRes;
- return hostPluginInWorkspace;
- }
- }
- }
- //ok no project in the workspace with this.
- } catch (Exception e) {
-
- }
- return null;
- }
- private Bundle getHostPluginBundleInPlatform() {
- Bundle bundle = Platform.getBundle(_fragmentHostID);
- if (bundle != null) {
- return bundle;
- }
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/NLPluginBundleGroupStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/NLPluginBundleGroupStrategy.java
deleted file mode 100644
index d9e7a5a2..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/bundle/NLPluginBundleGroupStrategy.java
+++ /dev/null
@@ -1,423 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.bundle;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.ui.IEditorSite;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * MessagesBundle group strategies for dealing with Eclipse "NL"
- * directory structure within a plugin.
- * <p>
- * This class also falls back to the usual locales as suffixes
- * by calling the methods defined in DefaultBundleGroupStrategy.
- * It enables us to re-use directly this class to support loading resources located
- * inside a fragment. In other words:
- * this class is extended by {@link NLFragmentBundleGroupStrategy}.
- * </p>
- * <p>
- * Note it is unclear how
- * <p>
- *
- *
- * @author Pascal Essiembre
- * @author Hugues Malphettes
- */
-public class NLPluginBundleGroupStrategy extends DefaultBundleGroupStrategy {
-
- private static Set<String> ISO_LANG_CODES = new HashSet<String>();
- private static Set<String> ISO_COUNTRY_CODES = new HashSet<String>();
- static {
- String[] isos = Locale.getISOLanguages();
- for (int i = 0; i < isos.length; i++) {
- ISO_LANG_CODES.add(isos[i]);
- }
- String[] isoc = Locale.getISOCountries();
- for (int i = 0; i < isoc.length; i++) {
- ISO_COUNTRY_CODES.add(isoc[i]);
- }
- }
-
- private IProject[] associatedFragmentProjects;
- protected IFolder nlFolder;
- protected String basePathInsideNL;
-
- /**
- * @param nlFolder when null, this strategy behaves just like
- * DefaultBundleGroupStrategy. Otherwise it is a localized file
- * using the "nl" folder. Most complete example found so far:
- * http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.html
- * Although it applies to properties files too:
- * See figure 1 of:
- * http://www.eclipse.org/articles/Article-Speak-The-Local-Language/article.html
- */
- public NLPluginBundleGroupStrategy(IEditorSite site, IFile file,
- IFolder nlFolder, IProject[] associatedFragmentProjects) {
- super(site, file);
- this.nlFolder = nlFolder;
- this.associatedFragmentProjects = associatedFragmentProjects;
- }
-
-
- /**
- * @param nlFolder when null, this strategy behaves just like
- * DefaultBundleGroupStrategy. Otherwise it is a localized file
- * using the "nl" folder. Most complete example found so far:
- * http://dev.eclipse.org/mhonarc/lists/babel-dev/msg00111.html
- * Although it applies to properties files too:
- * See figure 1 of:
- * http://www.eclipse.org/articles/Article-Speak-The-Local-Language/article.html
- */
- public NLPluginBundleGroupStrategy(IEditorSite site, IFile file,
- IFolder nlFolder) {
- super(site, file);
- this.nlFolder = nlFolder;
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy#loadBundles()
- */
- public MessagesBundle[] loadMessagesBundles() {
- final Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
- Collection<IFolder> nlFolders = nlFolder != null ? new ArrayList<IFolder>() : null;
- if (associatedFragmentProjects != null) {
- IPath basePath = null;
- //true when the file opened is located in a source folder.
- //in that case we don't support the nl structure
- //as at runtime it only applies to resources that ae no inside the classes.
- boolean fileIsInsideClasses = false;
- boolean fileHasLocaleSuffix = false;
- if (nlFolder == null) {
- //in that case the project relative path to the container
- //of the properties file is always the one here.
- basePath = removePathToSourceFolder(
- getOpenedFile().getParent().getProjectRelativePath());
- fileIsInsideClasses = !basePath.equals(
- getOpenedFile().getParent().getProjectRelativePath());
- fileHasLocaleSuffix = !getOpenedFile().getName().equals(
- super.getBaseName() + ".properties");
- if (!fileHasLocaleSuffix && !fileIsInsideClasses) {
- basePathInsideNL = basePath.toString();
- }
- } else {
- //the file opened is inside an nl folder.
- //this will compute the basePathInsideNL:
- extractLocale(getOpenedFile(), true);
- basePath = new Path(basePathInsideNL);
- }
-
- for (int i = 0; i < associatedFragmentProjects.length; i++) {
- IProject frag = associatedFragmentProjects[i];
- if (fileIsInsideClasses) {
- Collection<String> srcPathes = NLFragmentBundleGroupStrategy.getSourceFolderPathes(frag);
- if (srcPathes != null) {
- //for each source folder, collect the resources we can find
- //with the suffix scheme:
- for (String srcPath : srcPathes) {
- IPath container = new Path(srcPath).append(basePath);
- super.collectBundlesInContainer(getContainer(frag, basePath), bundles);
- }
- }
- //also search directly in the bundle:
- super.collectBundlesInContainer(getContainer(frag, basePath), bundles);
- } else {
- IFolder nl = frag.getFolder("nl");
- if (nl != null && nl.exists()) {
- if (nlFolders == null) {
- nlFolders = new ArrayList<IFolder>();
- }
- nlFolders.add(nl);
- }
- if (!fileHasLocaleSuffix) {
- //when the file is not inside nl and has no locale suffix
- //and is not inside the classes
- //it means we look both inside nl and with the suffix
- //based scheme:
- super.collectBundlesInContainer(getContainer(frag, basePath), bundles);
- }
- }
- }
-
- }
-
- if (nlFolders == null) {
- collectBundlesInContainer(getOpenedFile().getParent(), bundles);
- return bundles.toArray(EMPTY_BUNDLES);
- }
- if (nlFolder != null) {
- nlFolders.add(nlFolder);
- }
- //get the nl directory.
- //navigate the entire directory from there
- //and look for the file with the same file names.
- final String name = getOpenedFile().getName();
- IResourceVisitor visitor = new IResourceVisitor() {
- public boolean visit(IResource resource) throws CoreException {
- if (resource.getType() == IResource.FILE
- && resource.getName().equals(name)
- && !getOpenedFile().equals(resource)) {
- Locale locale = extractLocale((IFile)resource, false);
- if (locale != null && UIUtils.isDisplayed(locale)) {
- bundles.add(createBundle(locale, resource));
- }
- }
- return true;
- }
- };
- try {
- Locale locale = extractLocale(getOpenedFile(), true);
- if (UIUtils.isDisplayed(locale)) {
- bundles.add(createBundle(locale, getOpenedFile()));
- }
- for (IFolder nlFolder : nlFolders) {
- nlFolder.accept(visitor);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- //also look for files based on the suffix mechanism
- //if we have located the root locale file:
- IContainer container = null;
- for (MessagesBundle mb : bundles) {
- if (mb.getLocale() == null || mb.getLocale().equals(UIUtils.ROOT_LOCALE)) {
- Object src = mb.getResource().getSource();
- if (src instanceof IFile) {
- container = ((IFile)src).getParent();
- }
- break;
- }
- }
- if (container != null) {
- super.collectBundlesInContainer(container, bundles);
- }
- return bundles.toArray(EMPTY_BUNDLES);
- }
-
- private static final IContainer getContainer(IProject proj, IPath containerPath) {
- if (containerPath.segmentCount() == 0) {
- return proj;
- }
- return proj.getFolder(containerPath);
- }
-
- /**
- * @param baseContainerPath
- * @return if the path starts with a path to a source folder this method
- * returns the same path minus the source folder.
- */
- protected IPath removePathToSourceFolder(IPath baseContainerPath) {
- Collection<String> srcPathes = NLFragmentBundleGroupStrategy.getSourceFolderPathes(
- getOpenedFile().getProject());
- if (srcPathes == null) {
- return baseContainerPath;
- }
- String projRelativePathStr = baseContainerPath.toString();
- for (String srcPath : srcPathes) {
- if (projRelativePathStr.startsWith(srcPath)) {
- return new Path(projRelativePathStr.substring(srcPath.length()));
- }
- }
- return baseContainerPath;
- }
-
-
- /**
- * Tries to parse a locale directly from the file.
- * Support the locale as a string suffix and the locale as part of a path
- * inside an nl folder.
- * @param file
- * @return The parsed locale or null if no locale could be parsed.
- * If the locale is the root locale UIBableUtils.ROOT_LOCALE is returned.
- */
- private Locale extractLocale(IFile file, boolean docomputeBasePath) {
- IFolder nl = MessagesBundleGroupFactory.getNLFolder(file);
- String path = file.getFullPath().removeFileExtension().toString();
- if (nl == null) {
- int ind = path.indexOf('_');
- int maxInd = path.length()-1;
- while (ind != -1 && ind < maxInd) {
- String possibleLocale = path.substring(ind+1);
- Locale res = BabelUtils.parseLocale(possibleLocale);
- if (res != null) {
- return res;
- }
- ind = path.indexOf('_', ind+1);
- }
-
- return null;
- }
- //the locale is not in the suffix.
- //let's look into the nl folder:
- int ind = path.lastIndexOf("/nl/");
- //so the remaining String is a composition of the base path of
- //the default properties and the path that reflects the locale.
- //for example:
- //if the default file is /theproject/icons/img.gif
- //then the french localized file is /theproject/nl/FR/icons/img.gif
- //so we need to separate fr from icons/img.gif to locate the base file.
- //unfortunately we need to look into the values of the tokens
- //to guess whether they are part of the path leading to the default file
- //or part of the path that reflects the locale.
- //we simply look whether 'icons' exist.
-
- // in other words: using folders is risky and users could
- //crash eclipse using locales that conflict with pathes to resources.
-
- //so we must verify that the first 2 or 3 tokens after nl are valid ISO codes.
- //the variant is the most problematic issue
- //as it is not standardized.
-
- //we rely on finding the base properties
- //to decide whether 'icons' is a variant or a folder.
-
-
-
- if (ind != -1) {
- ind = ind + "/nl/".length();
- int lastFolder = path.lastIndexOf('/');
- if (lastFolder == ind) {
- return UIUtils.ROOT_LOCALE;
- }
- path = path.substring(ind, lastFolder);
- StringTokenizer tokens = new StringTokenizer(path, "/", false);
- switch (tokens.countTokens()) {
- case 0:
- return null;
- case 1:
- String lang = tokens.nextToken();
- if (!ISO_LANG_CODES.contains(lang)) {
- return null;
- }
- if (docomputeBasePath) {
- basePathInsideNL = "";
- return new Locale(lang);
- } else if ("".equals(basePathInsideNL)) {
- return new Locale(lang);
- } else {
- return null;
- }
- case 2:
- lang = tokens.nextToken();
- if (!ISO_LANG_CODES.contains(lang)) {
- return null;
- }
- String country = tokens.nextToken();
- if (!ISO_COUNTRY_CODES.contains(country)) {
- //in this case, this might be the beginning
- //of the base path.
- if (isExistingFirstFolderForDefaultLocale(country)) {
- if (docomputeBasePath) {
- basePathInsideNL = country;
- return new Locale(lang);
- } else if (basePathInsideNL.equals(country)) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- }
- if (docomputeBasePath) {
- basePathInsideNL = "";
- return new Locale(lang, country);
- } else if (basePathInsideNL.equals(country)) {
- return new Locale(lang, country);
- } else {
- return null;
- }
- default:
- lang = tokens.nextToken();
- if (!ISO_LANG_CODES.contains(lang)) {
- return null;
- }
- country = tokens.nextToken();
- if (!ISO_COUNTRY_CODES.contains(country)) {
- if (isExistingFirstFolderForDefaultLocale(country)) {
- StringBuffer b = new StringBuffer(country);
- while (tokens.hasMoreTokens()) {
- b.append("/" + tokens.nextToken());
- }
- if (docomputeBasePath) {
- basePathInsideNL = b.toString();
- return new Locale(lang);
- } else if (basePathInsideNL.equals(b.toString())) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- }
- String variant = tokens.nextToken();
- if (isExistingFirstFolderForDefaultLocale(variant)) {
- StringBuffer b = new StringBuffer(variant);
- while (tokens.hasMoreTokens()) {
- b.append("/" + tokens.nextToken());
- }
- if (docomputeBasePath) {
- basePathInsideNL = b.toString();
- return new Locale(lang, country);
- } else if (basePathInsideNL.equals(b.toString())) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- StringBuffer b = new StringBuffer();
- while (tokens.hasMoreTokens()) {
- b.append("/" + tokens.nextToken());
- }
- if (docomputeBasePath) {
- basePathInsideNL = b.toString();
- return new Locale(lang, country, variant);
- } else if (basePathInsideNL.equals(b.toString())) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
- }
- return UIUtils.ROOT_LOCALE;
- }
-
- /**
- * Called when using an nl structure.<br/>
- * We need to find out whether the variant is in fact a folder.
- * If we locate a folder inside the project with this name we assume it is not a variant.
- * <p>
- * This method is overridden inside the NLFragment thing as we need to check
- * 2 projects over there: the host-plugin project and the current project.
- * </p>
- * @param possibleVariant
- * @return
- */
- protected boolean isExistingFirstFolderForDefaultLocale(String folderName) {
- return getOpenedFile().getProject().getFolder(folderName).exists();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/EntryLeftBanner.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/EntryLeftBanner.java
deleted file mode 100644
index a7b2cfa7..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/EntryLeftBanner.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n;
-
-import java.util.Locale;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions.FoldingAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.widgets.ActionButton;
-
-/**
- * Tree for displaying and navigating through resource bundle keys.
- * @author Pascal Essiembre
- */
-public class EntryLeftBanner extends Composite {
-
- /**
- * Constructor.
- * @param parent parent composite
- * @param keyTree key tree
- */
- public EntryLeftBanner(
- Composite parent,
- final I18NEntry i18NEntry) {
- super(parent, SWT.NONE);
-
- RowLayout layout = new RowLayout();
- setLayout(layout);
- layout.marginBottom = 0;
- layout.marginLeft = 0;
- layout.marginRight = 0;
- layout.marginTop = 0;
-
- final IAction foldAction = new FoldingAction(i18NEntry);
- new ActionButton(this, foldAction);
-
-// Button commentButton = new Button(compos, SWT.TOGGLE);
-// commentButton.setImage(UIUtils.getImage("comment.gif"));
-
-
- Link localeLabel = new Link(this, SWT.NONE);
- localeLabel.setFont(UIUtils.createFont(localeLabel, SWT.BOLD));
-
- boolean isEditable = i18NEntry.isEditable();
- localeLabel.setText("<a>" + UIUtils.getDisplayName(
- i18NEntry.getLocale()) + "</a>" + (!isEditable
- ? " (" + MessagesEditorPlugin.getString(
- "editor.readOnly") + ")" : ""));
-
- localeLabel.setToolTipText(
- MessagesEditorPlugin.getString("editor.i18nentry.resourcelocation",
- i18NEntry.getResourceLocationLabel())); //$NON-NLS-1$
-
- localeLabel.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- i18NEntry.getResourceBundleEditor().setActivePage(
- i18NEntry.getLocale());
- }
- });
-
- //TODO have "show country flags" in preferences.
- //TODO have text aligned bottom next to flag icon.
- Image countryIcon = loadCountryIcon(i18NEntry.getLocale());
- if (countryIcon != null) {
- Label imgLabel = new Label(this, SWT.NONE);
- imgLabel.setImage(countryIcon);
- }
- }
-
-
- /**
- * Loads country icon based on locale country.
- * @param countryLocale the locale on which to grab the country
- * @return an image, or <code>null</code> if no match could be made
- */
- private Image loadCountryIcon(Locale countryLocale) {
- Image image = null;
- String countryCode = null;
- if (countryLocale != null && countryLocale.getCountry() != null) {
- countryCode = countryLocale.getCountry().toLowerCase();
- }
- if (countryCode != null && countryCode.length() > 0) {
- String imageName = "countries/" + //$NON-NLS-1$
- countryCode.toLowerCase() + ".gif"; //$NON-NLS-1$
- image = UIUtils.getImage(imageName);
- }
-// if (image == null) {
-// image = UIUtils.getImage("countries/blank.gif"); //$NON-NLS-1$
-// }
- return image;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/EntryRightBanner.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/EntryRightBanner.java
deleted file mode 100644
index 7335a62a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/EntryRightBanner.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.babel.core.message.checks.DuplicateValueCheck;
-import org.eclipse.babel.core.message.checks.IMessageCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions.ShowDuplicateAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions.ShowMissingAction;
-
-/**
- * Tree for displaying and navigating through resource bundle keys.
- * @author Pascal Essiembre
- */
-public class EntryRightBanner extends Composite {
-
- private Label colon;
- private Label warningIcon;
- private final Map actionByMarkerIds = new HashMap();
- private final ToolBarManager toolBarMgr = new ToolBarManager(SWT.FLAT);
- private final MessagesEditor editor;
- private final I18NEntry i18nEntry;
- private final Locale locale;
-
- /**
- * Constructor.
- * @param parent parent composite
- * @param keyTree key tree
- */
- public EntryRightBanner(
- Composite parent,
- final I18NEntry i18nEntry) {
- super(parent, SWT.NONE);
- this.i18nEntry = i18nEntry;
- this.locale = i18nEntry.getLocale();
- this.editor = i18nEntry.getResourceBundleEditor();
-
- RowLayout layout = new RowLayout();
- setLayout(layout);
- layout.marginBottom = 0;
- layout.marginLeft = 0;
- layout.marginRight = 0;
- layout.marginTop = 0;
-
- warningIcon = new Label(this, SWT.NONE);
- warningIcon.setImage(
- PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJS_WARN_TSK));
- warningIcon.setVisible(false);
- warningIcon.setToolTipText("This locale has warnings.");
-
- colon = new Label(this, SWT.NONE);
- colon.setText(":");
- colon.setVisible(false);
-
- toolBarMgr.createControl(this);
- toolBarMgr.update(true);
-
- editor.addChangeListener(
- new MessagesEditorChangeAdapter() {
- public void selectedKeyChanged(String oldKey, String newKey) {
- updateMarkers();
-
- }
- });
- editor.getMarkers().addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- updateMarkers();
- }
- });
- }
-
- /**
- * @param warningIcon
- * @param colon
- */
- private void updateMarkers() {
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
- public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()
-// && !editor.getMarkerManager().isDisposed()) {
- boolean isMarked = false;
- toolBarMgr.removeAll();
- actionByMarkerIds.clear();
- String key = editor.getSelectedKey();
- Collection<IMessageCheck> checks = editor.getMarkers().getFailedChecks(
- key, locale);
- if (checks != null) {
- for (IMessageCheck check : checks) {
- Action action = getCheckAction(key, check);
- if (action != null) {
- toolBarMgr.add(action);
- toolBarMgr.update(true);
- getParent().layout(true, true);
- isMarked = true;
- }
- }
- }
- toolBarMgr.update(true);
- getParent().layout(true, true);
-
- warningIcon.setVisible(isMarked);
- colon.setVisible(isMarked);
- }
-// }
- });
-
- }
-
- private Action getCheckAction(
- String key, IMessageCheck check) {
- if (check instanceof MissingValueCheck) {
- return new ShowMissingAction(key, locale);
- } else if (check instanceof DuplicateValueCheck) {
- return new ShowDuplicateAction(
- ((DuplicateValueCheck) check).getDuplicateKeys(),
- key, locale);
- }
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/I18NEntry.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/I18NEntry.java
deleted file mode 100644
index 5a881e29..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/I18NEntry.java
+++ /dev/null
@@ -1,827 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n;
-
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.Message;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CBanner;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.widgets.NullableText;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-
-/**
- * Tree for displaying and navigating through resource bundle keys.
- * @author Pascal Essiembre
- */
-public class I18NEntry extends Composite {
-
- private final MessagesEditor editor;
- private final String bundleGroupId;
- private final String projectName;
- private final Locale locale;
-
- private boolean expanded = true;
- private NullableText textBox;
- private CBanner banner;
- private String focusGainedText;
-
- /**
- * Constructor.
- * @param parent parent composite
- * @param keyTree key tree
- */
- public I18NEntry(
- Composite parent,
- final MessagesEditor editor,
- final Locale locale) {
- super(parent, SWT.NONE);
- this.editor = editor;
- this.locale = locale;
- this.bundleGroupId = editor.getBundleGroup().getResourceBundleId();
- this.projectName = editor.getBundleGroup().getProjectName();
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 0;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
-
- setLayout(gridLayout);
- GridData gd = new GridData(GridData.FILL_BOTH);
-// gd.heightHint = 80;
- setLayoutData(gd);
-
- banner = new CBanner(this, SWT.NONE);
-
- Control bannerLeft = new EntryLeftBanner(banner, this);// createBannerLeft(banner);
- Control bannerRight = new EntryRightBanner(banner, this);// createBannerRight(banner);
-
- GridData gridData = new GridData();
- gridData.horizontalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
-
- banner.setLeft(bannerLeft);
- banner.setRight(bannerRight);
-// banner.setRightWidth(300);
- banner.setSimple(false);
- banner.setLayoutData(gridData);
-
-
- createTextbox();
-
- }
-
-
-
-
- public MessagesEditor getResourceBundleEditor() {
- return editor;
- }
-
-
-
- public void setExpanded(boolean expanded) {
- this.expanded = expanded;
- textBox.setVisible(expanded);
-
- if (expanded) {
- GridData gridData = new GridData();
- gridData.verticalAlignment = GridData.FILL;
- gridData.grabExcessVerticalSpace = true;
- gridData.horizontalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
- gridData.heightHint = UIUtils.getHeightInChars(textBox, 3);
- textBox.setLayoutData(gridData);
-
- GridData gd = new GridData(GridData.FILL_BOTH);
-// gd.heightHint = 80;
- setLayoutData(gd);
- getParent().pack();
- getParent().layout(true, true);
-
- } else {
- GridData gridData = ((GridData) textBox.getLayoutData());
- gridData.verticalAlignment = GridData.BEGINNING;
- gridData.grabExcessVerticalSpace = false;
- textBox.setLayoutData(gridData);
-
- gridData = (GridData) getLayoutData();
- gridData.heightHint = banner.getSize().y;
- gridData.verticalAlignment = GridData.BEGINNING;
- gridData.grabExcessVerticalSpace = false;
- setLayoutData(gridData);
-
- getParent().pack();
- getParent().layout(true, true);
- }
-
- }
- public boolean getExpanded() {
- return expanded;
- }
-
- public Locale getLocale() {
- return locale;
- }
-
- public boolean isEditable() {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId);
- IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale);
- return ((TextEditor) bundle.getResource().getSource()).isEditable();
- }
-
- public String getResourceLocationLabel() {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId);
- IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale);
- return bundle.getResource().getResourceLocationLabel();
- }
-
-// /*default*/ Text getTextBox() {
-// return textBox;
-// }
-
-
- /**
- * @param editor
- * @param locale
- */
- private void createTextbox() {
- textBox = new NullableText(
- this, SWT.MULTI | SWT.WRAP |
- SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- textBox.setEnabled(false);
- textBox.setOrientation(UIUtils.getOrientation(locale));
-
-
- textBox.addFocusListener(new FocusListener() {
- public void focusGained(FocusEvent event) {
- focusGainedText = textBox.getText();
- }
- public void focusLost(FocusEvent event) {
- updateModel();
- }
- });
- //-- Setup read-only textbox --
- //that is the case if the corresponding editor is itself read-only.
- //it happens when the corresponding resource is defined inside the
- //target-platform for example
- textBox.setEditable(isEditable());
-
- //--- Handle tab key ---
- //TODO add a preference property listener and add/remove this listener
- textBox.addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent event) {
-// if (!MsgEditorPreferences.getFieldTabInserts()
-// && event.character == SWT.TAB) {
-// event.doit = true;
-// }
- }
- });
-
- // Handle dirtyness
- textBox.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- // Text field has changed: make editor dirty if not already
- if (!BabelUtils.equals(focusGainedText, textBox.getText())) {
- // Make the editor dirty if not already. If it is,
- // we wait until field focus lost (or save) to
- // update it completely.
- if (!editor.isDirty()) {
-// textEditor.isDirty();
- updateModel();
-// int caretPosition = eventBox.getCaretPosition();
-// updateBundleOnChanges();
-// eventBox.setSelection(caretPosition);
- }
- //autoDetectRequiredFont(eventBox.getText());
- }
- }
- });
-// // Eric Fettweis : new listener to automatically change the font
-// textBox.addModifyListener(new ModifyListener() {
-//
-// public void modifyText(ModifyEvent e) {
-// String text = textBox.getText();
-// Font f = textBox.getFont();
-// String fontName = getBestFont(f.getFontData()[0].getName(), text);
-// if(fontName!=null){
-// f = getSWTFont(f, fontName);
-// textBox.setFont(f);
-// }
-// }
-//
-// });
-
-
-
-
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void selectedKeyChanged(String oldKey, String newKey) {
- updateKey(newKey);
- }
- });
-
- }
-
- void updateKey(String key) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
- projectName).getMessagesBundleGroup(bundleGroupId);
- boolean isKey = key != null && messagesBundleGroup.isMessageKey(key);
- textBox.setEnabled(isKey);
- if (isKey) {
- IMessage entry = messagesBundleGroup.getMessage(key, locale);
- if (entry == null || entry.getValue() == null) {
- textBox.setText(null);
- // commentedCheckbox.setSelection(false);
- } else {
- // commentedCheckbox.setSelection(bundleEntry.isCommented());
- textBox.setText(entry.getValue());
- }
- } else {
- textBox.setText(null);
- }
- }
-
- private void updateModel() {
- if (editor.getSelectedKey() != null) {
- if (!BabelUtils.equals(focusGainedText, textBox.getText())) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId);
- String key = editor.getSelectedKey();
- IMessage entry = messagesBundleGroup.getMessage(key, locale);
- if (entry == null) {
- entry = new Message(key, locale);
- messagesBundleGroup.getMessagesBundle(locale).addMessage(entry);
- }
- entry.setText(textBox.getText());
- }
- }
- }
-}
-
-
-
-
-
-
-
-
-//TODO Grab and Apply font fix:
-///**
-// * Represents a data entry section for a bundle entry.
-// * @author Pascal Essiembre ([email protected])
-// * @version $Author: pessiembr $ $Revision: 1.3 $ $Date: 2008/01/11 04:15:15 $
-// */
-//public class BundleEntryComposite extends Composite {
-//
-// /*default*/ final ResourceManager resourceManager;
-// /*default*/ final Locale locale;
-// private final Font boldFont;
-// private final Font smallFont;
-//
-// /*default*/ Text textBox;
-// private Button commentedCheckbox;
-// private Button gotoButton;
-// private Button duplButton;
-// private Button simButton;
-//
-// /*default*/ String activeKey;
-// /*default*/ String textBeforeUpdate;
-//
-// /*default*/ DuplicateValuesVisitor duplVisitor;
-// /*default*/ SimilarValuesVisitor similarVisitor;
-//
-//
-// /**
-// * Constructor.
-// * @param parent parent composite
-// * @param resourceManager resource manager
-// * @param locale locale for this bundle entry
-// */
-// public BundleEntryComposite(
-// final Composite parent,
-// final ResourceManager resourceManager,
-// final Locale locale) {
-//
-// super(parent, SWT.NONE);
-// this.resourceManager = resourceManager;
-// this.locale = locale;
-//
-// this.boldFont = UIUtils.createFont(this, SWT.BOLD, 0);
-// this.smallFont = UIUtils.createFont(SWT.NONE, -1);
-//
-// GridLayout gridLayout = new GridLayout(1, false);
-// gridLayout.horizontalSpacing = 0;
-// gridLayout.verticalSpacing = 2;
-// gridLayout.marginWidth = 0;
-// gridLayout.marginHeight = 0;
-//
-// createLabelRow();
-// createTextRow();
-//
-// setLayout(gridLayout);
-// GridData gd = new GridData(GridData.FILL_BOTH);
-// gd.heightHint = 80;
-// setLayoutData(gd);
-//
-//
-// }
-//
-// /**
-// * Update bundles if the value of the active key changed.
-// */
-// public void updateBundleOnChanges(){
-// if (activeKey != null) {
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// Message entry = messagesBundleGroup.getBundleEntry(locale, activeKey);
-// boolean commentedSelected = commentedCheckbox.getSelection();
-// String textBoxValue = textBox.getText();
-//
-// if (entry == null || !textBoxValue.equals(entry.getValue())
-// || entry.isCommented() != commentedSelected) {
-// String comment = null;
-// if (entry != null) {
-// comment = entry.getComment();
-// }
-// messagesBundleGroup.addBundleEntry(locale, new Message(
-// activeKey,
-// textBox.getText(),
-// comment,
-// commentedSelected));
-// }
-// }
-// }
-//
-// /**
-// * @see org.eclipse.swt.widgets.Widget#dispose()
-// */
-// public void dispose() {
-// super.dispose();
-// boldFont.dispose();
-// smallFont.dispose();
-//
-// //Addition by Eric Fettweis
-// for(Iterator it = swtFontCache.values().iterator();it.hasNext();){
-// Font font = (Font) it.next();
-// font.dispose();
-// }
-// swtFontCache.clear();
-// }
-//
-// /**
-// * Gets the locale associated with this bundle entry
-// * @return a locale
-// */
-// public Locale getLocale() {
-// return locale;
-// }
-//
-// /**
-// * Sets a selection in the text box.
-// * @param start starting position to select
-// * @param end ending position to select
-// */
-// public void setTextSelection(int start, int end) {
-// textBox.setSelection(start, end);
-// }
-//
-// /**
-// * Refreshes the text field value with value matching given key.
-// * @param key key used to grab value
-// */
-// public void refresh(String key) {
-// activeKey = key;
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// if (key != null && messagesBundleGroup.isKey(key)) {
-// Message bundleEntry = messagesBundleGroup.getBundleEntry(locale, key);
-// SourceEditor sourceEditor = resourceManager.getSourceEditor(locale);
-// if (bundleEntry == null) {
-// textBox.setText(""); //$NON-NLS-1$
-// commentedCheckbox.setSelection(false);
-// } else {
-// commentedCheckbox.setSelection(bundleEntry.isCommented());
-// String value = bundleEntry.getValue();
-// textBox.setText(value);
-// }
-// commentedCheckbox.setEnabled(!sourceEditor.isReadOnly());
-// textBox.setEnabled(!sourceEditor.isReadOnly());
-// gotoButton.setEnabled(true);
-// if (MsgEditorPreferences.getReportDuplicateValues()) {
-// findDuplicates(bundleEntry);
-// } else {
-// duplVisitor = null;
-// }
-// if (MsgEditorPreferences.getReportSimilarValues()) {
-// findSimilar(bundleEntry);
-// } else {
-// similarVisitor = null;
-// }
-// } else {
-// commentedCheckbox.setSelection(false);
-// commentedCheckbox.setEnabled(false);
-// textBox.setText(""); //$NON-NLS-1$
-// textBox.setEnabled(false);
-// gotoButton.setEnabled(false);
-// duplButton.setVisible(false);
-// simButton.setVisible(false);
-// }
-// resetCommented();
-// }
-//
-// private void findSimilar(Message bundleEntry) {
-// ProximityAnalyzer analyzer;
-// if (MsgEditorPreferences.getReportSimilarValuesLevensthein()) {
-// analyzer = LevenshteinDistanceAnalyzer.getInstance();
-// } else {
-// analyzer = WordCountAnalyzer.getInstance();
-// }
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// if (similarVisitor == null) {
-// similarVisitor = new SimilarValuesVisitor();
-// }
-// similarVisitor.setProximityAnalyzer(analyzer);
-// similarVisitor.clear();
-// messagesBundleGroup.getBundle(locale).accept(similarVisitor, bundleEntry);
-// if (duplVisitor != null) {
-// similarVisitor.getSimilars().removeAll(duplVisitor.getDuplicates());
-// }
-// simButton.setVisible(similarVisitor.getSimilars().size() > 0);
-// }
-//
-// private void findDuplicates(Message bundleEntry) {
-// MessagesBundleGroup messagesBundleGroup = resourceManager.getBundleGroup();
-// if (duplVisitor == null) {
-// duplVisitor = new DuplicateValuesVisitor();
-// }
-// duplVisitor.clear();
-// messagesBundleGroup.getBundle(locale).accept(duplVisitor, bundleEntry);
-// duplButton.setVisible(duplVisitor.getDuplicates().size() > 0);
-// }
-//
-//
-// /**
-// * Creates the text field label, icon, and commented check box.
-// */
-// private void createLabelRow() {
-// Composite labelComposite = new Composite(this, SWT.NONE);
-// GridLayout gridLayout = new GridLayout();
-// gridLayout.numColumns = 6;
-// gridLayout.horizontalSpacing = 5;
-// gridLayout.verticalSpacing = 0;
-// gridLayout.marginWidth = 0;
-// gridLayout.marginHeight = 0;
-// labelComposite.setLayout(gridLayout);
-// labelComposite.setLayoutData(
-// new GridData(GridData.FILL_HORIZONTAL));
-//
-// // Locale text
-// Label txtLabel = new Label(labelComposite, SWT.NONE);
-// txtLabel.setText(" " + //$NON-NLS-1$
-// UIUtils.getDisplayName(locale) + " "); //$NON-NLS-1$
-// txtLabel.setFont(boldFont);
-// GridData gridData = new GridData();
-//
-// // Similar button
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// gridData.grabExcessHorizontalSpace = true;
-// simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
-// simButton.setImage(UIUtils.getImage("similar.gif")); //$NON-NLS-1$
-// simButton.setLayoutData(gridData);
-// simButton.setVisible(false);
-// simButton.setToolTipText(
-// RBEPlugin.getString("value.similar.tooltip")); //$NON-NLS-1$
-// simButton.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// String head = RBEPlugin.getString(
-// "dialog.similar.head"); //$NON-NLS-1$
-// String body = RBEPlugin.getString(
-// "dialog.similar.body", activeKey, //$NON-NLS-1$
-// UIUtils.getDisplayName(locale));
-// body += "\n\n"; //$NON-NLS-1$
-// for (Iterator iter = similarVisitor.getSimilars().iterator();
-// iter.hasNext();) {
-// body += " " //$NON-NLS-1$
-// + ((Message) iter.next()).getKey()
-// + "\n"; //$NON-NLS-1$
-// }
-// MessageDialog.openInformation(getShell(), head, body);
-// }
-// });
-//
-// // Duplicate button
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
-// duplButton.setImage(UIUtils.getImage("duplicate.gif")); //$NON-NLS-1$
-// duplButton.setLayoutData(gridData);
-// duplButton.setVisible(false);
-// duplButton.setToolTipText(
-// RBEPlugin.getString("value.duplicate.tooltip")); //$NON-NLS-1$
-//
-// duplButton.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// String head = RBEPlugin.getString(
-// "dialog.identical.head"); //$NON-NLS-1$
-// String body = RBEPlugin.getString(
-// "dialog.identical.body", activeKey, //$NON-NLS-1$
-// UIUtils.getDisplayName(locale));
-// body += "\n\n"; //$NON-NLS-1$
-// for (Iterator iter = duplVisitor.getDuplicates().iterator();
-// iter.hasNext();) {
-// body += " " //$NON-NLS-1$
-// + ((Message) iter.next()).getKey()
-// + "\n"; //$NON-NLS-1$
-// }
-// MessageDialog.openInformation(getShell(), head, body);
-// }
-// });
-//
-// // Commented checkbox
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// //gridData.grabExcessHorizontalSpace = true;
-// commentedCheckbox = new Button(
-// labelComposite, SWT.CHECK);
-// commentedCheckbox.setText("#"); //$NON-NLS-1$
-// commentedCheckbox.setFont(smallFont);
-// commentedCheckbox.setLayoutData(gridData);
-// commentedCheckbox.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// resetCommented();
-// updateBundleOnChanges();
-// }
-// });
-// commentedCheckbox.setEnabled(false);
-//
-// // Country flag
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// Label imgLabel = new Label(labelComposite, SWT.NONE);
-// imgLabel.setLayoutData(gridData);
-// imgLabel.setImage(loadCountryIcon(locale));
-//
-// // Goto button
-// gridData = new GridData();
-// gridData.horizontalAlignment = GridData.END;
-// gotoButton = new Button(
-// labelComposite, SWT.ARROW | SWT.RIGHT);
-// gotoButton.setToolTipText(
-// RBEPlugin.getString("value.goto.tooltip")); //$NON-NLS-1$
-// gotoButton.setEnabled(false);
-// gotoButton.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// ITextEditor editor = resourceManager.getSourceEditor(
-// locale).getEditor();
-// Object activeEditor =
-// editor.getSite().getPage().getActiveEditor();
-// if (activeEditor instanceof MessagesEditor) {
-// ((MessagesEditor) activeEditor).setActivePage(locale);
-// }
-// }
-// });
-// gotoButton.setLayoutData(gridData);
-// }
-// /**
-// * Creates the text row.
-// */
-// private void createTextRow() {
-// textBox = new Text(this, SWT.MULTI | SWT.WRAP |
-// SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
-// textBox.setEnabled(false);
-// //Addition by Eric FETTWEIS
-// //Note that this does not seem to work... It would however be usefull for arabic and some other languages
-// textBox.setOrientation(getOrientation(locale));
-//
-// GridData gridData = new GridData();
-// gridData.verticalAlignment = GridData.FILL;
-// gridData.grabExcessVerticalSpace = true;
-// gridData.horizontalAlignment = GridData.FILL;
-// gridData.grabExcessHorizontalSpace = true;
-// gridData.heightHint = UIUtils.getHeightInChars(textBox, 3);
-// textBox.setLayoutData(gridData);
-// textBox.addFocusListener(new FocusListener() {
-// public void focusGained(FocusEvent event) {
-// textBeforeUpdate = textBox.getText();
-// }
-// public void focusLost(FocusEvent event) {
-// updateBundleOnChanges();
-// }
-// });
-// //TODO add a preference property listener and add/remove this listener
-// textBox.addTraverseListener(new TraverseListener() {
-// public void keyTraversed(TraverseEvent event) {
-// if (!MsgEditorPreferences.getFieldTabInserts()
-// && event.character == SWT.TAB) {
-// event.doit = true;
-// }
-// }
-// });
-// textBox.addKeyListener(new KeyAdapter() {
-// public void keyReleased(KeyEvent event) {
-// Text eventBox = (Text) event.widget;
-// final ITextEditor editor = resourceManager.getSourceEditor(
-// locale).getEditor();
-// // Text field has changed: make editor dirty if not already
-// if (textBeforeUpdate != null
-// && !textBeforeUpdate.equals(eventBox.getText())) {
-// // Make the editor dirty if not already. If it is,
-// // we wait until field focus lost (or save) to
-// // update it completely.
-// if (!editor.isDirty()) {
-// int caretPosition = eventBox.getCaretPosition();
-// updateBundleOnChanges();
-// eventBox.setSelection(caretPosition);
-// }
-// //autoDetectRequiredFont(eventBox.getText());
-// }
-// }
-// });
-// // Eric Fettweis : new listener to automatically change the font
-// textBox.addModifyListener(new ModifyListener() {
-//
-// public void modifyText(ModifyEvent e) {
-// String text = textBox.getText();
-// Font f = textBox.getFont();
-// String fontName = getBestFont(f.getFontData()[0].getName(), text);
-// if(fontName!=null){
-// f = getSWTFont(f, fontName);
-// textBox.setFont(f);
-// }
-// }
-//
-// });
-// }
-//
-//
-//
-// /*default*/ void resetCommented() {
-// if (commentedCheckbox.getSelection()) {
-// commentedCheckbox.setToolTipText(
-// RBEPlugin.getString("value.uncomment.tooltip"));//$NON-NLS-1$
-// textBox.setForeground(
-// getDisplay().getSystemColor(SWT.COLOR_GRAY));
-// } else {
-// commentedCheckbox.setToolTipText(
-// RBEPlugin.getString("value.comment.tooltip"));//$NON-NLS-1$
-// textBox.setForeground(null);
-// }
-// }
-//
-//
-//
-// /** Additions by Eric FETTWEIS */
-// /*private void autoDetectRequiredFont(String value) {
-// Font f = getFont();
-// FontData[] data = f.getFontData();
-// boolean resetFont = true;
-// for (int i = 0; i < data.length; i++) {
-// java.awt.Font test = new java.awt.Font(data[i].getName(), java.awt.Font.PLAIN, 12);
-// if(test.canDisplayUpTo(value)==-1){
-// resetFont = false;
-// break;
-// }
-// }
-// if(resetFont){
-// String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
-// for (int i = 0; i < fonts.length; i++) {
-// java.awt.Font fnt = new java.awt.Font(fonts[i],java.awt.Font.PLAIN,12);
-// if(fnt.canDisplayUpTo(value)==-1){
-// textBox.setFont(createFont(fonts[i]));
-// break;
-// }
-// }
-// }
-//}*/
-// /**
-// * Holds swt fonts used for the textBox.
-// */
-// private Map swtFontCache = new HashMap();
-//
-// /**
-// * Gets a font by its name. The resulting font is build based on the baseFont parameter.
-// * The font is retrieved from the swtFontCache, or created if needed.
-// * @param baseFont the current font used to build the new one.
-// * Only the name of the new font will differ fromm the original one.
-// * @parama baseFont a font
-// * @param name the new font name
-// * @return a font with the same style and size as the original.
-// */
-// private Font getSWTFont(Font baseFont, String name){
-// Font font = (Font) swtFontCache.get(name);
-// if(font==null){
-// font = createFont(baseFont, getDisplay(), name);
-// swtFontCache.put(name, font);
-// }
-// return font;
-// }
-// /**
-// * Gets the name of the font which will be the best to display a String.
-// * All installed fonts are searched. If a font can display the entire string, then it is retuned immediately.
-// * Otherwise, the font returned is the one which can display properly the longest substring possible from the argument value.
-// * @param baseFontName a font to be tested before any other. It will be the current font used by a widget.
-// * @param value the string to be displayed.
-// * @return a font name
-// */
-// private static String getBestFont(String baseFontName, String value){
-// if(canFullyDisplay(baseFontName, value)) return baseFontName;
-// String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
-// String fontName=null;
-// int currentScore = 0;
-// for (int i = 0; i < fonts.length; i++) {
-// int score = canDisplayUpTo(fonts[i], value);
-// if(score==-1){//no need to loop further
-// fontName=fonts[i];
-// break;
-// }
-// if(score>currentScore){
-// fontName=fonts[i];
-// currentScore = score;
-// }
-// }
-//
-// return fontName;
-// }
-//
-// /**
-// * A cache holding an instance of every AWT font tested.
-// */
-// private static Map awtFontCache = new HashMap();
-//
-// /**
-// * Creates a variation from an original font, by changing the face name.
-// * @param baseFont the original font
-// * @param display the current display
-// * @param name the new font face name
-// * @return a new Font
-// */
-// private static Font createFont(Font baseFont, Display display, String name){
-// FontData[] fontData = baseFont.getFontData();
-// for (int i = 0; i < fontData.length; i++) {
-// fontData[i].setName(name);
-// }
-// return new Font(display, fontData);
-// }
-// /**
-// * Can a font display correctly an entire string ?
-// * @param fontName the font name
-// * @param value the string to be displayed
-// * @return
-// */
-// private static boolean canFullyDisplay(String fontName, String value){
-// return canDisplayUpTo(fontName, value)==-1;
-// }
-//
-// /**
-// * Test the number of characters from a given String that a font can display correctly.
-// * @param fontName the name of the font
-// * @param value the value to be displayed
-// * @return the number of characters that can be displayed, or -1 if the entire string can be displayed successfuly.
-// * @see java.aw.Font#canDisplayUpTo(String)
-// */
-// private static int canDisplayUpTo(String fontName, String value){
-// java.awt.Font font = getAWTFont(fontName);
-// return font.canDisplayUpTo(value);
-// }
-// /**
-// * Returns a cached or new AWT font by its name.
-// * If the font needs to be created, its style will be Font.PLAIN and its size will be 12.
-// * @param name teh font name
-// * @return an AWT Font
-// */
-// private static java.awt.Font getAWTFont(String name){
-// java.awt.Font font = (java.awt.Font) awtFontCache.get(name);
-// if(font==null){
-// font = new java.awt.Font(name, java.awt.Font.PLAIN, 12);
-// awtFontCache.put(name, font);
-// }
-// return font;
-// }
-
-//}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/I18NPage.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/I18NPage.java
deleted file mode 100644
index 6ff0c7e4..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/I18NPage.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-
-/**
- * Internationalization page where one can edit all resource bundle entries
- * at once for all supported locales.
- * @author Pascal Essiembre
- */
-public class I18NPage extends ScrolledComposite implements ISelectionProvider {
-
- /** Minimum height of text fields. */
- private static final int TEXT_MIN_HEIGHT = 90;
-
- private final MessagesEditor editor;
- private final SideNavComposite keysComposite;
- private final Composite valuesComposite;
- private final Map<Locale,I18NEntry> entryComposites = new HashMap<Locale,I18NEntry>();
-
-// private Composite parent;
- private boolean keyTreeVisible = true;
-
-// private final StackLayout layout = new StackLayout();
- private final SashForm sashForm;
-
-
- /**
- * Constructor.
- * @param parent parent component.
- * @param style style to apply to this component
- * @param resourceMediator resource manager
- */
- public I18NPage(
- Composite parent, int style,
- final MessagesEditor editor) {
- super(parent, style);
- this.editor = editor;
- sashForm = new SashForm(this, SWT.SMOOTH);
- sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
- editor.getEditorSite().getPage().addPartListener(new IPartListener(){
- public void partActivated(IWorkbenchPart part) {
- if (part == editor) {
- sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
- }
- }
- public void partDeactivated(IWorkbenchPart part) {
- if (part == editor) {
- sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
-
- }
- }
- public void partBroughtToTop(IWorkbenchPart part) {}
- public void partClosed(IWorkbenchPart part) {}
- public void partOpened(IWorkbenchPart part) {}
- });
-
- setContent(sashForm);
-
-
- keysComposite = new SideNavComposite(sashForm, editor);
-
- valuesComposite = createValuesComposite(sashForm);
-
-
- sashForm.setWeights(new int[]{25, 75});
-
- setExpandHorizontal(true);
- setExpandVertical(true);
- setMinWidth(400);
-
- RBManager instance = RBManager.getInstance(editor.getBundleGroup().getProjectName());
- instance.addMessagesEditorListener(new IMessagesEditorListener() {
-
- public void onSave() {
- // TODO Auto-generated method stub
-
- }
-
- public void onModify() {
- // TODO Auto-generated method stub
- }
-
- public void onResourceChanged(IMessagesBundle bundle) {
- I18NEntry i18nEntry = entryComposites.get(bundle.getLocale());
- if (i18nEntry != null && !getSelection().isEmpty()) {
- i18nEntry.updateKey(String.valueOf(((IStructuredSelection)getSelection()).getFirstElement()));
- }
- }
-
- });
- }
-
- /**
- * @see org.eclipse.swt.widgets.Widget#dispose()
- */
- public void dispose() {
- keysComposite.dispose();
- super.dispose();
- }
-
- public void setKeyTreeVisible(boolean visible) {
- keyTreeVisible = visible;
- if (visible) {
- sashForm.setMaximizedControl(null);
- } else {
- sashForm.setMaximizedControl(valuesComposite);
- }
- for (IMessagesEditorChangeListener listener : editor.getChangeListeners()) {
- listener.keyTreeVisibleChanged(visible);
- }
- }
-
- public boolean isKeyTreeVisible() {
- return keyTreeVisible;
- }
-
-
- private Composite createValuesComposite(SashForm parent) {
- final ScrolledComposite scrolledComposite =
- new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
- scrolledComposite.setExpandHorizontal(true);
- scrolledComposite.setExpandVertical(true);
- scrolledComposite.setSize(SWT.DEFAULT, 100);
-
- final Composite entriesComposite =
- new Composite(scrolledComposite, SWT.BORDER);
- scrolledComposite.setContent(entriesComposite);
- scrolledComposite.setMinSize(entriesComposite.computeSize(
- SWT.DEFAULT,
- editor.getBundleGroup().getLocales().length * TEXT_MIN_HEIGHT));
-
-
- entriesComposite.setLayout(new GridLayout(1, false));
- Locale[] locales = editor.getBundleGroup().getLocales();
- UIUtils.sortLocales(locales);
- locales = UIUtils.filterLocales(locales);
- for (int i = 0; i < locales.length; i++) {
- Locale locale = locales[i];
- I18NEntry i18NEntry = new I18NEntry(
- entriesComposite, editor, locale);
-// entryComposite.addFocusListener(localBehaviour);
- entryComposites.put(locale, i18NEntry);
- }
-
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void selectedKeyChanged(String oldKey, String newKey) {
- boolean isKey =
- newKey != null && editor.getBundleGroup().isMessageKey(newKey);
-// scrolledComposite.setBackground(isKey);
- }
- });
-
-
-
- return scrolledComposite;
- }
-
- public void selectLocale(Locale locale) {
- Collection<Locale> locales = entryComposites.keySet();
- for (Locale entryLocale : locales) {
- I18NEntry entry =
- entryComposites.get(entryLocale);
-
- //TODO add equivalent method on entry composite
-// Text textBox = entry.getTextBox();
-// if (BabelUtils.equals(locale, entryLocale)) {
-// textBox.selectAll();
-// textBox.setFocus();
-// } else {
-// textBox.clearSelection();
-// }
- }
- }
-
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- keysComposite.getTreeViewer().addSelectionChangedListener(listener);
-
- }
-
- public ISelection getSelection() {
- return keysComposite.getTreeViewer().getSelection();
- }
-
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- keysComposite.getTreeViewer().removeSelectionChangedListener(listener);
- }
-
- public void setSelection(ISelection selection) {
- keysComposite.getTreeViewer().setSelection(selection);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/SideNavComposite.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/SideNavComposite.java
deleted file mode 100644
index aa536290..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/SideNavComposite.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n;
-
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.KeyTreeContributor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.CollapseAllAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.ExpandAllAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.FlatModelAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.TreeModelAction;
-
-/**
- * Tree for displaying and navigating through resource bundle keys.
- * @author Pascal Essiembre
- */
-public class SideNavComposite extends Composite {
-
- /** Key Tree Viewer. */
- private TreeViewer treeViewer;
-
- private MessagesEditor editor;
-
- /**
- * Constructor.
- * @param parent parent composite
- * @param keyTree key tree
- */
- public SideNavComposite(
- Composite parent, final MessagesEditor editor) {
- super(parent, SWT.BORDER);
- this.editor = editor;
-
- // Create a toolbar.
- ToolBarManager toolBarMgr = new ToolBarManager(SWT.FLAT);
- ToolBar toolBar = toolBarMgr.createControl(this);
-
-
- this.treeViewer = new TreeViewer(this,
- SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
-
-
- setLayout(new GridLayout(1, false));
-
- GridData gid;
-
- gid = new GridData();
- gid.horizontalAlignment = GridData.END;
- gid.verticalAlignment = GridData.BEGINNING;
- toolBar.setLayoutData(gid);
- toolBarMgr.add(new TreeModelAction(editor, treeViewer));
- toolBarMgr.add(new FlatModelAction(editor, treeViewer));
- toolBarMgr.add(new Separator());
- toolBarMgr.add(new ExpandAllAction(editor, treeViewer));
- toolBarMgr.add(new CollapseAllAction(editor, treeViewer));
- toolBarMgr.update(true);
-
- //TODO have two toolbars, one left-align, and one right, with drop
- //down menu
-// initListener();
-
-// createTopSection();
- createKeyTree();
- new SideNavTextBoxComposite(this, editor);
- }
-
-// private void initListener() {
-// IResourceChangeListener listener = new IResourceChangeListener() {
-//
-// public void resourceChanged(IResourceChangeEvent event) {
-// if (!Boolean.valueOf(System.getProperty("dirty"))) {
-// createKeyTree();
-// }
-// }
-// };
-//
-// ResourcesPlugin.getWorkspace().addResourceChangeListener(listener, IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE);
-//
-// }
-
- /**
- * Gets the tree viewer.
- * @return tree viewer
- */
- public TreeViewer getTreeViewer() {
- return treeViewer;
- }
-
- /**
- * @see org.eclipse.swt.widgets.Widget#dispose()
- */
- public void dispose() {
- super.dispose();
- }
-
- /**
- * Creates the middle (tree) section of this composite.
- */
- private void createKeyTree() {
-
- GridData gridData = new GridData();
- gridData.verticalAlignment = GridData.FILL;
- gridData.grabExcessVerticalSpace = true;
- gridData.horizontalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
-
-
- KeyTreeContributor treeContributor = new KeyTreeContributor(editor);
- treeContributor.contribute(treeViewer);
- treeViewer.getTree().setLayoutData(gridData);
-
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/SideNavTextBoxComposite.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/SideNavTextBoxComposite.java
deleted file mode 100644
index a83d7d80..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/SideNavTextBoxComposite.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n;
-
-import org.eclipse.babel.core.message.tree.visitor.NodePathRegexVisitor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-/**
- * Tree for displaying and navigating through resource bundle keys.
- * @author Pascal Essiembre
- */
-public class SideNavTextBoxComposite extends Composite {
-
-
- /** Whether to synchronize the add text box with tree key selection. */
- private boolean syncAddTextBox = true;
-
- /** Text box to add a new key. */
- private Text addTextBox;
-
- private MessagesEditor editor;
-
- /**
- * Constructor.
- * @param parent parent composite
- * @param keyTree key tree
- */
- public SideNavTextBoxComposite(
- Composite parent,
- final MessagesEditor editor) {
- super(parent, SWT.NONE);
- this.editor = editor;
-
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 2;
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 0;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- setLayout(gridLayout);
- GridData gridData = new GridData();
- gridData.horizontalAlignment = GridData.FILL;
- gridData.verticalAlignment = GridData.CENTER;
- gridData.grabExcessHorizontalSpace = true;
- setLayoutData(gridData);
-
- // Text box
- addTextBox = new Text(this, SWT.BORDER);
- gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- gridData.horizontalAlignment = GridData.FILL;
- addTextBox.setLayoutData(gridData);
-
- // Add button
- final Button addButton = new Button(this, SWT.PUSH);
- addButton.setText(MessagesEditorPlugin.getString("key.add")); //$NON-NLS-1$
- addButton.setEnabled(false);
- addButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- addKey(addTextBox.getText());
- }
- });
-
- addTextBox.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- String key = addTextBox.getText();
- if (event.character == SWT.CR && isNewKey(key)) {
- addKey(key);
- } else if (key.length() > 0){
- NodePathRegexVisitor visitor = new NodePathRegexVisitor(
- "^" + key + ".*"); //$NON-NLS-1$//$NON-NLS-2$
- editor.getKeyTreeModel().accept(visitor, null);
- IKeyTreeNode node = visitor.getKeyTreeNode();
- if (node != null) {
- syncAddTextBox = false;
- editor.setSelectedKey(node.getMessageKey());
- }
- }
- }
- });
- addTextBox.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent event) {
- addButton.setEnabled(isNewKey(addTextBox.getText()));
- }
- });
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void selectedKeyChanged(String oldKey, String newKey) {
- if (syncAddTextBox && newKey != null) {
- addTextBox.setText(newKey);
- }
- syncAddTextBox = true;
- }
- });
-
- }
-
- private void addKey(String key) {
- editor.getBundleGroup().addMessages(key);
- editor.setSelectedKey(key);
- }
-
- private boolean isNewKey(String key) {
- return !editor.getBundleGroup().isMessageKey(key) && key.length() > 0;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/FoldingAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/FoldingAction.java
deleted file mode 100644
index 89a7aa6f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/FoldingAction.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.I18NEntry;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class FoldingAction extends Action {
-
- private final I18NEntry i18NEntry;
- private boolean expanded;
-
- /**
- *
- */
- public FoldingAction(I18NEntry i18NEntry) {
- super();
- this.i18NEntry = i18NEntry;
- this.expanded = i18NEntry.getExpanded();
- setText("Collapse");
- setImageDescriptor(
- UIUtils.getImageDescriptor("minus.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- if (i18NEntry.getExpanded()) {
- setImageDescriptor(UIUtils.getImageDescriptor("plus.gif"));
- i18NEntry.setExpanded(false);
- } else {
- setImageDescriptor(UIUtils.getImageDescriptor("minus.gif"));
- i18NEntry.setExpanded(true);
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowDuplicateAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowDuplicateAction.java
deleted file mode 100644
index d8e35f88..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowDuplicateAction.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions;
-
-import java.util.Locale;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class ShowDuplicateAction extends Action {
-
- private final String[] keys;
- private final String key;
- private final Locale locale;
-
- /**
- *
- */
- public ShowDuplicateAction(String[] keys, String key, Locale locale) {
- super();
- this.keys = keys;
- this.key = key;
- this.locale = locale;
- setText("Show duplicate keys.");
- setImageDescriptor(
- UIUtils.getImageDescriptor("duplicate.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- //TODO have preference for whether to do cross locale checking
- StringBuffer buf = new StringBuffer("\"" + key + "\" (" + UIUtils.getDisplayName(locale) + ") has the same "
- + "value as the following key(s): \n\n");
- for (int i = 0; i < keys.length; i++) {
- String duplKey = keys[i];
- if (!key.equals(duplKey)) {
- buf.append(" � ");
- buf.append(duplKey);
- buf.append(" (" + UIUtils.getDisplayName(locale) + ")");
- buf.append("\n");
- }
- }
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(),
- "Duplicate value",
- buf.toString());
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowMissingAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowMissingAction.java
deleted file mode 100644
index 156617b8..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowMissingAction.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions;
-
-import java.util.Locale;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class ShowMissingAction extends Action {
-
- /**
- *
- */
- public ShowMissingAction(String key, Locale locale) {
- super();
- setText("Key missing a value.");
- setImageDescriptor(
- UIUtils.getImageDescriptor("empty.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(),
- "Missing value",
- "Key missing a value");
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowSimilarAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowSimilarAction.java
deleted file mode 100644
index 5c4efcd1..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/i18n/actions/ShowSimilarAction.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.i18n.actions;
-
-import java.util.Locale;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class ShowSimilarAction extends Action {
-
- private final String[] keys;
- private final String key;
- private final Locale locale;
-
- /**
- *
- */
- public ShowSimilarAction(String[] keys, String key, Locale locale) {
- super();
- this.keys = keys;
- this.key = key;
- this.locale = locale;
- setText("Show similar keys.");
- setImageDescriptor(
- UIUtils.getImageDescriptor("similar.gif"));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- StringBuffer buf = new StringBuffer("\"" + key + "\" (" + UIUtils.getDisplayName(locale) + ") has similar "
- + "value as the following key(s): \n\n");
- for (int i = 0; i < keys.length; i++) {
- String similarKey = keys[i];
- if (!key.equals(similarKey)) {
- buf.append(" � ");
- buf.append(similarKey);
- buf.append(" (" + UIUtils.getDisplayName(locale) + ")");
- buf.append("\n");
- }
- }
- MessageDialog.openInformation(
- Display.getDefault().getActiveShell(),
- "Similar value",
- buf.toString());
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/plugin/MessagesEditorPlugin.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/plugin/MessagesEditorPlugin.java
deleted file mode 100644
index ea393ac1..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/plugin/MessagesEditorPlugin.java
+++ /dev/null
@@ -1,302 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.plugin;
-
-import java.io.IOException;
-import java.net.URL;
-import java.text.MessageFormat;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.MissingResourceException;
-import java.util.PropertyResourceBundle;
-import java.util.ResourceBundle;
-import java.util.Set;
-
-import org.eclipse.babel.core.message.AbstractIFileChangeListener;
-import org.eclipse.babel.core.message.AbstractIFileChangeListener.IFileChangeListenerRegistry;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.eclipselabs.pde.nls.internal.ui.model.ResourceBundleModel;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.builder.ToggleNatureAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- * @author Pascal Essiembre ([email protected])
- */
-public class MessagesEditorPlugin extends AbstractUIPlugin implements IFileChangeListenerRegistry {
-
- //TODO move somewhere more appropriate
- public static final String MARKER_TYPE =
- "org.eclipse.babel.editor.nlsproblem"; //$NON-NLS-1$
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.babel.editor";
-
- // The shared instance
- private static MessagesEditorPlugin plugin;
-
- //Resource bundle.
- //TODO Use Eclipse MessagesBundle instead.
- private ResourceBundle resourceBundle;
-
- //The resource change litener for the entire plugin.
- //objects interested in changes in the workspace resources must
- //subscribe to this listener by calling subscribe/unsubscribe on the plugin.
- private IResourceChangeListener resourceChangeListener;
-
- //The map of resource change subscribers.
- //The key is the full path of the resource listened. The value as set of SimpleResourceChangeListners
- //private Map<String,Set<SimpleResourceChangeListners>> resourceChangeSubscribers;
- private Map<String,Set<AbstractIFileChangeListener>> resourceChangeSubscribers;
-
- private ResourceBundleModel model;
-
- /**
- * The constructor
- */
- public MessagesEditorPlugin() {
- resourceChangeSubscribers = new HashMap<String,Set<AbstractIFileChangeListener>>();
- }
-
- /**
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(
- * org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
-
- //make sure the rbe nature and builder are set on java projects
- //if that is what the users prefers.
- if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) {
- ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
- }
-
- //TODO replace deprecated
- try {
- URL messagesUrl = FileLocator.find(getBundle(),
- new Path("$nl$/messages.properties"), null);//$NON-NLS-1$
- if(messagesUrl != null) {
- resourceBundle = new PropertyResourceBundle(
- messagesUrl.openStream());
- }
- } catch (IOException x) {
- resourceBundle = null;
- }
-
- //the unique file change listener
- resourceChangeListener = new IResourceChangeListener() {
- public void resourceChanged(IResourceChangeEvent event) {
- IResource resource = event.getResource();
- if (resource != null) {
- String fullpath = resource.getFullPath().toString();
- Set<AbstractIFileChangeListener> listeners = resourceChangeSubscribers.get(fullpath);
- if (listeners != null) {
- AbstractIFileChangeListener[] larray = listeners.toArray(new AbstractIFileChangeListener[0]);//avoid concurrency issues. kindof.
- for (int i = 0; i < larray.length; i++) {
- larray[i].listenedFileChanged(event);
- }
- }
- }
- }
- };
- ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener);
- }
-
- /**
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(
- * org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
- super.stop(context);
- }
-
- /**
- * @param rcl Adds a subscriber to a resource change event.
- */
- public void subscribe(AbstractIFileChangeListener fileChangeListener) {
- synchronized (resourceChangeListener) {
- String channel = fileChangeListener.getListenedFileFullPath();
- Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers.get(channel);
- if (channelListeners == null) {
- channelListeners = new HashSet<AbstractIFileChangeListener>();
- resourceChangeSubscribers.put(channel, channelListeners);
- }
- channelListeners.add(fileChangeListener);
- }
- }
-
- /**
- * @param rcl Removes a subscriber to a resource change event.
- */
- public void unsubscribe(AbstractIFileChangeListener fileChangeListener) {
- synchronized (resourceChangeListener) {
- String channel = fileChangeListener.getListenedFileFullPath();
- Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers.get(channel);
- if (channelListeners != null
- && channelListeners.remove(fileChangeListener)
- && channelListeners.isEmpty()) {
- //nobody left listening to this file.
- resourceChangeSubscribers.remove(channel);
- }
- }
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static MessagesEditorPlugin getDefault() {
- return plugin;
- }
-
- //--------------------------------------------------------------------------
- //TODO Better way/location for these methods?
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @return localized string corresponding to key
- */
- public static String getString(String key) {
- ResourceBundle bundle =
- MessagesEditorPlugin.getDefault().getResourceBundle();
- try {
- return (bundle != null) ? bundle.getString(key) : key;
- } catch (MissingResourceException e) {
- return key;
- }
- }
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1) {
- return MessageFormat.format(getString(key), new Object[]{arg1});
- }
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime first argument to replace in key value
- * @param arg2 runtime second argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1, String arg2) {
- return MessageFormat.format(
- getString(key), new Object[]{arg1, arg2});
- }
-
- /**
- * Returns the string from the plugin's resource bundle,
- * or 'key' if not found.
- * @param key the key for which to fetch a localized text
- * @param arg1 runtime argument to replace in key value
- * @param arg2 runtime second argument to replace in key value
- * @param arg3 runtime third argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(
- String key, String arg1, String arg2, String arg3) {
- return MessageFormat.format(
- getString(key), new Object[]{arg1, arg2, arg3});
- }
-
- /**
- * Returns the plugin's resource bundle.
- * @return resource bundle
- */
- protected ResourceBundle getResourceBundle() {
- return resourceBundle;
- }
-
- // Stefan's activator methods:
-
- /**
- * Returns an image descriptor for the given icon filename.
- *
- * @param filename the icon filename relative to the icons path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String filename) {
- String iconPath = "icons/"; //$NON-NLS-1$
- return imageDescriptorFromPlugin(PLUGIN_ID, iconPath + filename);
- }
-
- public static ResourceBundleModel getModel(IProgressMonitor monitor) {
- if (plugin.model == null) {
- plugin.model = new ResourceBundleModel(monitor);
- }
- return plugin.model;
- }
-
- public static void disposeModel() {
- if (plugin != null) {
- plugin.model = null;
- }
- }
-
- // Logging
-
- /**
- * Adds the given exception to the log.
- *
- * @param e the exception to log
- * @return the logged status
- */
- public static IStatus log(Throwable e) {
- return log(new Status(IStatus.ERROR, PLUGIN_ID, 0, "Internal error.", e));
- }
-
- /**
- * Adds the given exception to the log.
- *
- * @param exception the exception to log
- * @return the logged status
- */
- public static IStatus log(String message, Throwable exception) {
- return log(new Status(IStatus.ERROR, PLUGIN_ID, -1, message, exception));
- }
-
- /**
- * Adds the given <code>IStatus</code> to the log.
- *
- * @param status the status to log
- * @return the logged status
- */
- public static IStatus log(IStatus status) {
- getDefault().getLog().log(status);
- return status;
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/plugin/Startup.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/plugin/Startup.java
deleted file mode 100644
index dbbc21ef..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/plugin/Startup.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.plugin;
-
-import org.eclipse.ui.IStartup;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class Startup implements IStartup {
-
- /**
- * @see org.eclipse.ui.IStartup#earlyStartup()
- */
- public void earlyStartup() {
- //done.
-// System.out.println("Starting up. "
-// + "TODO: Register nature with every project and listen for new "
-// + "projects???");
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/AbstractPrefPage.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/AbstractPrefPage.java
deleted file mode 100644
index 285efe09..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/AbstractPrefPage.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * Plugin base preference page.
- * @author Pascal Essiembre ([email protected])
- */
-public abstract class AbstractPrefPage extends PreferencePage implements
- IWorkbenchPreferencePage {
-
- /** Number of pixels per field indentation */
- protected final int indentPixels = 20;
-
- /** Controls with errors in them. */
- protected final Map<Text,String> errors = new HashMap<Text,String>();
-
- /**
- * Constructor.
- */
- public AbstractPrefPage() {
- super();
- }
-
- /**
- * @see org.eclipse.ui.IWorkbenchPreferencePage
- * #init(org.eclipse.ui.IWorkbench)
- */
- public void init(IWorkbench workbench) {
- setPreferenceStore(
- MessagesEditorPlugin.getDefault().getPreferenceStore());
- }
-
- protected Composite createFieldComposite(Composite parent) {
- return createFieldComposite(parent, 0);
- }
- protected Composite createFieldComposite(Composite parent, int indent) {
- Composite composite = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = new GridLayout(2, false);
- gridLayout.marginWidth = indent;
- gridLayout.marginHeight = 0;
- gridLayout.verticalSpacing = 0;
- composite.setLayout(gridLayout);
- return composite;
- }
-
- protected class IntTextValidatorKeyListener extends KeyAdapter {
-
- private String errMsg = null;
-
- /**
- * Constructor.
- * @param errMsg error message
- */
- public IntTextValidatorKeyListener(String errMsg) {
- super();
- this.errMsg = errMsg;
- }
- /**
- * @see org.eclipse.swt.events.KeyAdapter#keyPressed(
- * org.eclipse.swt.events.KeyEvent)
- */
- public void keyReleased(KeyEvent event) {
- Text text = (Text) event.widget;
- String value = text.getText();
- event.doit = value.matches("^\\d*$"); //$NON-NLS-1$
- if (event.doit) {
- errors.remove(text);
- if (errors.isEmpty()) {
- setErrorMessage(null);
- setValid(true);
- } else {
- setErrorMessage(
- (String) errors.values().iterator().next());
- }
- } else {
- errors.put(text, errMsg);
- setErrorMessage(errMsg);
- setValid(false);
- }
- }
- }
-
- protected class DoubleTextValidatorKeyListener extends KeyAdapter {
-
- private String errMsg;
- private double minValue;
- private double maxValue;
-
- /**
- * Constructor.
- * @param errMsg error message
- */
- public DoubleTextValidatorKeyListener(String errMsg) {
- super();
- this.errMsg = errMsg;
- }
- /**
- * Constructor.
- * @param errMsg error message
- * @param minValue minimum value (inclusive)
- * @param maxValue maximum value (inclusive)
- */
- public DoubleTextValidatorKeyListener(
- String errMsg, double minValue, double maxValue) {
- super();
- this.errMsg = errMsg;
- this.minValue = minValue;
- this.maxValue = maxValue;
- }
-
- /**
- * @see org.eclipse.swt.events.KeyAdapter#keyPressed(
- * org.eclipse.swt.events.KeyEvent)
- */
- public void keyReleased(KeyEvent event) {
- Text text = (Text) event.widget;
- String value = text.getText();
- boolean valid = value.length() > 0;
- if (valid) {
- valid = value.matches("^\\d*\\.?\\d*$"); //$NON-NLS-1$
- }
- if (valid && minValue != maxValue) {
- double doubleValue = Double.parseDouble(value);
- valid = doubleValue >= minValue && doubleValue <= maxValue;
- }
- event.doit = valid;
- if (event.doit) {
- errors.remove(text);
- if (errors.isEmpty()) {
- setErrorMessage(null);
- setValid(true);
- } else {
- setErrorMessage(errors.values().iterator().next());
- }
- } else {
- errors.put(text, errMsg);
- setErrorMessage(errMsg);
- setValid(false);
- }
- }
- }
-
- protected void setWidthInChars(Control field, int widthInChars) {
- GridData gd = new GridData();
- gd.widthHint = UIUtils.getWidthInChars(field, widthInChars);
- field.setLayoutData(gd);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/FormattingPrefPage.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/FormattingPrefPage.java
deleted file mode 100644
index d18b4f45..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/FormattingPrefPage.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * Plugin formatting preference page.
- * @author Pascal Essiembre ([email protected])
- */
-public class FormattingPrefPage extends AbstractPrefPage {
-
- /* Preference fields. */
- private Button showGeneratedBy;
-
- private Button convertUnicodeToEncoded;
- private Button convertUnicodeUpperCase;
-
- private Button alignEqualSigns;
- private Button ensureSpacesAroundEquals;
-
- private Button groupKeys;
- private Text groupLevelDeep;
- private Text groupLineBreaks;
- private Button groupAlignEqualSigns;
-
- private Button wrapLines;
- private Text wrapCharLimit;
- private Button wrapAlignEqualSigns;
- private Text wrapIndentSpaces;
- private Button wrapNewLine;
-
- private Button newLineTypeForce;
- private Button[] newLineTypes = new Button[3];
-
- private Button keepEmptyFields;
- private Button sortKeys;
-
- /**
- * Constructor.
- */
- public FormattingPrefPage() {
- super();
- }
-
- /**
- * @see org.eclipse.jface.preference.PreferencePage#createContents(
- * org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite field = null;
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, false));
-
- // Show generated by comment?
- field = createFieldComposite(composite);
- showGeneratedBy = new Button(field, SWT.CHECK);
- showGeneratedBy.setSelection(
- prefs.getBoolean(MsgEditorPreferences.SHOW_SUPPORT_ENABLED));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.showGeneratedBy")); //$NON-NLS-1$
-
- // Convert unicode to encoded?
- field = createFieldComposite(composite);
- convertUnicodeToEncoded = new Button(field, SWT.CHECK);
- convertUnicodeToEncoded.setSelection(
- prefs.getBoolean(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED));
- convertUnicodeToEncoded.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.convertUnicode")); //$NON-NLS-1$
-
- // Use upper case for encoded hexadecimal values?
- field = createFieldComposite(composite, indentPixels);
- convertUnicodeUpperCase = new Button(field, SWT.CHECK);
- convertUnicodeUpperCase.setSelection(prefs.getBoolean(
- MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.convertUnicode.upper"));//$NON-NLS-1$
-
- // Align equal signs?
- field = createFieldComposite(composite);
- alignEqualSigns = new Button(field, SWT.CHECK);
- alignEqualSigns.setSelection(
- prefs.getBoolean(MsgEditorPreferences.ALIGN_EQUALS_ENABLED));
- alignEqualSigns.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.alignEquals")); //$NON-NLS-1$
-
- field = createFieldComposite(composite);
- ensureSpacesAroundEquals = new Button(field, SWT.CHECK);
- ensureSpacesAroundEquals.setSelection(
- prefs.getBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.spacesAroundEquals")); //$NON-NLS-1$
-
- // Group keys?
- field = createFieldComposite(composite);
- groupKeys = new Button(field, SWT.CHECK);
- groupKeys.setSelection(prefs.getBoolean(MsgEditorPreferences.GROUP_KEYS_ENABLED));
- groupKeys.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.groupKeys")); //$NON-NLS-1$
-
- // Group keys by how many level deep?
- field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.levelDeep")); //$NON-NLS-1$
- groupLevelDeep = new Text(field, SWT.BORDER);
- groupLevelDeep.setText(prefs.getString(MsgEditorPreferences.GROUP_LEVEL_DEEP));
- groupLevelDeep.setTextLimit(2);
- setWidthInChars(groupLevelDeep, 2);
- groupLevelDeep.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.levelDeep.error"))); //$NON-NLS-1$
-
- // How many lines between groups?
- field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.linesBetween")); //$NON-NLS-1$
- groupLineBreaks = new Text(field, SWT.BORDER);
- groupLineBreaks.setText(
- prefs.getString(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT));
- groupLineBreaks.setTextLimit(2);
- setWidthInChars(groupLineBreaks, 2);
- groupLineBreaks.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.linesBetween.error"))); //$NON-NLS-1$
-
- // Align equal signs within groups?
- field = createFieldComposite(composite, indentPixels);
- groupAlignEqualSigns = new Button(field, SWT.CHECK);
- groupAlignEqualSigns.setSelection(
- prefs.getBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString(
- "prefs.groupAlignEquals")); //$NON-NLS-1$
-
- // Wrap lines?
- field = createFieldComposite(composite);
- wrapLines = new Button(field, SWT.CHECK);
- wrapLines.setSelection(prefs.getBoolean(MsgEditorPreferences.WRAP_LINES_ENABLED));
- wrapLines.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapLines")); //$NON-NLS-1$
-
- // After how many characters should we wrap?
- field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapLinesChar")); //$NON-NLS-1$
- wrapCharLimit = new Text(field, SWT.BORDER);
- wrapCharLimit.setText(prefs.getString(MsgEditorPreferences.WRAP_LINE_LENGTH));
- wrapCharLimit.setTextLimit(4);
- setWidthInChars(wrapCharLimit, 4);
- wrapCharLimit.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.wrapLinesChar.error"))); //$NON-NLS-1$
-
- // Align wrapped lines with equal signs?
- field = createFieldComposite(composite, indentPixels);
- wrapAlignEqualSigns = new Button(field, SWT.CHECK);
- wrapAlignEqualSigns.setSelection(
- prefs.getBoolean(MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED));
- wrapAlignEqualSigns.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapAlignEquals")); //$NON-NLS-1$
-
- // How many spaces/tabs to use for indenting?
- field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.wrapIndent")); //$NON-NLS-1$
- wrapIndentSpaces = new Text(field, SWT.BORDER);
- wrapIndentSpaces.setText(
- prefs.getString(MsgEditorPreferences.WRAP_INDENT_LENGTH));
- wrapIndentSpaces.setTextLimit(2);
- setWidthInChars(wrapIndentSpaces, 2);
- wrapIndentSpaces.addKeyListener(new IntTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.wrapIndent.error"))); //$NON-NLS-1$
-
- // Should we wrap after new line characters
- field = createFieldComposite(composite);
- wrapNewLine = new Button(field, SWT.CHECK);
- wrapNewLine.setSelection(
- prefs.getBoolean(MsgEditorPreferences.NEW_LINE_NICE));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString(
- "prefs.newline.nice")); //$NON-NLS-1$
-
- // How should new lines appear in properties file
- field = createFieldComposite(composite);
- newLineTypeForce = new Button(field, SWT.CHECK);
- newLineTypeForce.setSelection(
- prefs.getBoolean(MsgEditorPreferences.FORCE_NEW_LINE_TYPE));
- newLineTypeForce.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
- Composite newLineRadioGroup = new Composite(field, SWT.NONE);
- new Label(newLineRadioGroup, SWT.NONE).setText(
- MessagesEditorPlugin.getString(
- "prefs.newline.force")); //$NON-NLS-1$
- newLineRadioGroup.setLayout(new RowLayout());
- newLineTypes[0] = new Button(newLineRadioGroup, SWT.RADIO);
- newLineTypes[0].setText("UNIX (\\n)"); //$NON-NLS-1$
- newLineTypes[1] = new Button(newLineRadioGroup, SWT.RADIO);
- newLineTypes[1].setText("Windows (\\r\\n)"); //$NON-NLS-1$
- newLineTypes[2] = new Button(newLineRadioGroup, SWT.RADIO);
- newLineTypes[2].setText("Mac (\\r)"); //$NON-NLS-1$
- newLineTypes[prefs.getInt(
- MsgEditorPreferences.NEW_LINE_STYLE) - 1].setSelection(true);
-
- // Keep empty fields?
- field = createFieldComposite(composite);
- keepEmptyFields = new Button(field, SWT.CHECK);
- keepEmptyFields.setSelection(prefs.getBoolean(
- MsgEditorPreferences.KEEP_EMPTY_FIELDS));
- new Label(field, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.keepEmptyFields"));//$NON-NLS-1$
-
- // Sort keys?
- field = createFieldComposite(composite);
- sortKeys = new Button(field, SWT.CHECK);
- sortKeys.setSelection(prefs.getBoolean(
- MsgEditorPreferences.SORT_KEYS));
- new Label(field, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.keysSorted"));//$NON-NLS-1$
-
- refreshEnabledStatuses();
-
- return composite;
- }
-
-
- /**
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
- prefs.setValue(MsgEditorPreferences.SHOW_SUPPORT_ENABLED,
- showGeneratedBy.getSelection());
- prefs.setValue(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED,
- convertUnicodeToEncoded.getSelection());
- prefs.setValue(MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE,
- convertUnicodeUpperCase.getSelection());
- prefs.setValue(MsgEditorPreferences.ALIGN_EQUALS_ENABLED,
- alignEqualSigns.getSelection());
- prefs.setValue(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED,
- ensureSpacesAroundEquals.getSelection());
- prefs.setValue(MsgEditorPreferences.GROUP_KEYS_ENABLED,
- groupKeys.getSelection());
- prefs.setValue(MsgEditorPreferences.GROUP_LEVEL_DEEP,
- groupLevelDeep.getText());
- prefs.setValue(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT,
- groupLineBreaks.getText());
- prefs.setValue(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED,
- groupAlignEqualSigns.getSelection());
- prefs.setValue(MsgEditorPreferences.WRAP_LINES_ENABLED,
- wrapLines.getSelection());
- prefs.setValue(MsgEditorPreferences.WRAP_LINE_LENGTH,
- wrapCharLimit.getText());
- prefs.setValue(MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED,
- wrapAlignEqualSigns.getSelection());
- prefs.setValue(MsgEditorPreferences.WRAP_INDENT_LENGTH,
- wrapIndentSpaces.getText());
- prefs.setValue(MsgEditorPreferences.NEW_LINE_NICE,
- wrapNewLine.getSelection());
- prefs.setValue(MsgEditorPreferences.FORCE_NEW_LINE_TYPE,
- newLineTypeForce.getSelection());
- for (int i = 0; i < newLineTypes.length; i++) {
- if (newLineTypes[i].getSelection()) {
- prefs.setValue(MsgEditorPreferences.NEW_LINE_STYLE, i + 1);
- }
- }
- prefs.setValue(MsgEditorPreferences.KEEP_EMPTY_FIELDS,
- keepEmptyFields.getSelection());
- prefs.setValue(MsgEditorPreferences.SORT_KEYS, sortKeys.getSelection());
- refreshEnabledStatuses();
- return super.performOk();
- }
-
-
- /**
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
- showGeneratedBy.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.SHOW_SUPPORT_ENABLED));
- convertUnicodeToEncoded.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.UNICODE_ESCAPE_ENABLED));
- convertUnicodeToEncoded.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE));
- alignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.ALIGN_EQUALS_ENABLED));
- alignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED));
- groupKeys.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.GROUP_KEYS_ENABLED));
- groupLevelDeep.setText(prefs.getDefaultString(
- MsgEditorPreferences.GROUP_LEVEL_DEEP));
- groupLineBreaks.setText(prefs.getDefaultString(
- MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT));
- groupAlignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED));
- wrapLines.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.WRAP_LINES_ENABLED));
- wrapCharLimit.setText(prefs.getDefaultString(
- MsgEditorPreferences.WRAP_LINE_LENGTH));
- wrapAlignEqualSigns.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED));
- wrapIndentSpaces.setText(prefs.getDefaultString(
- MsgEditorPreferences.WRAP_INDENT_LENGTH));
- wrapNewLine.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.NEW_LINE_NICE));
- newLineTypeForce.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.FORCE_NEW_LINE_TYPE));
- newLineTypes[Math.min(prefs.getDefaultInt(
- MsgEditorPreferences.NEW_LINE_STYLE) - 1, 0)].setSelection(
- true);
- keepEmptyFields.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.KEEP_EMPTY_FIELDS));
- sortKeys.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.SORT_KEYS));
- refreshEnabledStatuses();
- super.performDefaults();
- }
-
- /*default*/ void refreshEnabledStatuses() {
- boolean isEncodingUnicode = convertUnicodeToEncoded.getSelection();
- boolean isGroupKeyEnabled = groupKeys.getSelection();
- boolean isAlignEqualsEnabled = alignEqualSigns.getSelection();
- boolean isWrapEnabled = wrapLines.getSelection();
- boolean isWrapAlignEqualsEnabled = wrapAlignEqualSigns.getSelection();
- boolean isNewLineStyleForced = newLineTypeForce.getSelection();
-
- convertUnicodeUpperCase.setEnabled(isEncodingUnicode);
- groupLevelDeep.setEnabled(isGroupKeyEnabled);
- groupLineBreaks.setEnabled(isGroupKeyEnabled);
- groupAlignEqualSigns.setEnabled(
- isGroupKeyEnabled && isAlignEqualsEnabled);
- wrapCharLimit.setEnabled(isWrapEnabled);
- wrapAlignEqualSigns.setEnabled(isWrapEnabled);
- wrapIndentSpaces.setEnabled(isWrapEnabled && !isWrapAlignEqualsEnabled);
- for (int i = 0; i < newLineTypes.length; i++) {
- newLineTypes[i].setEnabled(isNewLineStyleForced);
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/GeneralPrefPage.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/GeneralPrefPage.java
deleted file mode 100644
index 1119f4ff..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/GeneralPrefPage.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * Plugin generic preference page.
- * @author Pascal Essiembre ([email protected])
- */
-public class GeneralPrefPage extends AbstractPrefPage {
-
- /* Preference fields. */
- private Text keyGroupSeparator;
-
- private Text filterLocales;
-
- private Button convertEncodedToUnicode;
-
- private Button supportNL;
-// private Button supportFragments;
-// private Button loadOnlyFragmentResources;
-
- private Button keyTreeHierarchical;
- private Button keyTreeExpanded;
-
- private Button fieldTabInserts;
-
-// private Button noTreeInEditor;
-
- private Button setupRbeNatureAutomatically;
-
- /**
- * Constructor.
- */
- public GeneralPrefPage() {
- super();
- }
-
- /**
- * @see org.eclipse.jface.preference.PreferencePage
- * #createContents(org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- MsgEditorPreferences prefs = MsgEditorPreferences.getInstance();
-
-// IPreferenceStore prefs = getPreferenceStore();
- Composite field = null;
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, false));
-
- // Key group separator
- field = createFieldComposite(composite);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.groupSep")); //$NON-NLS-1$
- keyGroupSeparator = new Text(field, SWT.BORDER);
- keyGroupSeparator.setText(prefs.getSerializerConfig().getGroupLevelSeparator());
-// prefs.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
- keyGroupSeparator.setTextLimit(2);
-
- field = createFieldComposite(composite);
- Label filterLocalesLabel = new Label(field, SWT.NONE);
- filterLocalesLabel.setText(
- MessagesEditorPlugin.getString("prefs.filterLocales.label")); //$NON-NLS-1$
- filterLocalesLabel.setToolTipText(
- MessagesEditorPlugin.getString("prefs.filterLocales.tooltip")); //$NON-NLS-1$
- filterLocales = new Text(field, SWT.BORDER);
- filterLocales.setText(prefs.getFilterLocalesStringMatcher());
-// prefs.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
- filterLocales.setTextLimit(22);
- setWidthInChars(filterLocales, 16);
-
-
- // Convert encoded to unicode?
- field = createFieldComposite(composite);
- convertEncodedToUnicode = new Button(field, SWT.CHECK);
- convertEncodedToUnicode.setSelection(
- prefs.getSerializerConfig().isUnicodeEscapeEnabled());
-// prefs.getBoolean(MsgEditorPreferences.CONVERT_ENCODED_TO_UNICODE));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.convertEncoded")); //$NON-NLS-1$
-
- // Support "NL" localization structure
- field = createFieldComposite(composite);
- supportNL = new Button(field, SWT.CHECK);
- supportNL.setSelection(prefs.isNLSupportEnabled());
- //prefs.getBoolean(MsgEditorPreferences.SUPPORT_NL));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.supportNL")); //$NON-NLS-1$
-
- // Setup rbe validation builder on java projects automatically.
- field = createFieldComposite(composite);
- setupRbeNatureAutomatically = new Button(field, SWT.CHECK);
- setupRbeNatureAutomatically.setSelection(prefs.isBuilderSetupAutomatically());
- //prefs.getBoolean(MsgEditorPreferences.SUPPORT_NL));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.setupValidationBuilderAutomatically")); //$NON-NLS-1$
-
-// // Support loading resources from fragment
-// field = createFieldComposite(composite);
-// supportFragments = new Button(field, SWT.CHECK);
-// supportFragments.setSelection(prefs.isShowSupportEnabled());
-// new Label(field, SWT.NONE).setText(
-// MessagesEditorPlugin.getString("prefs.supportFragments")); //$NON-NLS-1$
-//
-// // Support loading resources from fragment
-// field = createFieldComposite(composite);
-// loadOnlyFragmentResources = new Button(field, SWT.CHECK);
-// loadOnlyFragmentResources.setSelection(
-// prefs.isLoadingOnlyFragmentResources());
-// //MsgEditorPreferences.getLoadOnlyFragmentResources());
-// new Label(field, SWT.NONE).setText(
-// MessagesEditorPlugin.getString("prefs.loadOnlyFragmentResources")); //$NON-NLS-1$
-
- // Default key tree mode (tree vs flat)
- field = createFieldComposite(composite);
- keyTreeHierarchical = new Button(field, SWT.CHECK);
- keyTreeHierarchical.setSelection(
- prefs.isKeyTreeHierarchical());
-// prefs.getBoolean(MsgEditorPreferences.KEY_TREE_HIERARCHICAL));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.keyTree.hierarchical"));//$NON-NLS-1$
-
- // Default key tree expand status (expanded vs collapsed)
- field = createFieldComposite(composite);
- keyTreeExpanded = new Button(field, SWT.CHECK);
- keyTreeExpanded.setSelection(prefs.isKeyTreeExpanded());
-// prefs.getBoolean(MsgEditorPreferences.KEY_TREE_EXPANDED)); //$NON-NLS-1$
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.keyTree.expanded")); //$NON-NLS-1$
-
- // Default tab key behaviour in text field
- field = createFieldComposite(composite);
- fieldTabInserts = new Button(field, SWT.CHECK);
- fieldTabInserts.setSelection(prefs.isFieldTabInserts());
-// prefs.getBoolean(MsgEditorPreferences.FIELD_TAB_INSERTS));
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.fieldTabInserts")); //$NON-NLS-1$
-
-// field = createFieldComposite(composite);
-// noTreeInEditor = new Button(field, SWT.CHECK);
-// noTreeInEditor.setSelection(prefs.isEditorTreeHidden());
-//// prefs.getBoolean(MsgEditorPreferences.EDITOR_TREE_HIDDEN)); //$NON-NLS-1$
-// new Label(field, SWT.NONE).setText(
-// MessagesEditorPlugin.getString("prefs.noTreeInEditor")); //$NON-NLS-1$
-
- refreshEnabledStatuses();
- return composite;
- }
-
- /**
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
- prefs.setValue(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR,
- keyGroupSeparator.getText());
- prefs.setValue(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS,
- filterLocales.getText());
- prefs.setValue(MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED,
- convertEncodedToUnicode.getSelection());
- prefs.setValue(MsgEditorPreferences.NL_SUPPORT_ENABLED,
- supportNL.getSelection());
- prefs.setValue(MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS,
- setupRbeNatureAutomatically.getSelection());
- prefs.setValue(MsgEditorPreferences.KEY_TREE_HIERARCHICAL,
- keyTreeHierarchical.getSelection());
- prefs.setValue(MsgEditorPreferences.KEY_TREE_EXPANDED,
- keyTreeExpanded.getSelection());
- prefs.setValue(MsgEditorPreferences.FIELD_TAB_INSERTS,
- fieldTabInserts.getSelection());
-// prefs.setValue(MsgEditorPreferences.EDITOR_TREE_HIDDEN,
-// noTreeInEditor.getSelection());
- refreshEnabledStatuses();
- return super.performOk();
- }
-
-
- /**
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
- keyGroupSeparator.setText(
- prefs.getDefaultString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR));
- filterLocales.setText(
- prefs.getDefaultString(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS));
- convertEncodedToUnicode.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED));
- supportNL.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.NL_SUPPORT_ENABLED));
- keyTreeHierarchical.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.KEY_TREE_HIERARCHICAL));
- keyTreeHierarchical.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.KEY_TREE_EXPANDED));
- fieldTabInserts.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.FIELD_TAB_INSERTS));
- setupRbeNatureAutomatically.setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS));
-
- refreshEnabledStatuses();
- super.performDefaults();
- }
-
- private void refreshEnabledStatuses() {
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/MsgEditorPreferences.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/MsgEditorPreferences.java
deleted file mode 100644
index d45d4def..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/MsgEditorPreferences.java
+++ /dev/null
@@ -1,729 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
-import org.eclipse.babel.core.message.resource.ser.IPropertiesSerializerConfig;
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.internal.misc.StringMatcher;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.builder.Builder;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.builder.ToggleNatureAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * Messages Editor preferences.
- * @author Pascal Essiembre ([email protected])
- */
-public final class MsgEditorPreferences
- implements /*IPropertiesSerializerConfig, IPropertiesDeserializerConfig,*/ IPropertyChangeListener {
-
- /** the corresponding validation message with such a preference should
- * not be generated */
- public static final int VALIDATION_MESSAGE_IGNORE = 0;
- /** the corresponding validation message with such a preference should
- * generate a marker with severity 'info' */
- public static final int VALIDATION_MESSAGE_INFO = 1;
- /** the corresponding validation message with such a preference should
- * generate a marker with severity 'warning' */
- public static final int VALIDATION_MESSAGE_WARNING = 2;
- /** the corresponding validation message with such a preference should
- * generate a marker with severity 'error' */
- public static final int VALIDATION_MESSAGE_ERROR = 3;
-
- /** Key group separator. */
- public static final String GROUP__LEVEL_SEPARATOR =
- "groupLevelSeparator"; //$NON-NLS-1$
-
- /** Should key tree be hiearchical by default. */
- public static final String KEY_TREE_HIERARCHICAL =
- "keyTreeHierarchical"; //$NON-NLS-1$
- /** Should key tree be expanded by default. */
- public static final String KEY_TREE_EXPANDED =
- "keyTreeExpanded"; //$NON-NLS-1$
-
- /** Should "Generated by" line be added to files. */
- public static final String SHOW_SUPPORT_ENABLED =
- "showSupportEnabled"; //$NON-NLS-1$
-
- /** Should Eclipse "nl" directory structure be supported. */
- public static final String NL_SUPPORT_ENABLED =
- "nLSupportEnabled"; //$NON-NLS-1$
-
- /** Should resources also be loaded from fragments. */
- public static final String SUPPORT_FRAGMENTS = "supportFragments"; //$NON-NLS-1$
- /**
- * Load only fragment resources when loading from fragments.
- * The default bundle is mostly located in the host plug-in.
- */
- public static final String LOADING_ONLY_FRAGMENT_RESOURCES =
- "loadingOnlyFragmentResources";
-
- /** Should tab characters be inserted when tab key pressed on text field. */
- public static final String FIELD_TAB_INSERTS =
- "fieldTabInserts"; //$NON-NLS-1$
-
- /** Should equal signs be aligned. */
- public static final String ALIGN_EQUALS_ENABLED =
- "alignEqualsEnabled"; //$NON-NLS-1$
- /** Should spaces be put around equal signs. */
- public static final String SPACES_AROUND_EQUALS_ENABLED =
- "spacesAroundEqualsEnabled"; //$NON-NLS-1$
-
- /** Should keys be grouped. */
- public static final String GROUP_KEYS_ENABLED =
- "groupKeysEnabled"; //$NON-NLS-1$
- /** How many level deep should keys be grouped. */
- public static final String GROUP_LEVEL_DEEP =
- "groupLevelDeep"; //$NON-NLS-1$
- /** How many line breaks between key groups. */
- public static final String GROUP_SEP_BLANK_LINE_COUNT =
- "groupSepBlankLineCount"; //$NON-NLS-1$
- /** Should equal signs be aligned within groups. */
- public static final String GROUP_ALIGN_EQUALS_ENABLED =
- "groupAlignEqualsEnabled"; //$NON-NLS-1$
-
- /** Should lines be wrapped. */
- public static final String WRAP_LINES_ENABLED =
- "wrapLinesEnabled"; //$NON-NLS-1$
- /** Maximum number of character after which we should wrap. */
- public static final String WRAP_LINE_LENGTH = "wrapLineLength"; //$NON-NLS-1$
- /** Align subsequent lines with equal signs. */
- public static final String WRAP_ALIGN_EQUALS_ENABLED =
- "wrapAlignEqualsEnabled"; //$NON-NLS-1$
- /** Number of spaces to indent subsequent lines. */
- public static final String WRAP_INDENT_LENGTH =
- "wrapIndentLength"; //$NON-NLS-1$
-
- /** Should unicode values be converted to their encoded equivalent. */
- public static final String UNICODE_ESCAPE_ENABLED =
- "unicodeEscapeEnabled"; //$NON-NLS-1$
- /** Should unicode values be converted to their encoded equivalent. */
- public static final String UNICODE_ESCAPE_UPPERCASE =
- "unicodeEscapeUppercase"; //$NON-NLS-1$
- /** Should encoded values be converted to their unicode equivalent. */
- public static final String UNICODE_UNESCAPE_ENABLED =
- "unicodeUnescapeEnabled"; //$NON-NLS-1$
-
- /** Impose a given new line type. */
- public static final String FORCE_NEW_LINE_TYPE =
- "forceNewLineType"; //$NON-NLS-1$
- /** How new lines are represented in resource bundle. */
- public static final String NEW_LINE_STYLE = "newLineStyle"; //$NON-NLS-1$
- /** Should new lines character produce a line break in properties files. */
- public static final String NEW_LINE_NICE = "newLineNice"; //$NON-NLS-1$
-
- /** Report missing values with given level of reporting: IGNORE, INFO, WARNING, ERROR. */
- public static final String REPORT_MISSING_VALUES_LEVEL =
- "detectMissingValuesLevel"; //$NON-NLS-1$
- /** Report duplicate values. */
- public static final String REPORT_DUPL_VALUES_LEVEL =
- "reportDuplicateValuesLevel"; //$NON-NLS-1$
- /** Report duplicate values. */
- public static final String REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE =
- "reportDuplicateValuesOnlyInRootLocale"; //$NON-NLS-1$
- /** Report similar values. */
- public static final String REPORT_SIM_VALUES_LEVEL =
- "reportSimilarValuesLevel"; //$NON-NLS-1$
- /** Report similar values: word compare. */
- public static final String REPORT_SIM_VALUES_WORD_COMPARE =
- "reportSimilarValuesWordCompare"; //$NON-NLS-1$
- /** Report similar values: levensthein distance. */
- public static final String REPORT_SIM_VALUES_LEVENSTHEIN =
- "reportSimilarValuesLevensthein"; //$NON-NLS-1$
- /** Report similar values: precision. */
- public static final String REPORT_SIM_VALUES_PRECISION =
- "reportSimilarValuesPrecision"; //$NON-NLS-1$
-
- /** Don't show the tree within the editor. */
- public static final String EDITOR_TREE_HIDDEN =
- "editorTreeHidden"; //$NON-NLS-1$
-
- /** Keep empty fields. */
- public static final String KEEP_EMPTY_FIELDS =
- "keepEmptyFields"; //$NON-NLS-1$
-
- /** Sort keys. */
- public static final String SORT_KEYS = "sortKeys"; //$NON-NLS-1$
-
- /** Display comment editor for default language. */
- public static final String DISPLAY_DEFAULT_COMMENT_FIELD =
- "displayCommentFieldNL"; //$NON-NLS-1$
- /** Display comment editor for all languages*/
- public static final String DISPLAY_LANG_COMMENT_FIELDS =
- "displayLangCommentFieldsNL"; //$NON-NLS-1$
-
- /** Locales filter and order defined as a comma separated list of string matchers */
- public static final String FILTER_LOCALES_STRING_MATCHERS = "localesFilterStringMatchers";
-
- /** When true the builder that validates translation files is
- * automatically added to java projects when the plugin is started
- * or when a new project is added. */
- public static final String ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS =
- "addMsgEditorBuilderToJavaProjects";
-
- /** holds what filter is activated. for the properties displayed in the editor. */
- public static final String PROPERTIES_DISPLAYED_FILTER = "propertiesFilter";
-
- /** true to enable the indexer false otherwise.
- * the indexer is used to generate list of suggestions in the translations.
- * this is currently experimental. */
- public static final String ENABLE_PROPERTIES_INDEXER = "enablePropertiesIndexer";
-
- /** MsgEditorPreferences. */
- private static final Preferences PREFS =
- MessagesEditorPlugin.getDefault().getPluginPreferences();
-
- private static final MsgEditorPreferences INSTANCE =
- new MsgEditorPreferences();
-
- private final IPropertiesSerializerConfig serializerConfig = new PropertiesSerializerConfig();
-
- private final IPropertiesDeserializerConfig deserializerConfig = new PropertiesDeserializerConfig();
-
- private StringMatcher[] cachedCompiledLocaleFilter;
-
- /**
- * Constructor.
- */
- private MsgEditorPreferences() {
- super();
- }
-
- public static MsgEditorPreferences getInstance() {
- return INSTANCE;
- }
-
-
- public IPropertiesSerializerConfig getSerializerConfig() {
- return serializerConfig;
- }
-
- public IPropertiesDeserializerConfig getDeserializerConfig() {
- return deserializerConfig;
- }
-
- /**
- * Gets whether pressing tab inserts a tab in a field.
- * @return <code>true</code> if pressing tab inserts a tab in a field
- */
- public boolean isFieldTabInserts() {
- return PREFS.getBoolean(FIELD_TAB_INSERTS);
- }
-
- /**
- * Gets whether key tree should be displayed in hiearchical way by default.
- * @return <code>true</code> if hierarchical
- */
- public boolean isKeyTreeHierarchical() {
- return PREFS.getBoolean(KEY_TREE_HIERARCHICAL);
- }
- /**
- * Gets whether key tree should be show expaned by default.
- * @return <code>true</code> if expanded
- */
- public boolean isKeyTreeExpanded() {
- return PREFS.getBoolean(KEY_TREE_EXPANDED);
- }
-
- /**
- * Gets whether to support Eclipse NL directory structure.
- * @return <code>true</code> if supported
- */
- public boolean isNLSupportEnabled() {
- return PREFS.getBoolean(NL_SUPPORT_ENABLED);
- }
-
- /**
- * Gets whether to support resources found in fragments.
- * @return <code>true</code> if supported
- */
- public boolean isLoadingOnlyFragmentResources() {
- return PREFS.getBoolean(LOADING_ONLY_FRAGMENT_RESOURCES);
- }
-
- /**
- * Gets whether to support resources found in fragments.
- * @return <code>true</code> if supported
- */
- public boolean getSupportFragments() {
- return PREFS.getBoolean(SUPPORT_FRAGMENTS);
- }
-
-// /**
-// * True iff the I18N editor page should contiain a comment field for the
-// * default language
-// *
-// * @return boolean
-// */
-// public static boolean getDisplayDefaultCommentField() {
-// return PREFS.getBoolean(DISPLAY_DEFAULT_COMMENT_FIELD);
-// }
-//
-// /**
-// * True iff the I18N editor page should contain a comment field for each
-// * individual language
-// *
-// * @return boolean
-// */
-// public static boolean getDisplayLangCommentFields() {
-// return PREFS.getBoolean(DISPLAY_LANG_COMMENT_FIELDS);
-// }
-//
-
- /**
- * @return the filter to apply on the displayed properties.
- * One of the {@link IMessagesEditorChangeListener}.SHOW_*
- * Byt default: show all.
- */
- public int getPropertiesFilter() {
- return PREFS.getInt(PROPERTIES_DISPLAYED_FILTER);
- }
- /**
- * @param filter The filter to apply on the displayed properties.
- * One of the {@link IMessagesEditorChangeListener}.SHOW_*
- */
- public void setPropertiesFilter(int filter) {
- PREFS.setValue(PROPERTIES_DISPLAYED_FILTER, filter);
- }
-
- /**
- * Gets whether we want to overwrite system (or Eclipse) default new line
- * type when generating file.
- * @return <code>true</code> if overwriting
- */
- public boolean getForceNewLineType() {
- return PREFS.getBoolean(FORCE_NEW_LINE_TYPE);
- }
-
- /**
- * Gets whether to report keys with missing values.
- * @return <code>true</code> if reporting
- */
- public boolean getReportMissingValues() {
- return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
- //return PREFS.getBoolean(REPORT_MISSING_VALUES);
- }
- /**
- * Returns the level of reporting for missing values.
- * @return VALIDATION_MESSAGE_IGNORE or VALIDATION_MESSAGE_INFO or
- * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
- */
- public int getReportMissingValuesLevel() {
- return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL);
- }
-
-
- /**
- * Gets whether to report keys with duplicate values.
- * @return <code>true</code> if reporting
- */
- public boolean getReportDuplicateValues() {
- return PREFS.getInt(REPORT_DUPL_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
- }
-
- /**
- * Returns the level of reporting for duplicate values.
- * @return VALIDATION_MESSAGE_IGNORE or VALIDATION_MESSAGE_INFO or
- * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
- */
- public int getReportDuplicateValuesLevel() {
- return PREFS.getInt(REPORT_DUPL_VALUES_LEVEL);
- }
-
- /**
- * Gets whether to report keys with duplicate values.
- * @return <code>true</code> if reporting duplicate is applied
- * only for the root locale (aka default properties file.)
- */
- public boolean getReportDuplicateValuesOnlyInRootLocales() {
- return PREFS.getBoolean(REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE);
- }
-
- /**
- * Gets whether to report keys with similar values.
- * @return <code>true</code> if reporting
- */
- public boolean getReportSimilarValues() {
- return PREFS.getInt(REPORT_SIM_VALUES_LEVEL) != VALIDATION_MESSAGE_IGNORE;
- }
- /**
- * Returns the level of reporting for similar values.
- * @return VALIDATION_MESSAGE_IGNORE or VALIDATION_MESSAGE_INFO or
- * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR.
- */
- public int getReportSimilarValuesLevel() {
- return PREFS.getInt(REPORT_SIM_VALUES_LEVEL);
- }
-
- /**
- * Gets whether to use the "word compare" method when reporting similar
- * values.
- * @return <code>true</code> if using "word compare" method
- */
- public boolean getReportSimilarValuesWordCompare() {
- return PREFS.getBoolean(REPORT_SIM_VALUES_WORD_COMPARE);
- }
-
- /**
- * Gets whether to use the Levensthein method when reporting similar
- * values.
- * @return <code>true</code> if using Levensthein method
- */
- public boolean getReportSimilarValuesLevensthein() {
- return PREFS.getBoolean(REPORT_SIM_VALUES_LEVENSTHEIN);
- }
-
- /**
- * Gets the minimum precision level to use for determining when to report
- * similarities.
- * @return precision
- */
- public double getReportSimilarValuesPrecision() {
- return PREFS.getDouble(REPORT_SIM_VALUES_PRECISION);
- }
-
- /**
- * Gets whether a tree shall be displayed within the editor or not.
- * @return <code>true</code> A tree shall not be displayed.
- */
- public boolean isEditorTreeHidden() {
- return PREFS.getBoolean(EDITOR_TREE_HIDDEN);
- }
-
- /**
- * Gets whether to keep empty fields.
- * @return <code>true</code> if empty fields are to be kept.
- */
- public boolean getKeepEmptyFields() {
- return PREFS.getBoolean(KEEP_EMPTY_FIELDS);
- }
-
- /**
- * @return a comma separated list of locales-string-matchers.
- * <p>
- * Note: StringMatcher is an internal API duplicated in many different places of eclipse.
- * The only project that decided to make it public is GMF (org.eclipse.gmf.runtime.common.core.util)
- * Although they have been request to make it public since 2001:
- * http://dev.eclipse.org/newslists/news.eclipse.tools/msg00666.html
- * </p>
- * <p>
- * We choose org.eclipse.ui.internal.misc in the org.eclipse.ui.workbench
- * plugin as it is part of RCP; the most common one.
- * </p>
- * @see org.eclipse.ui.internal.misc.StringMatcher
- */
- public String getFilterLocalesStringMatcher() {
- return PREFS.getString(FILTER_LOCALES_STRING_MATCHERS);
- }
- /**
- * @return The StringMatchers compiled from #getFilterLocalesStringMatcher()
- */
- public synchronized StringMatcher[] getFilterLocalesStringMatchers() {
- if (cachedCompiledLocaleFilter != null) {
- return cachedCompiledLocaleFilter;
- }
-
- String pref = PREFS.getString(FILTER_LOCALES_STRING_MATCHERS);
- StringTokenizer tokenizer = new StringTokenizer(pref, ";, ", false);
- cachedCompiledLocaleFilter = new StringMatcher[tokenizer.countTokens()];
- int ii = 0;
- while (tokenizer.hasMoreTokens()) {
- StringMatcher pattern = new StringMatcher(tokenizer.nextToken().trim(), true, false);
- cachedCompiledLocaleFilter[ii] = pattern;
- ii++;
- }
- return cachedCompiledLocaleFilter;
- }
-
- /**
- * Gets whether the rbe nature and rbe builder are automatically setup
- * on java projects in the workspace.
- * @return <code>true</code> Setup automatically the rbe builder
- * on java projects.
- */
- public boolean isBuilderSetupAutomatically() {
- return PREFS.getBoolean(ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS);
- }
-
- /**
- * Notified when the value of the filter locales preferences changes.
- *
- * @param event the property change event object describing which
- * property changed and how
- */
- public void propertyChange(Preferences.PropertyChangeEvent event) {
- if (FILTER_LOCALES_STRING_MATCHERS.equals(event.getProperty())) {
- onLocalFilterChange();
- } else if (ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS.equals(event.getProperty())) {
- onAddValidationBuilderChange();
- }
- }
-
- /**
- * Called when the locales filter value is changed.
- * <p>
- * Takes care of reloading the opened editors and calling the full-build
- * of the rbeBuilder on all project that use it.
- * </p>
- */
- private void onLocalFilterChange() {
- cachedCompiledLocaleFilter = null;
-
- //first: refresh the editors.
- //look at the opened editors and reload them if possible
- //otherwise, save them, close them and re-open them.
- IWorkbenchPage[] pages =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPages();
- for (int i = 0; i < pages.length; i++) {
- IEditorReference[] edRefs = pages[i].getEditorReferences();
- for (int j = 0; j < edRefs.length; j++) {
- IEditorReference ref = edRefs[j];
- IEditorPart edPart = ref.getEditor(false);
- if (edPart != null && edPart instanceof MessagesEditor) {
- //the editor was loaded. reload it:
- MessagesEditor meToReload = (MessagesEditor)edPart;
- meToReload.reloadDisplayedContents();
- }
- }
- }
-
- //second: clean and build all the projects that have the rbe builder.
- //Calls the builder for a clean and build on all projects of the workspace.
- try {
- IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projs.length; i++) {
- if (projs[i].isAccessible()) {
- ICommand[] builders = projs[i].getDescription().getBuildSpec();
- for (int j = 0; j < builders.length; j++) {
- if (Builder.BUILDER_ID.equals(builders[j].getBuilderName())) {
- projs[i].build(IncrementalProjectBuilder.FULL_BUILD,
- Builder.BUILDER_ID, null, new NullProgressMonitor());
- break;
- }
- }
- }
- }
- } catch (CoreException ce) {
- IStatus status= new Status(IStatus.ERROR, MessagesEditorPlugin.PLUGIN_ID, IStatus.OK,
- ce.getMessage(), ce);
- MessagesEditorPlugin.getDefault().getLog().log(status);
- }
- }
-
- /**
- * Called when the value of the setting up automatically the validation builder to
- * projects is changed.
- * <p>
- * When changed to true, call the static method that goes through
- * the projects accessible in the workspace and if they have a java nature,
- * make sure they also have the rbe nature and rbe builder.
- * </p>
- * <p>
- * When changed to false, make a dialog offering the user to remove all setup
- * builders from the projects where it can be found.
- * </p>
- */
- private void onAddValidationBuilderChange() {
- if (isBuilderSetupAutomatically()) {
- ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
- } else {
- boolean res =
- MessageDialog.openQuestion(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- MessagesEditorPlugin.getString("prefs.removeAlreadyInstalledValidators.title"),
- MessagesEditorPlugin.getString("prefs.removeAlreadyInstalledValidators.text"));
- if (res) {
- ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(false);
- }
- }
- }
-
- //###########################################################################################
- //###############################PropertiesSerializerConfig##################################
- //###########################################################################################
-
-// /**
-// * Gets whether to escape unicode characters when generating file.
-// * @return <code>true</code> if escaping
-// */
-// public boolean isUnicodeEscapeEnabled() {
-// return PREFS.getBoolean(UNICODE_ESCAPE_ENABLED);
-// }
-//
-// /**
-// * Gets the new line type to use when overwriting system (or Eclipse)
-// * default new line type when generating file. Use constants to this
-// * effect.
-// * @return new line type
-// */
-// public int getNewLineStyle() {
-// return PREFS.getInt(NEW_LINE_STYLE);
-// }
-//
-// /**
-// * Gets how many blank lines should separate groups when generating file.
-// * @return how many blank lines between groups
-// */
-// public int getGroupSepBlankLineCount() {
-// return PREFS.getInt(GROUP_SEP_BLANK_LINE_COUNT);
-// }
-//
-// /**
-// * Gets whether to print "Generated By..." comment when generating file.
-// * @return <code>true</code> if we print it
-// */
-// public boolean isShowSupportEnabled() {
-// return PREFS.getBoolean(SHOW_SUPPORT_ENABLED);
-// }
-//
-// /**
-// * Gets whether keys should be grouped when generating file.
-// * @return <code>true</code> if keys should be grouped
-// */
-// public boolean isGroupKeysEnabled() {
-// return PREFS.getBoolean(GROUP_KEYS_ENABLED);
-// }
-//
-// /**
-// * Gets whether escaped unicode "alpha" characters should be uppercase
-// * when generating file.
-// * @return <code>true</code> if uppercase
-// */
-// public boolean isUnicodeEscapeUppercase() {
-// return PREFS.getBoolean(UNICODE_ESCAPE_UPPERCASE);
-// }
-//
-// /**
-// * Gets the number of character after which lines should be wrapped when
-// * generating file.
-// * @return number of characters
-// */
-// public int getWrapLineLength() {
-// return PREFS.getInt(WRAP_LINE_LENGTH);
-// }
-//
-// /**
-// * Gets whether lines should be wrapped if too big when generating file.
-// * @return <code>true</code> if wrapped
-// */
-// public boolean isWrapLinesEnabled() {
-// return PREFS.getBoolean(WRAP_LINES_ENABLED);
-// }
-//
-// /**
-// * Gets whether wrapped lines should be aligned with equal sign when
-// * generating file.
-// * @return <code>true</code> if aligned
-// */
-// public boolean isWrapAlignEqualsEnabled() {
-// return PREFS.getBoolean(WRAP_ALIGN_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets the number of spaces to use for indentation of wrapped lines when
-// * generating file.
-// * @return number of spaces
-// */
-// public int getWrapIndentLength() {
-// return PREFS.getInt(WRAP_INDENT_LENGTH);
-// }
-//
-// /**
-// * Gets whether there should be spaces around equals signs when generating
-// * file.
-// * @return <code>true</code> there if should be spaces around equals signs
-// */
-// public boolean isSpacesAroundEqualsEnabled() {
-// return PREFS.getBoolean(SPACES_AROUND_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets whether new lines are escaped or printed as is when generating file.
-// * @return <code>true</code> if printed as is.
-// */
-// public boolean isNewLineNice() {
-// return PREFS.getBoolean(NEW_LINE_NICE);
-// }
-//
-// /**
-// * Gets how many level deep keys should be grouped when generating file.
-// * @return how many level deep
-// */
-// public int getGroupLevelDepth() {
-// return PREFS.getInt(GROUP_LEVEL_DEEP);
-// }
-//
-// /**
-// * Gets key group separator.
-// * @return key group separator.
-// */
-// public String getGroupLevelSeparator() {
-// return PREFS.getString(GROUP__LEVEL_SEPARATOR);
-// }
-//
-// /**
-// * Gets whether equals signs should be aligned when generating file.
-// * @return <code>true</code> if equals signs should be aligned
-// */
-// public boolean isAlignEqualsEnabled() {
-// return PREFS.getBoolean(ALIGN_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets whether equal signs should be aligned within each groups when
-// * generating file.
-// * @return <code>true</code> if equal signs should be aligned within groups
-// */
-// public boolean isGroupAlignEqualsEnabled() {
-// return PREFS.getBoolean(GROUP_ALIGN_EQUALS_ENABLED);
-// }
-//
-// /**
-// * Gets whether to sort keys upon serializing them.
-// * @return <code>true</code> if keys are to be sorted.
-// */
-// public boolean isKeySortingEnabled() {
-// return PREFS.getBoolean(SORT_KEYS);
-// }
-
- //###########################################################################################
- //###############################PropertiesSerializerConfig##################################
- //###########################################################################################
-
-
-// /**
-// * Gets whether to convert encoded strings to unicode characters when
-// * reading file.
-// * @return <code>true</code> if converting
-// */
-// public boolean isUnicodeUnescapeEnabled() {
-// return PREFS.getBoolean(UNICODE_UNESCAPE_ENABLED);
-// }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PreferenceInitializer.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PreferenceInitializer.java
deleted file mode 100644
index 8fbbe1c9..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PreferenceInitializer.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * Initializes default preferences.
- * @author Pascal Essiembre ([email protected])
- */
-public class PreferenceInitializer extends
- AbstractPreferenceInitializer {
-
- /**
- * Constructor.
- */
- public PreferenceInitializer() {
- super();
- }
-
- /**
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer
- * #initializeDefaultPreferences()
- */
- public void initializeDefaultPreferences() {
- Preferences prefs = MessagesEditorPlugin.getDefault().getPluginPreferences();
-
- //General
- prefs.setDefault(MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.FIELD_TAB_INSERTS, true);
- prefs.setDefault(MsgEditorPreferences.KEY_TREE_HIERARCHICAL, true);
- prefs.setDefault(MsgEditorPreferences.KEY_TREE_EXPANDED, true);
- prefs.setDefault(MsgEditorPreferences.SUPPORT_FRAGMENTS, true);
- prefs.setDefault(MsgEditorPreferences.NL_SUPPORT_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.LOADING_ONLY_FRAGMENT_RESOURCES, false);
- prefs.setDefault(MsgEditorPreferences.PROPERTIES_DISPLAYED_FILTER,
- IMessagesEditorChangeListener.SHOW_ALL);
-
- //Formatting
- prefs.setDefault(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE, true);
-
- prefs.setDefault(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED, true);
-
- prefs.setDefault(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR, "."); //$NON-NLS-1$
- prefs.setDefault(MsgEditorPreferences.ALIGN_EQUALS_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.SHOW_SUPPORT_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.KEY_TREE_HIERARCHICAL, true);
-
- prefs.setDefault(MsgEditorPreferences.GROUP_KEYS_ENABLED, true);
- prefs.setDefault(MsgEditorPreferences.GROUP_LEVEL_DEEP, 1);
- prefs.setDefault(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT, 1);
- prefs.setDefault(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED, true);
-
- prefs.setDefault(MsgEditorPreferences.WRAP_LINE_LENGTH, 80);
- prefs.setDefault(MsgEditorPreferences.WRAP_INDENT_LENGTH, 8);
-
- prefs.setDefault(MsgEditorPreferences.NEW_LINE_STYLE,
- MsgEditorPreferences.getInstance().getSerializerConfig().NEW_LINE_UNIX);
-
- prefs.setDefault(MsgEditorPreferences.KEEP_EMPTY_FIELDS, false);
- prefs.setDefault(MsgEditorPreferences.SORT_KEYS, true);
-
- // Reporting/Performance
- prefs.setDefault(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL,
- MsgEditorPreferences.VALIDATION_MESSAGE_ERROR);
- prefs.setDefault(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL,
- MsgEditorPreferences.VALIDATION_MESSAGE_WARNING);
- prefs.setDefault(MsgEditorPreferences.REPORT_DUPL_VALUES_ONLY_IN_ROOT_LOCALE, true);
- prefs.setDefault(MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE, true);
- prefs.setDefault(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION, 0.75d);
-
- prefs.setDefault(MsgEditorPreferences.EDITOR_TREE_HIDDEN, false);
-
- //locales filter: by default: don't filter locales.
- prefs.setDefault(MsgEditorPreferences.FILTER_LOCALES_STRING_MATCHERS, "*"); //$NON-NLS-1$
- prefs.addPropertyChangeListener(MsgEditorPreferences.getInstance());
-
- //setup the i18n validation nature and its associated builder
- //on all java projects when the plugin is started
- //an when the editor is opened.
- prefs.setDefault(MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS, true); //$NON-NLS-1$
- prefs.addPropertyChangeListener(MsgEditorPreferences.getInstance());
-
-
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PropertiesDeserializerConfig.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PropertiesDeserializerConfig.java
deleted file mode 100644
index 7f0983d4..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PropertiesDeserializerConfig.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- *
- */
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.message.resource.ser.IPropertiesDeserializerConfig;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * @author ala
- *
- */
-public class PropertiesDeserializerConfig implements
- IPropertiesDeserializerConfig {
-
- /** MsgEditorPreferences. */
- private static final Preferences PREFS =
- MessagesEditorPlugin.getDefault().getPluginPreferences();
-
- PropertiesDeserializerConfig() {
- ConfigurationManager.getInstance().setDeserializerConfig(this);
- }
-
- /**
- * Gets whether to convert encoded strings to unicode characters when
- * reading file.
- * @return <code>true</code> if converting
- */
- public boolean isUnicodeUnescapeEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.UNICODE_UNESCAPE_ENABLED);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PropertiesSerializerConfig.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PropertiesSerializerConfig.java
deleted file mode 100644
index 3886aab7..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/PropertiesSerializerConfig.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- *
- */
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.message.resource.ser.IPropertiesSerializerConfig;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * @author ala
- *
- */
-public class PropertiesSerializerConfig implements IPropertiesSerializerConfig {
-
- /** MsgEditorPreferences. */
- private static final Preferences PREFS =
- MessagesEditorPlugin.getDefault().getPluginPreferences();
-
- PropertiesSerializerConfig() {
- ConfigurationManager.getInstance().setSerializerConfig(this);
- }
-
- /**
- * Gets whether to escape unicode characters when generating file.
- * @return <code>true</code> if escaping
- */
- public boolean isUnicodeEscapeEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.UNICODE_ESCAPE_ENABLED);
- }
-
- /**
- * Gets the new line type to use when overwriting system (or Eclipse)
- * default new line type when generating file. Use constants to this
- * effect.
- * @return new line type
- */
- public int getNewLineStyle() {
- return PREFS.getInt(MsgEditorPreferences.NEW_LINE_STYLE);
- }
-
- /**
- * Gets how many blank lines should separate groups when generating file.
- * @return how many blank lines between groups
- */
- public int getGroupSepBlankLineCount() {
- return PREFS.getInt(MsgEditorPreferences.GROUP_SEP_BLANK_LINE_COUNT);
- }
-
- /**
- * Gets whether to print "Generated By..." comment when generating file.
- * @return <code>true</code> if we print it
- */
- public boolean isShowSupportEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.SHOW_SUPPORT_ENABLED);
- }
-
- /**
- * Gets whether keys should be grouped when generating file.
- * @return <code>true</code> if keys should be grouped
- */
- public boolean isGroupKeysEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.GROUP_KEYS_ENABLED);
- }
-
- /**
- * Gets whether escaped unicode "alpha" characters should be uppercase
- * when generating file.
- * @return <code>true</code> if uppercase
- */
- public boolean isUnicodeEscapeUppercase() {
- return PREFS.getBoolean(MsgEditorPreferences.UNICODE_ESCAPE_UPPERCASE);
- }
-
- /**
- * Gets the number of character after which lines should be wrapped when
- * generating file.
- * @return number of characters
- */
- public int getWrapLineLength() {
- return PREFS.getInt(MsgEditorPreferences.WRAP_LINE_LENGTH);
- }
-
- /**
- * Gets whether lines should be wrapped if too big when generating file.
- * @return <code>true</code> if wrapped
- */
- public boolean isWrapLinesEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.WRAP_LINES_ENABLED);
- }
-
- /**
- * Gets whether wrapped lines should be aligned with equal sign when
- * generating file.
- * @return <code>true</code> if aligned
- */
- public boolean isWrapAlignEqualsEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.WRAP_ALIGN_EQUALS_ENABLED);
- }
-
- /**
- * Gets the number of spaces to use for indentation of wrapped lines when
- * generating file.
- * @return number of spaces
- */
- public int getWrapIndentLength() {
- return PREFS.getInt(MsgEditorPreferences.WRAP_INDENT_LENGTH);
- }
-
- /**
- * Gets whether there should be spaces around equals signs when generating
- * file.
- * @return <code>true</code> there if should be spaces around equals signs
- */
- public boolean isSpacesAroundEqualsEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.SPACES_AROUND_EQUALS_ENABLED);
- }
-
- /**
- * Gets whether new lines are escaped or printed as is when generating file.
- * @return <code>true</code> if printed as is.
- */
- public boolean isNewLineNice() {
- return PREFS.getBoolean(MsgEditorPreferences.NEW_LINE_NICE);
- }
-
- /**
- * Gets how many level deep keys should be grouped when generating file.
- * @return how many level deep
- */
- public int getGroupLevelDepth() {
- return PREFS.getInt(MsgEditorPreferences.GROUP_LEVEL_DEEP);
- }
-
- /**
- * Gets key group separator.
- * @return key group separator.
- */
- public String getGroupLevelSeparator() {
- return PREFS.getString(MsgEditorPreferences.GROUP__LEVEL_SEPARATOR);
- }
-
- /**
- * Gets whether equals signs should be aligned when generating file.
- * @return <code>true</code> if equals signs should be aligned
- */
- public boolean isAlignEqualsEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.ALIGN_EQUALS_ENABLED);
- }
-
- /**
- * Gets whether equal signs should be aligned within each groups when
- * generating file.
- * @return <code>true</code> if equal signs should be aligned within groups
- */
- public boolean isGroupAlignEqualsEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.GROUP_ALIGN_EQUALS_ENABLED);
- }
-
- /**
- * Gets whether to sort keys upon serializing them.
- * @return <code>true</code> if keys are to be sorted.
- */
- public boolean isKeySortingEnabled() {
- return PREFS.getBoolean(MsgEditorPreferences.SORT_KEYS);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/ReportingPrefPage.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/ReportingPrefPage.java
deleted file mode 100644
index b55bd13e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/preferences/ReportingPrefPage.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.preferences;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * Plugin preference page for reporting/performance options.
- * @author Pascal Essiembre ([email protected])
- */
-public class ReportingPrefPage extends AbstractPrefPage {
-
- /* Preference fields. */
- private Combo reportMissingVals;
- private Combo reportDuplVals;
- private Combo reportSimVals;
- private Text reportSimPrecision;
- private Button[] reportSimValsMode = new Button[2];
-
- /**
- * Constructor.
- */
- public ReportingPrefPage() {
- super();
- }
-
- /**
- * @see org.eclipse.jface.preference.PreferencePage#createContents(
- * org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite field = null;
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, false));
-
- new Label(composite, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.intro1")); //$NON-NLS-1$
- new Label(composite, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.intro2")); //$NON-NLS-1$
- new Label(composite, SWT.NONE).setText(" "); //$NON-NLS-1$
-
- // Report missing values?
- field = createFieldComposite(composite);
- GridData gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- field.setLayoutData(gridData);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.missingVals")); //$NON-NLS-1$
- reportMissingVals = new Combo(field, SWT.READ_ONLY);
- populateCombo(reportMissingVals,
- prefs.getInt(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL));
-// reportMissingVals.setSelection(
-// prefs.getBoolean(MsgEditorPreferences.REPORT_MISSING_VALUES));
-
- // Report duplicate values?
- field = createFieldComposite(composite);
- gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- field.setLayoutData(gridData);
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.duplVals")); //$NON-NLS-1$
- reportDuplVals = new Combo(field, SWT.READ_ONLY);
- populateCombo(reportDuplVals,
- prefs.getInt(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL));
-
- // Report similar values?
- field = createFieldComposite(composite);
- gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- field.setLayoutData(gridData);
-
- new Label(field, SWT.NONE).setText(
- MessagesEditorPlugin.getString("prefs.perform.simVals")); //$NON-NLS-1$
- reportSimVals = new Combo(field, SWT.READ_ONLY);
- populateCombo(reportSimVals,
- prefs.getInt(MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL));
- reportSimVals.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- refreshEnabledStatuses();
- }
- });
-
- Composite simValModeGroup = new Composite(composite, SWT.NONE);
- GridLayout gridLayout = new GridLayout(2, false);
- gridLayout.marginWidth = indentPixels;
- gridLayout.marginHeight = 0;
- gridLayout.verticalSpacing = 0;
- simValModeGroup.setLayout(gridLayout);
-
- // Report similar values: word count
- reportSimValsMode[0] = new Button(simValModeGroup, SWT.RADIO);
- reportSimValsMode[0].setSelection(prefs.getBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE));
- new Label(simValModeGroup, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.perform.simVals.wordCount")); //$NON-NLS-1$
-
- // Report similar values: Levensthein
- reportSimValsMode[1] = new Button(simValModeGroup, SWT.RADIO);
- reportSimValsMode[1].setSelection(prefs.getBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN));
- new Label(simValModeGroup, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.perform.simVals.levensthein")); //$NON-NLS-1$
-
- // Report similar values: precision level
- field = createFieldComposite(composite, indentPixels);
- new Label(field, SWT.NONE).setText(MessagesEditorPlugin.getString(
- "prefs.perform.simVals.precision")); //$NON-NLS-1$
- reportSimPrecision = new Text(field, SWT.BORDER);
- reportSimPrecision.setText(
- prefs.getString(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION));
- reportSimPrecision.setTextLimit(6);
- setWidthInChars(reportSimPrecision, 6);
- reportSimPrecision.addKeyListener(new DoubleTextValidatorKeyListener(
- MessagesEditorPlugin.getString(
- "prefs.perform.simVals.precision.error"), //$NON-NLS-1$
- 0, 1));
-
- refreshEnabledStatuses();
-
- return composite;
- }
-
- /**
- * Creates the items in the combo and select the item that matches the
- * current value.
- * @param combo
- * @param selectedLevel
- */
- private void populateCombo(Combo combo, int selectedLevel) {
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.ignore"));
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.info"));
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.warning"));
- combo.add(MessagesEditorPlugin.getString("prefs.perform.message.error"));
- combo.select(selectedLevel);
- GridData gridData = new GridData();
- gridData.grabExcessHorizontalSpace = true;
- gridData.horizontalAlignment = SWT.RIGHT;
- combo.setLayoutData(gridData);
- }
-
-
- /**
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
- prefs.setValue(MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL,
- reportMissingVals.getSelectionIndex());
- prefs.setValue(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL,
- reportDuplVals.getSelectionIndex());
- prefs.setValue(MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL,
- reportSimVals.getSelectionIndex());
- prefs.setValue(MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE,
- reportSimValsMode[0].getSelection());
- prefs.setValue(MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN,
- reportSimValsMode[1].getSelection());
- prefs.setValue(MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION,
- Double.parseDouble(reportSimPrecision.getText()));
- refreshEnabledStatuses();
- return super.performOk();
- }
-
-
- /**
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
- reportMissingVals.select(prefs.getDefaultInt(
- MsgEditorPreferences.REPORT_MISSING_VALUES_LEVEL));
- reportDuplVals.select(prefs.getDefaultInt(
- MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL));
- reportSimVals.select(prefs.getDefaultInt(
- MsgEditorPreferences.REPORT_SIM_VALUES_LEVEL));
- reportSimValsMode[0].setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_WORD_COMPARE));
- reportSimValsMode[1].setSelection(prefs.getDefaultBoolean(
- MsgEditorPreferences.REPORT_SIM_VALUES_LEVENSTHEIN));
- reportSimPrecision.setText(Double.toString(prefs.getDefaultDouble(
- MsgEditorPreferences.REPORT_SIM_VALUES_PRECISION)));
- refreshEnabledStatuses();
- super.performDefaults();
- }
-
- /*default*/ void refreshEnabledStatuses() {
- boolean isReportingSimilar = reportSimVals.getSelectionIndex()
- != MsgEditorPreferences.VALIDATION_MESSAGE_IGNORE;
-
- for (int i = 0; i < reportSimValsMode.length; i++) {
- reportSimValsMode[i].setEnabled(isReportingSimilar);
- }
- reportSimPrecision.setEnabled(isReportingSimilar);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyArguments.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyArguments.java
deleted file mode 100644
index f2c261d4..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyArguments.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-
-/**
- * This class contains the data that a processor provides to its rename resource
- * bundle key participants.
- */
-public class RenameKeyArguments extends RefactoringArguments {
-
- private String fNewName;
-
- private boolean fRenameChildKeys;
-
- private boolean fUpdateReferences;
-
- /**
- * Creates new rename arguments.
- *
- * @param newName
- * the new name of the element to be renamed
- * @param renameChildKeys
- * <code>true</code> if child keys are to be renamed;
- * <code>false</code> otherwise
- * @param updateReferences
- * <code>true</code> if reference updating is requested;
- * <code>false</code> otherwise
- */
- public RenameKeyArguments(String newName, boolean renameChildKeys, boolean updateReferences) {
- Assert.isNotNull(newName);
- fNewName= newName;
- fRenameChildKeys = renameChildKeys;
- fUpdateReferences= updateReferences;
- }
-
- /**
- * Returns the new element name.
- *
- * @return the new element name
- */
- public String getNewName() {
- return fNewName;
- }
-
- /**
- * Returns whether child keys are to be renamed or not.
- *
- * @return returns <code>true</code> if child keys are to be renamed;
- * <code>false</code> otherwise
- */
- public boolean getRenameChildKeys() {
- return fRenameChildKeys;
- }
-
- /**
- * Returns whether reference updating is requested or not.
- *
- * @return returns <code>true</code> if reference updating is requested;
- * <code>false</code> otherwise
- */
- public boolean getUpdateReferences() {
- return fUpdateReferences;
- }
-
- public String toString() {
- return "rename to " + fNewName //$NON-NLS-1$
- + (fRenameChildKeys ? " (rename child keys)" : " (don't rename child keys)") //$NON-NLS-1$//$NON-NLS-2$
- + (fUpdateReferences ? " (update references)" : " (don't update references)"); //$NON-NLS-1$//$NON-NLS-2$
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyChange.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyChange.java
deleted file mode 100644
index 8c956991..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyChange.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring;
-
-import java.text.MessageFormat;
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-
-/**
- * {@link Change} that renames a resource bundle key.
- */
-public class RenameKeyChange extends Change {
-
- private final MessagesBundleGroup fMessagesBundleGroup;
-
- private final String fNewName;
-
- private final boolean fRenameChildKeys;
-
- private final KeyTreeNode fKeyTreeNode;
-
- private ChangeDescriptor fDescriptor;
-
- /**
- * Creates the change.
- *
- * @param keyTreeNode the node in the model to rename
- * @param newName the new name. Must not be empty
- * @param renameChildKeys true if child keys are also to be renamed, false if just this one key is to be renamed
- */
- protected RenameKeyChange(MessagesBundleGroup messageBundleGroup, KeyTreeNode keyTreeNode, String newName, boolean renameChildKeys) {
- if (keyTreeNode == null || newName == null || newName.length() == 0) {
- throw new IllegalArgumentException();
- }
-
- fMessagesBundleGroup = messageBundleGroup;
- fKeyTreeNode= keyTreeNode;
- fNewName= newName;
- fRenameChildKeys = renameChildKeys;
- fDescriptor= null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#getDescriptor()
- */
- public ChangeDescriptor getDescriptor() {
- return fDescriptor;
- }
-
- /**
- * Sets the change descriptor to be returned by {@link Change#getDescriptor()}.
- *
- * @param descriptor the change descriptor
- */
- public void setDescriptor(ChangeDescriptor descriptor) {
- fDescriptor= descriptor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#getName()
- */
- public String getName() {
- return MessageFormat.format("Rename {0} to {1}", new Object [] { fKeyTreeNode.getMessageKey(), fNewName});
- }
-
- /**
- * Returns the new name.
- *
- * @return return the new name
- */
- public String getNewName() {
- return fNewName;
- }
-
- /**
- * This implementation of {@link Change#isValid(IProgressMonitor)} tests the modified resource using the validation method
- * specified by {@link #setValidationMethod(int)}.
- */
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- pm.beginTask("", 2); //$NON-NLS-1$
- try {
- RefactoringStatus result = new RefactoringStatus();
- return result;
- } finally {
- pm.done();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor)
- */
- public void initializeValidationData(IProgressMonitor pm) {
- }
-
- public Object getModifiedElement() {
- return "what is this for?";
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("Rename resource bundle key", 1);
-
- // Find the root - we will need this later
- KeyTreeNode root = (KeyTreeNode) fKeyTreeNode.getParent();
- while (root.getName() != null) {
- root = (KeyTreeNode) root.getParent();
- }
-
- if (fRenameChildKeys) {
- String key = fKeyTreeNode.getMessageKey();
- String keyPrefix = fKeyTreeNode.getMessageKey() + ".";
- Collection<KeyTreeNode> branchNodes = fKeyTreeNode.getBranch();
- for (KeyTreeNode branchNode : branchNodes) {
- String oldKey = branchNode.getMessageKey();
- if (oldKey.equals(key) || oldKey.startsWith(keyPrefix)) {
- String newKey = fNewName + oldKey.substring(key.length());
- fMessagesBundleGroup.renameMessageKeys(oldKey, newKey);
- }
- }
- } else {
- fMessagesBundleGroup.renameMessageKeys(fKeyTreeNode.getMessageKey(), fNewName);
- }
-
- String oldName= fKeyTreeNode.getMessageKey();
-
- // Find the node that was created with the new name
- String segments [] = fNewName.split("\\.");
- KeyTreeNode renamedKey = root;
- for (String segment : segments) {
- renamedKey = (KeyTreeNode) renamedKey.getChild(segment);
- }
-
- assert(renamedKey != null);
- return new RenameKeyChange(fMessagesBundleGroup, renamedKey, oldName, fRenameChildKeys);
- } finally {
- pm.done();
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyDescriptor.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyDescriptor.java
deleted file mode 100644
index 06a31bbc..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyDescriptor.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-
-/**
- * Refactoring descriptor for the rename resource bundle key refactoring.
- * <p>
- * An instance of this refactoring descriptor may be obtained by calling
- * {@link RefactoringContribution#createDescriptor()} on a refactoring
- * contribution requested by invoking
- * {@link RefactoringCore#getRefactoringContribution(String)} with the
- * refactoring id ({@link #ID}).
- */
-public final class RenameKeyDescriptor extends RefactoringDescriptor {
-
- public static final String ID = "org.eclipse.babel.editor.refactoring.renameKey"; //$NON-NLS-1$
-
- /** The name attribute */
- private String fNewName;
-
- private KeyTreeNode fKeyNode;
-
- private MessagesBundleGroup fMessagesBundleGroup;
-
- /** Configures if references will be updated */
- private boolean fRenameChildKeys;
-
- /**
- * Creates a new refactoring descriptor.
- * <p>
- * Clients should not instantiated this class but use {@link RefactoringCore#getRefactoringContribution(String)}
- * with {@link #ID} to get the contribution that can create the descriptor.
- * </p>
- */
- public RenameKeyDescriptor() {
- super(ID, null, "N/A", null, RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE);
- fNewName = null;
- }
-
- /**
- * Sets the new name to rename the resource to.
- *
- * @param name
- * the non-empty new name to set
- */
- public void setNewName(final String name) {
- Assert.isNotNull(name);
- Assert.isLegal(!"".equals(name), "Name must not be empty"); //$NON-NLS-1$//$NON-NLS-2$
- fNewName = name;
- }
-
- /**
- * Returns the new name to rename the resource to.
- *
- * @return
- * the new name to rename the resource to
- */
- public String getNewName() {
- return fNewName;
- }
-
- /**
- * Sets the project name of this refactoring.
- * <p>
- * Note: If the resource to be renamed is of type {@link IResource#PROJECT},
- * clients are required to to set the project name to <code>null</code>.
- * </p>
- * <p>
- * The default is to associate the refactoring with the workspace.
- * </p>
- *
- * @param project
- * the non-empty project name to set, or <code>null</code> for
- * the workspace
- *
- * @see #getProject()
- */
-// public void setProject(final String project) {
-// super.setProject(project);
-// }
-
- /**
- * If set to <code>true</code>, this rename will also rename child keys. The default is to rename child keys.
- *
- * @param renameChildKeys <code>true</code> if this rename will rename child keys
- */
- public void setRenameChildKeys(boolean renameChildKeys) {
- fRenameChildKeys = renameChildKeys;
- }
-
- public void setRenameChildKeys(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
- this.fKeyNode = keyNode;
- this.fMessagesBundleGroup = messagesBundleGroup;
- }
-
- /**
- * Returns if this rename will also rename child keys
- *
- * @return returns <code>true</code> if this rename will rename child keys
- */
- public boolean isRenameChildKeys() {
- return fRenameChildKeys;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.RefactoringDescriptor#createRefactoring(org.eclipse.ltk.core.refactoring.RefactoringStatus)
- */
- public Refactoring createRefactoring(RefactoringStatus status) throws CoreException {
-
- String newName= getNewName();
- if (newName == null || newName.length() == 0) {
- status.addFatalError("The rename resource bundle key refactoring can not be performed as the new name is invalid");
- return null;
- }
- RenameKeyProcessor processor = new RenameKeyProcessor(fKeyNode, fMessagesBundleGroup);
- processor.setNewResourceName(newName);
- processor.setRenameChildKeys(fRenameChildKeys);
-
- return new RenameRefactoring(processor);
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyProcessor.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyProcessor.java
deleted file mode 100644
index b2b17057..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyProcessor.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring;
-
-import java.text.MessageFormat;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * A rename processor for {@link IResource}. The processor will rename the resource and
- * load rename participants if references should be renamed as well.
- *
- * @since 3.4
- */
-public class RenameKeyProcessor extends RenameProcessor {
-
- private KeyTreeNode fKeyNode;
-
- private MessagesBundleGroup fMessageBundleGroup;
-
- private String fNewResourceName;
-
- private boolean fRenameChildKeys;
-
- private RenameKeyArguments fRenameArguments; // set after checkFinalConditions
-
- /**
- * Creates a new rename resource processor.
- *
- * @param keyNode the resource to rename.
- * @param messagesBundleGroup
- */
- public RenameKeyProcessor(KeyTreeNode keyNode, MessagesBundleGroup messagesBundleGroup) {
- if (keyNode == null) {
- throw new IllegalArgumentException("key node must not be null"); //$NON-NLS-1$
- }
-
- fKeyNode = keyNode;
- fMessageBundleGroup = messagesBundleGroup;
- fRenameArguments= null;
- fRenameChildKeys= true;
- setNewResourceName(keyNode.getMessageKey()); // Initialize new name
- }
-
- /**
- * Returns the new key node
- *
- * @return the new key node
- */
- public KeyTreeNode getNewKeyTreeNode() {
- return fKeyNode;
- }
-
- /**
- * Returns the new resource name
- *
- * @return the new resource name
- */
- public String getNewResourceName() {
- return fNewResourceName;
- }
-
- /**
- * Sets the new resource name
- *
- * @param newName the new resource name
- */
- public void setNewResourceName(String newName) {
- Assert.isNotNull(newName);
- fNewResourceName= newName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- /*
- * This method allows fatal and non-fatal problems to be shown to
- * the user. Currently there are none so we return null to indicate
- * this.
- */
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- fRenameArguments = new RenameKeyArguments(getNewResourceName(), fRenameChildKeys, false);
-
- ResourceChangeChecker checker = (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IResourceChangeDescriptionFactory deltaFactory = checker.getDeltaFactory();
-
- // TODO figure out what we want to do here....
-// ResourceModifications.buildMoveDelta(deltaFactory, fKeyNode, fRenameArguments);
-
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- /**
- * Validates if the a name is valid. This method does not change the name settings on the refactoring. It is intended to be used
- * in a wizard to validate user input.
- *
- * @param newName the name to validate
- * @return returns the resulting status of the validation
- */
- public RefactoringStatus validateNewElementName(String newName) {
- Assert.isNotNull(newName);
-
- if (newName.length() == 0) {
- return RefactoringStatus.createFatalErrorStatus("New name for key must be entered");
- }
- if (newName.startsWith(".")) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot start with a '.'");
- }
- if (newName.endsWith(".")) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot end with a '.'");
- }
-
- String [] parts = newName.split("\\.");
- for (String part : parts) {
- if (part.length() == 0) {
- return RefactoringStatus.createFatalErrorStatus("Key cannot contain an empty part between two periods");
- }
- if (!part.matches("([A-Z]|[a-z]|[0-9])*")) {
- return RefactoringStatus.createFatalErrorStatus("Key can contain only letters, digits, and periods");
- }
- }
-
- if (fMessageBundleGroup.isMessageKey(newName)) {
- return RefactoringStatus.createFatalErrorStatus(MessagesEditorPlugin.getString("dialog.error.exists"));
- }
-
- return new RefactoringStatus();
- }
-
- protected RenameKeyDescriptor createDescriptor() {
- RenameKeyDescriptor descriptor= new RenameKeyDescriptor();
- descriptor.setDescription(MessageFormat.format("Rename resource bundle key ''{0}''", fKeyNode.getMessageKey()));
- descriptor.setComment(MessageFormat.format("Rename resource ''{0}'' to ''{1}''", new Object[] { fKeyNode.getMessageKey(), fNewResourceName }));
- descriptor.setFlags(RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE);
- descriptor.setNewName(getNewResourceName());
- descriptor.setRenameChildKeys(fRenameChildKeys);
- return descriptor;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- RenameKeyChange change = new RenameKeyChange(fMessageBundleGroup, getNewKeyTreeNode(), fNewResourceName, fRenameChildKeys);
- change.setDescriptor(new RefactoringChangeDescriptor(createDescriptor()));
- return change;
- } finally {
- pm.done();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
- */
- public Object[] getElements() {
- return new Object[] { fKeyNode };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getIdentifier()
- */
- public String getIdentifier() {
- return "org.eclipse.babel.editor.refactoring.renameKeyProcessor"; //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
- */
- public String getProcessorName() {
- return "Rename Resource Bundle Key";
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
- */
- public boolean isApplicable() {
- if (this.fKeyNode == null)
- return false;
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus, org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
- */
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- // TODO: figure out participants to return here
- return new RefactoringParticipant[0];
-
-// String[] affectedNatures= ResourceProcessors.computeAffectedNatures(fResource);
-// return ParticipantManager.loadRenameParticipants(status, this, fResource, fRenameArguments, null, affectedNatures, shared);
- }
-
- /**
- * Returns <code>true</code> if the refactoring processor also renames the child keys
- *
- * @return <code>true</code> if the refactoring processor also renames the child keys
- */
- public boolean getRenameChildKeys() {
- return fRenameChildKeys;
- }
-
- /**
- * Specifies if the refactoring processor also updates the child keys.
- * The default behaviour is to update the child keys.
- *
- * @param renameChildKeys <code>true</code> if the refactoring processor should also rename the child keys
- */
- public void setRenameChildKeys(boolean renameChildKeys) {
- fRenameChildKeys = renameChildKeys;
- }
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyWizard.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyWizard.java
deleted file mode 100644
index d98a12be..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/refactoring/RenameKeyWizard.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Nigel Westbury
- * All rights reserved. This program and the accompanying materials
- * are made available under the 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:
- * Nigel Westbury - initial implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring;
-
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * A wizard for the rename bundle key refactoring.
- */
-public class RenameKeyWizard extends RefactoringWizard {
-
- /**
- * Creates a {@link RenameKeyWizard}.
- *
- * @param resource
- * the bundle key to rename
- * @param refactoring
- */
- public RenameKeyWizard(KeyTreeNode resource, RenameKeyProcessor refactoring) {
- super(new RenameRefactoring(refactoring), DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle("Rename Resource Bundle Key");
- setWindowTitle("Rename Resource Bundle Key");
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
- RenameKeyProcessor processor = (RenameKeyProcessor) getRefactoring().getAdapter(RenameKeyProcessor.class);
- addPage(new RenameResourceRefactoringConfigurationPage(processor));
- }
-
- private static class RenameResourceRefactoringConfigurationPage extends UserInputWizardPage {
-
- private final RenameKeyProcessor fRefactoringProcessor;
- private Text fNameField;
-
- public RenameResourceRefactoringConfigurationPage(RenameKeyProcessor processor) {
- super("RenameResourceRefactoringInputPage"); //$NON-NLS-1$
- fRefactoringProcessor= processor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setFont(parent.getFont());
-
- Label label = new Label(composite, SWT.NONE);
- label.setText("New name:");
- label.setLayoutData(new GridData());
-
- fNameField = new Text(composite, SWT.BORDER);
- fNameField.setText(fRefactoringProcessor.getNewResourceName());
- fNameField.setFont(composite.getFont());
- fNameField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
- fNameField.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
- });
-
- final Button includeChildKeysCheckbox = new Button(composite, SWT.CHECK);
- if (fRefactoringProcessor.getNewKeyTreeNode().isUsedAsKey()) {
- if (fRefactoringProcessor.getNewKeyTreeNode().getChildren().length == 0) {
- // This is an actual key with no child keys.
- includeChildKeysCheckbox.setSelection(false);
- includeChildKeysCheckbox.setEnabled(false);
- } else {
- // This is both an actual key and it has child keys, so we
- // let the user choose whether to also rename the child keys.
- includeChildKeysCheckbox.setSelection(fRefactoringProcessor.getRenameChildKeys());
- includeChildKeysCheckbox.setEnabled(true);
- }
- } else {
- // This is no an actual key, just a containing node, so the option
- // to rename child keys must be set (otherwise this rename would not
- // do anything).
- includeChildKeysCheckbox.setSelection(true);
- includeChildKeysCheckbox.setEnabled(false);
- }
-
- includeChildKeysCheckbox.setText("Also rename child keys (other keys with this key as a prefix)");
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- includeChildKeysCheckbox.setLayoutData(gd);
- includeChildKeysCheckbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- fRefactoringProcessor.setRenameChildKeys(includeChildKeysCheckbox.getSelection());
- }
- });
-
- fNameField.selectAll();
- setPageComplete(false);
- setControl(composite);
- }
-
- public void setVisible(boolean visible) {
- if (visible) {
- fNameField.setFocus();
- }
- super.setVisible(visible);
- }
-
- protected final void validatePage() {
- String text= fNameField.getText();
- RefactoringStatus status= fRefactoringProcessor.validateNewElementName(text);
- setPageComplete(status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#performFinish()
- */
- protected boolean performFinish() {
- initializeRefactoring();
- storeSettings();
- return super.performFinish();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#getNextPage()
- */
- public IWizardPage getNextPage() {
- initializeRefactoring();
- storeSettings();
- return super.getNextPage();
- }
-
- private void storeSettings() {
- }
-
- private void initializeRefactoring() {
- fRefactoringProcessor.setNewResourceName(fNameField.getText());
- }
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/EclipsePropertiesEditorResource.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/EclipsePropertiesEditorResource.java
deleted file mode 100644
index 1baea5a1..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/EclipsePropertiesEditorResource.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.resource;
-
-import java.util.Locale;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.resource.AbstractPropertiesResource;
-import org.eclipse.babel.core.message.resource.ser.PropertiesDeserializer;
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.editors.text.TextEditor;
-
-
-/**
- * Editor which contains file content being edited, which may not be saved yet
- * which may not take effect in a IResource (which make a difference with
- * markers).
- * @author Pascal Essiembre
- *
- */
-public class EclipsePropertiesEditorResource extends AbstractPropertiesResource {
-
- private TextEditor textEditor;
- /** label of the location of the resource edited here.
- * When null, try to locate the resource and use it to return that label. */
- private String _resourceLocationLabel;
-
- /**
- * Constructor.
- * @param locale the resource locale
- * @param serializer resource serializer
- * @param deserializer resource deserializer
- * @param textEditor the editor
- */
- public EclipsePropertiesEditorResource(
- Locale locale,
- PropertiesSerializer serializer,
- PropertiesDeserializer deserializer,
- TextEditor textEditor) {
- super(locale, serializer, deserializer);
- this.textEditor = textEditor;
-
- //FIXME: [hugues] this should happen only once at the plugin level?
- //for now it does nothing. Remove it all?
-// IResourceChangeListener rcl = new IResourceChangeListener() {
-// public void resourceChanged(IResourceChangeEvent event) {
-// IResource resource = event.getResource();
-// System.out.println("RESOURCE CHANGED:" + resource);
-// if (resource != null && resource.getFileExtension().equals("escript")) {
-// // run the compiler
-// }
-// }
-// };
-// ResourcesPlugin.getWorkspace().addResourceChangeListener(rcl);
-
- // [alst] do we really need this? It causes an endless loop!
-// IDocument document = textEditor.getDocumentProvider().getDocument(
-// textEditor.getEditorInput());
-// System.out.println("DOCUMENT:" + document);
-// document.addDocumentListener(new IDocumentListener() {
-// public void documentAboutToBeChanged(DocumentEvent event) {
-// //do nothing
-// System.out.println("DOCUMENT ABOUT to CHANGE:");
-// }
-// public void documentChanged(DocumentEvent event) {
-// System.out.println("DOCUMENT CHANGED:");
-//// fireResourceChange(EclipsePropertiesEditorResource.this);
-// }
-// });
-
-// IDocumentProvider docProvider = textEditor.getDocumentProvider();
-//// PropertiesFileDocumentProvider
-// // textEditor.getEditorInput().
-//
-//// textEditor.sets
-//
-// docProvider.addElementStateListener(new IElementStateListener() {
-// public void elementContentAboutToBeReplaced(Object element) {
-// System.out.println("about:" + element);
-// }
-// public void elementContentReplaced(Object element) {
-// System.out.println("replaced:" + element);
-// }
-// public void elementDeleted(Object element) {
-// System.out.println("deleted:" + element);
-// }
-// public void elementDirtyStateChanged(Object element, boolean isDirty) {
-// System.out.println("dirty:" + element + " " + isDirty);
-// }
-// public void elementMoved(Object originalElement, Object movedElement) {
-// System.out.println("moved from:" + originalElement
-// + " to " + movedElement);
-// }
-// });
-
-
-// textEditor.addPropertyListener(new IPropertyListener() {
-// public void propertyChanged(Object source, int propId) {
-// System.out.println(
-// "text editor changed. source:"
-// + source
-// + " propId: " + propId);
-// fireResourceChange(EclipsePropertiesEditorResource.this);
-// }
-// });
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.resource.TextResource#getText()
- */
- public String getText() {
- return textEditor.getDocumentProvider().getDocument(
- textEditor.getEditorInput()).get();
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.resource.TextResource#setText(
- * java.lang.String)
- */
- public void setText(final String content) {
- /*
- * We may come in from an event from another thread, so ensure
- * we are on the UI thread. This may not be the best place to do
- * this???
- */
- // [alst] muss 2x speichern wenn async exec
-// Display.getDefault().asyncExec(new Runnable() {
-// public void run() {
- if (DirtyHack.isEditorModificationEnabled()) {
- textEditor.getDocumentProvider()
- .getDocument(textEditor.getEditorInput()).set(content);
- }
-// }
-// });
- }
-
- /**
- * @see org.eclipse.babel.core.bundle.resource.IMessagesResource#getSource()
- */
- public Object getSource() {
- return textEditor;
- }
-
- public IResource getResource() {
- IEditorInput input = textEditor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- return ((IFileEditorInput) input).getFile();
- }
- return null;
- }
-
- /**
- * @return The resource location label. or null if unknown.
- */
- public String getResourceLocationLabel() {
- if (_resourceLocationLabel != null) {
- return _resourceLocationLabel;
- }
- IResource resource = getResource();
- if (resource != null) {
- return resource.getFullPath().toString();
- }
- return null;
- }
-
- /**
- * @param resourceLocationLabel The label of the location of the edited resource.
- */
- public void setResourceLocationLabel(String resourceLocationLabel) {
- _resourceLocationLabel = resourceLocationLabel;
- }
-
- /**
- * Called before this object will be discarded.
- * Nothing to do: we were not listening to changes to this file ourselves.
- */
- public void dispose() {
- //nothing to do.
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/FileMarkerStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/FileMarkerStrategy.java
deleted file mode 100644
index 6e9c3dbb..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/FileMarkerStrategy.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator;
-
-import org.eclipse.babel.core.message.MessagesBundle;
-import org.eclipse.babel.core.message.checks.DuplicateValueCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
-import org.eclipse.babel.core.util.BabelUtils;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class FileMarkerStrategy implements IValidationMarkerStrategy {
-
-
- /**
- * @see org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck)
- */
- public void markFailed(ValidationFailureEvent event) {
- if (event.getCheck() instanceof MissingValueCheck) {
- MessagesBundle bundle = (MessagesBundle) event.getBundleGroup().getMessagesBundle(event.getLocale());
- addMarker((IResource) bundle.getResource().getSource(),
-// addMarker(event.getResource(),
- event.getKey(),
- "Key \"" + event.getKey() //$NON-NLS-1$
- + "\" is missing a value.", //$NON-NLS-1$
- getSeverity(MsgEditorPreferences.getInstance()
- .getReportMissingValuesLevel()));
-
- } else if (event.getCheck() instanceof DuplicateValueCheck) {
- String duplicates = BabelUtils.join(
- ((DuplicateValueCheck) event.getCheck())
- .getDuplicateKeys(), ", ");
- MessagesBundle bundle = (MessagesBundle) event.getBundleGroup().getMessagesBundle(event.getLocale());
- addMarker((IResource) bundle.getResource().getSource(),
-// addMarker(event.getResource(),
- event.getKey(),
- "Key \"" + event.getKey() //$NON-NLS-1$
- + "\" duplicates " + duplicates, //$NON-NLS-1$
- getSeverity(MsgEditorPreferences.getInstance()
- .getReportDuplicateValuesLevel()));
- }
- }
-
- private void addMarker(
- IResource resource,
- String key,
- String message, //int lineNumber,
- int severity) {
- try {
- //TODO move MARKER_TYPE elsewhere.
- IMarker marker = resource.createMarker(MessagesEditorPlugin.MARKER_TYPE);
- marker.setAttribute(IMarker.MESSAGE, message);
- marker.setAttribute(IMarker.SEVERITY, severity);
- marker.setAttribute(IMarker.LOCATION, key);
-// if (lineNumber == -1) {
-// lineNumber = 1;
-// }
-// marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
- } catch (CoreException e) {
- throw new RuntimeException("Cannot add marker.", e); //$NON-NLS-1$
- }
- }
-
- /**
- * Translates the validation level as defined in
- * MsgEditorPreferences.VALIDATION_MESSAGE_* to the corresponding value
- * for the marker attribute IMarke.SEVERITY.
- * @param msgValidationLevel
- * @return The value for the marker attribute IMarker.SEVERITY.
- */
- private static int getSeverity(int msgValidationLevel) {
- switch (msgValidationLevel) {
- case MsgEditorPreferences.VALIDATION_MESSAGE_ERROR:
- return IMarker.SEVERITY_ERROR;
- case MsgEditorPreferences.VALIDATION_MESSAGE_WARNING:
- return IMarker.SEVERITY_WARNING;
- case MsgEditorPreferences.VALIDATION_MESSAGE_INFO:
- return IMarker.SEVERITY_INFO;
- case MsgEditorPreferences.VALIDATION_MESSAGE_IGNORE:
- default:
- return IMarker.SEVERITY_INFO;//why are we here?
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/IValidationMarkerStrategy.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/IValidationMarkerStrategy.java
deleted file mode 100644
index d466cfee..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/IValidationMarkerStrategy.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public interface IValidationMarkerStrategy {
-
- void markFailed(ValidationFailureEvent event);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/MessagesBundleGroupValidator.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/MessagesBundleGroupValidator.java
deleted file mode 100644
index 2a8c536a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/MessagesBundleGroupValidator.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator;
-
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.checks.DuplicateValueCheck;
-import org.eclipse.babel.core.message.checks.MissingValueCheck;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class MessagesBundleGroupValidator {
-
- //TODO Re-think... ??
-
- public static void validate(
- MessagesBundleGroup messagesBundleGroup,
- Locale locale,
- IValidationMarkerStrategy markerStrategy) {
- //TODO check if there is a matching EclipsePropertiesEditorResource already open.
- //else, create MessagesBundle from PropertiesIFileResource
-
- DuplicateValueCheck duplicateCheck =
- MsgEditorPreferences.getInstance().getReportDuplicateValues()
- ? new DuplicateValueCheck()
- : null;
- String[] keys = messagesBundleGroup.getMessageKeys();
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
- if (MsgEditorPreferences.getInstance().getReportMissingValues()) {
- if (MissingValueCheck.MISSING_KEY.checkKey(
- messagesBundleGroup,
- messagesBundleGroup.getMessage(key, locale))) {
- markerStrategy.markFailed(new ValidationFailureEvent(
- messagesBundleGroup, locale, key,
- MissingValueCheck.MISSING_KEY));
- }
- }
- if (duplicateCheck != null) {
- if (!MsgEditorPreferences.getInstance().getReportDuplicateValuesOnlyInRootLocales()
- || (locale == null || locale.toString().length() == 0)) {
- //either the locale is the root locale either
- //we report duplicated on all the locales anyways.
- if (duplicateCheck.checkKey(
- messagesBundleGroup,
- messagesBundleGroup.getMessage(key, locale))) {
- markerStrategy.markFailed(new ValidationFailureEvent(
- messagesBundleGroup, locale, key, duplicateCheck));
- }
- duplicateCheck.reset();
- }
- }
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/ValidationFailureEvent.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/ValidationFailureEvent.java
deleted file mode 100644
index b01b642a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/resource/validator/ValidationFailureEvent.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.resource.validator;
-
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.checks.IMessageCheck;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class ValidationFailureEvent {
-
- private final MessagesBundleGroup messagesBundleGroup;
- private final Locale locale;
- private final String key;
-// private final IResource resource;
- private final IMessageCheck check;
- /**
- * @param messagesBundleGroup
- * @param locale
- * @param key
- * @param resource
- * @param check not null
- */
- /*default*/ ValidationFailureEvent(
- final MessagesBundleGroup messagesBundleGroup,
- final Locale locale,
- final String key,
-// final IResource resource,
- final IMessageCheck check) {
- super();
- this.messagesBundleGroup = messagesBundleGroup;
- this.locale = locale;
- this.key = key;
-// this.resource = resource;
- this.check = check;
- }
- /**
- * @return the messagesBundleGroup
- */
- public MessagesBundleGroup getBundleGroup() {
- return messagesBundleGroup;
- }
- /**
- * @return the check, never null
- */
- public IMessageCheck getCheck() {
- return check;
- }
- /**
- * @return the key
- */
- public String getKey() {
- return key;
- }
- /**
- * @return the locale
- */
- public Locale getLocale() {
- return locale;
- }
-
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeContentProvider.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeContentProvider.java
deleted file mode 100644
index e57ac17e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeContentProvider.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-
-/**
- * Content provider for key tree viewer.
- * @author Pascal Essiembre
- */
-public class KeyTreeContentProvider implements ITreeContentProvider {
-
- private AbstractKeyTreeModel keyTreeModel;
- private Viewer viewer;
- private TreeType treeType;
-
- /**
- * @param treeType
- *
- */
- public KeyTreeContentProvider(TreeType treeType) {
- this.treeType = treeType;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(
- * java.lang.Object)
- */
- public Object[] getChildren(Object parentElement) {
- KeyTreeNode parentNode = (KeyTreeNode) parentElement;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren(parentNode);
- case Flat:
- return new KeyTreeNode[0];
- default:
- // Should not happen
- return new KeyTreeNode[0];
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#
- * getParent(java.lang.Object)
- */
- public Object getParent(Object element) {
- KeyTreeNode node = (KeyTreeNode) element;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getParent(node);
- case Flat:
- return keyTreeModel;
- default:
- // Should not happen
- return null;
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#
- * hasChildren(java.lang.Object)
- */
- public boolean hasChildren(Object element) {
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren((KeyTreeNode) element).length > 0;
- case Flat:
- return false;
- default:
- // Should not happen
- return false;
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#
- * getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- switch (treeType) {
- case Tree:
- return 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 KeyTreeNode[0];
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- public void dispose() {}
-
- /**
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(
- * org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (TreeViewer) viewer;
- this.keyTreeModel = (AbstractKeyTreeModel) newInput;
- }
-
- public TreeType getTreeType() {
- return treeType;
- }
-
- public void setTreeType(TreeType treeType) {
- if (this.treeType != treeType) {
- this.treeType = treeType;
- viewer.refresh();
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeContributor.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeContributor.java
deleted file mode 100644
index 6c005c03..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeContributor.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree;
-
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.IKeyTreeModelListener;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.IMessagesEditorChangeListener;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorChangeAdapter;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorMarkers;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.AddKeyAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.DeleteKeyAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.RenameKeyAction;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeContributor;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class KeyTreeContributor implements IKeyTreeContributor {
-
- private MessagesEditor editor;
- private AbstractKeyTreeModel treeModel;
- private TreeType treeType;
-
- /**
- *
- */
- public KeyTreeContributor(final MessagesEditor editor) {
- super();
- this.editor = editor;
- this.treeModel = new AbstractKeyTreeModel(editor.getBundleGroup());
- this.treeType = TreeType.Tree;
- }
-
- /**
- *
- */
- public void contribute(final TreeViewer treeViewer) {
-
- KeyTreeContentProvider contentProvider = new KeyTreeContentProvider(treeType);
- treeViewer.setContentProvider(contentProvider);
- treeViewer.setLabelProvider(new KeyTreeLabelProvider(editor, treeModel, contentProvider));
- if (treeViewer.getInput() == null)
- treeViewer.setUseHashlookup(true);
-
- ViewerFilter onlyUnusedAndMissingKeysFilter = new OnlyUnsuedAndMissingKey();
- ViewerFilter[] filters = {onlyUnusedAndMissingKeysFilter};
- treeViewer.setFilters(filters);
-
-// IKeyBindingService service = editor.getSite().getKeyBindingService();
-// service.setScopes(new String[]{"org.eclilpse.babel.editor.editor.tree"});
-
- contributeActions(treeViewer);
-
- contributeKeySync(treeViewer);
-
- contributeModelChanges(treeViewer);
-
- contributeDoubleClick(treeViewer);
-
- contributeMarkers(treeViewer);
-
- // Set input model
- treeViewer.setInput(treeModel);
- treeViewer.expandAll();
- }
-
- private class OnlyUnsuedAndMissingKey extends ViewerFilter implements
- AbstractKeyTreeModel.IKeyTreeNodeLeafFilter {
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
- */
- public boolean select(Viewer viewer, Object parentElement,
- Object element) {
- if (editor.isShowOnlyUnusedAndMissingKeys() == IMessagesEditorChangeListener.SHOW_ALL
- || !(element instanceof KeyTreeNode)) {
- //no filtering. the element is displayed by default.
- return true;
- }
- if (editor.getI18NPage() != null && editor.getI18NPage().isKeyTreeVisible()) {
- return editor.getKeyTreeModel().isBranchFiltered(this, (KeyTreeNode)element);
- } else {
- return isFilteredLeaf((KeyTreeNode)element);
- }
- }
-
- /**
- * @param node
- * @return true if this node should be in the filter. Does not navigate the tree
- * of KeyTreeNode. false unless the node is a missing or unused key.
- */
- public boolean isFilteredLeaf(IKeyTreeNode node) {
- MessagesEditorMarkers markers = KeyTreeContributor.this.editor.getMarkers();
- String key = node.getMessageKey();
- boolean missingOrUnused = markers.isMissingOrUnusedKey(key);
- if (!missingOrUnused) {
- return false;
- }
- switch (editor.isShowOnlyUnusedAndMissingKeys()) {
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING_AND_UNUSED:
- return missingOrUnused;
- case IMessagesEditorChangeListener.SHOW_ONLY_MISSING:
- return !markers.isUnusedKey(key, missingOrUnused);
- case IMessagesEditorChangeListener.SHOW_ONLY_UNUSED:
- return markers.isUnusedKey(key, missingOrUnused);
- default:
- return false;
- }
- }
-
- }
-
-
- /**
- * Contributes markers.
- * @param treeViewer tree viewer
- */
- private void contributeMarkers(final TreeViewer treeViewer) {
- editor.getMarkers().addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh();
- }
- });
- }
- });
-// editor.addChangeListener(new MessagesEditorChangeAdapter() {
-// public void editorDisposed() {
-// editor.getMarkers().clear();
-// }
-// });
-
-
-
-
-
-
-
-
-// final IMarkerListener markerListener = new IMarkerListener() {
-// public void markerAdded(IMarker marker) {
-// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
-// public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
-// treeViewer.refresh(true);
-// }
-// }
-// });
-// }
-// public void markerRemoved(IMarker marker) {
-// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable () {
-// public void run() {
-// if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
-// treeViewer.refresh(true);
-// }
-// }
-// });
-// }
-// };
-// editor.getMarkerManager().addMarkerListener(markerListener);
-// editor.addChangeListener(new MessagesEditorChangeAdapter() {
-// public void editorDisposed() {
-// editor.getMarkerManager().removeMarkerListener(markerListener);
-// }
-// });
- }
-
-
-
- /**
- * Contributes double-click support, expanding/collapsing nodes.
- * @param treeViewer tree viewer
- */
- private void contributeDoubleClick(final TreeViewer treeViewer) {
- treeViewer.getTree().addMouseListener(new MouseAdapter() {
- public void mouseDoubleClick(MouseEvent event) {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
- Object element = selection.getFirstElement();
- if (treeViewer.isExpandable(element)) {
- if (treeViewer.getExpandedState(element)) {
- treeViewer.collapseToLevel(element, 1);
- } else {
- treeViewer.expandToLevel(element, 1);
- }
- }
- }
- });
- }
-
- /**
- * Contributes key synchronization between editor and tree selected keys.
- * @param treeViewer tree viewer
- */
- private void contributeModelChanges(final TreeViewer treeViewer) {
- final IKeyTreeModelListener keyTreeListener = new IKeyTreeModelListener() {
- //TODO be smarter about refreshes.
- public void nodeAdded(KeyTreeNode node) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh(true);
- }
- });
- };
-// public void nodeChanged(KeyTreeNode node) {
-// treeViewer.refresh(true);
-// };
- public void nodeRemoved(KeyTreeNode node) {
- Display.getDefault().asyncExec(new Runnable(){
- public void run() {
- treeViewer.refresh(true);
- }
- });
- };
- };
- treeModel.addKeyTreeModelListener(keyTreeListener);
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, AbstractKeyTreeModel newModel) {
- oldModel.removeKeyTreeModelListener(keyTreeListener);
- newModel.addKeyTreeModelListener(keyTreeListener);
- treeViewer.setInput(newModel);
- treeViewer.refresh();
- }
- public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) {
- treeViewer.refresh();
- }
- });
- }
-
- /**
- * Contributes key synchronization between editor and tree selected keys.
- * @param treeViewer tree viewer
- */
- private void contributeKeySync(final TreeViewer treeViewer) {
- // changes in tree selected key update the editor
- treeViewer.getTree().addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
- if (selection != null && selection.getFirstElement() != null) {
- KeyTreeNode node =
- (KeyTreeNode) selection.getFirstElement();
- System.out.println("viewer key/hash:" + node.getMessageKey() + "/" + node.hashCode());
- editor.setSelectedKey(node.getMessageKey());
- } else {
- editor.setSelectedKey(null);
- }
- }
- });
- // changes in editor selected key updates the tree
- editor.addChangeListener(new MessagesEditorChangeAdapter() {
- public void selectedKeyChanged(String oldKey, String newKey) {
- ITreeContentProvider provider =
- (ITreeContentProvider) treeViewer.getContentProvider();
- if (provider != null) { // alst workaround
- KeyTreeNode node = findKeyTreeNode(
- provider, provider.getElements(null), newKey);
-
- // String[] test = newKey.split("\\.");
- // treeViewer.setSelection(new StructuredSelection(test), true);
-
-
- if (node != null) {
- treeViewer.setSelection(new StructuredSelection(node),
- true);
- treeViewer.getTree().showSelection();
- }
- }
- }
- });
- }
-
-
-
- /**
- * Contributes actions to the tree.
- * @param treeViewer tree viewer
- */
- private void contributeActions(final TreeViewer treeViewer) {
- Tree tree = treeViewer.getTree();
-
- // Add menu
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(tree);
-
- // Add
- final IAction addAction = new AddKeyAction(editor, treeViewer);
- menuManager.add(addAction);
- // Delete
- final IAction deleteAction = new DeleteKeyAction(editor, treeViewer);
- menuManager.add(deleteAction);
- // Rename
- final IAction renameAction = new RenameKeyAction(editor, treeViewer);
- menuManager.add(renameAction);
-
- menuManager.update(true);
- tree.setMenu(menu);
-
- // Bind actions to tree
- tree.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- if (event.character == SWT.DEL) {
- deleteAction.run();
- } else if (event.keyCode == SWT.F2) {
- renameAction.run();
- }
- }
- });
- }
-
- private KeyTreeNode findKeyTreeNode(
- ITreeContentProvider provider, Object[] nodes, String key) {
- for (int i = 0; i < nodes.length; i++) {
- KeyTreeNode node = (KeyTreeNode) nodes[i];
- if (node.getMessageKey().equals(key)) {
- return node;
- }
- node = findKeyTreeNode(provider, provider.getChildren(node), key);
- if (node != null) {
- return node;
- }
- }
- return null;
- }
-
- public IKeyTreeNode getKeyTreeNode(String key) {
- return getKeyTreeNode(key, null);
- }
-
- // TODO, think about a hashmap
- private IKeyTreeNode getKeyTreeNode(String key, IKeyTreeNode node) {
- if (node == null) {
- for (IKeyTreeNode ktn : treeModel.getRootNodes()) {
- String id = ktn.getMessageKey();
- if (key.equals(id)) {
- return ktn;
- } else {
- getKeyTreeNode(key, ktn);
- }
- }
- } else {
- for (IKeyTreeNode ktn : node.getChildren()) {
- String id = ktn.getMessageKey();
- if (key.equals(id)) {
- return ktn;
- } else {
- getKeyTreeNode(key, ktn);
- }
- }
- }
- return null;
- }
-
- public IKeyTreeNode[] getRootKeyItems() {
- return treeModel.getRootNodes();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeLabelProvider.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeLabelProvider.java
deleted file mode 100644
index 3505852f..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/KeyTreeLabelProvider.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree;
-
-import java.util.Collection;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.checks.IMessageCheck;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.IFontProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditorMarkers;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.OverlayImageIcon;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-
-/**
- * Label provider for key tree viewer.
- * @author Pascal Essiembre
- */
-public class KeyTreeLabelProvider
- extends LabelProvider implements IFontProvider, IColorProvider {
-
- private static final int KEY_DEFAULT = 1 << 1;
- private static final int KEY_COMMENTED = 1 << 2;
- private static final int KEY_VIRTUAL = 1 << 3;
- private static final int BADGE_WARNING = 1 << 4;
- private static final int BADGE_WARNING_GREY = 1 << 5;
-
- /** Registry instead of UIUtils one for image not keyed by file name. */
- private static ImageRegistry imageRegistry = new ImageRegistry();
-
-
- private MessagesEditor editor;
- private MessagesBundleGroup messagesBundleGroup;
-
- /**
- * This label provider keeps a reference to the content provider.
- * This is only because the way the nodes are labeled depends on whether
- * the node is being displayed in a tree or a flat structure.
- * <P>
- * This label provider does not have to listen to changes in the tree/flat
- * selection because such a change would cause the content provider to do
- * a full refresh anyway.
- */
- private KeyTreeContentProvider contentProvider;
-
- /**
- *
- */
- public KeyTreeLabelProvider(
- MessagesEditor editor,
- AbstractKeyTreeModel treeModel,
- KeyTreeContentProvider contentProvider) {
- super();
- this.editor = editor;
- this.messagesBundleGroup = editor.getBundleGroup();
- this.contentProvider = contentProvider;
- }
-
- /**
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- if (element instanceof KeyTreeNode) {
- KeyTreeNode node = (KeyTreeNode)element;
- Collection<IMessageCheck> c = editor.getMarkers().getFailedChecks(node.getMessageKey());
- if (c == null || c.isEmpty()) {
- return UIUtils.getImage(UIUtils.IMAGE_KEY);
- }
- boolean isMissingOrUnused = editor.getMarkers().isMissingOrUnusedKey(node.getMessageKey());
- if (isMissingOrUnused) {
- if (editor.getMarkers().isUnusedKey(node.getMessageKey(), isMissingOrUnused)) {
- return UIUtils.getImage(UIUtils.IMAGE_UNUSED_TRANSLATION);
- } else {
- return UIUtils.getImage(UIUtils.IMAGE_MISSING_TRANSLATION);
- }
- } else {
- return UIUtils.getImage(UIUtils.IMAGE_WARNED_TRANSLATION);
- }
- } else {
-/* // Figure out background icon
- if (messagesBundleGroup.isMessageKey(key)) {
- //TODO create check (or else)
-// if (!noInactiveKeyCheck.checkKey(messagesBundleGroup, node.getPath())) {
-// iconFlags += KEY_COMMENTED;
-// } else {
- iconFlags += KEY_DEFAULT;
-
-// }
- } else {
- iconFlags += KEY_VIRTUAL;
- }*/
- return UIUtils.getImage(UIUtils.IMAGE_KEY);
- }
-
- }
-
-
- /**
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- /*
- * We look to the content provider to see if the node is being
- * displayed in flat or tree mode.
- */
- KeyTreeNode node = (KeyTreeNode) element;
- switch (contentProvider.getTreeType()) {
- case Tree:
- return node.getName();
- case Flat:
- return node.getMessageKey();
- default:
- // Should not happen
- return "error";
- }
- }
-
- /**
- * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
- */
- public void dispose() {
-//TODO imageRegistry.dispose(); could do if version 3.1
- }
-
- /**
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- return null;
- }
-
- /**
- * Generates an image based on icon flags.
- * @param iconFlags
- * @return generated image
- */
- private Image generateImage(int iconFlags) {
- Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
- if (image == null) {
- // Figure background image
- if ((iconFlags & KEY_COMMENTED) != 0) {
- image = getRegistryImage("keyCommented.png"); //$NON-NLS-1$
- } else if ((iconFlags & KEY_VIRTUAL) != 0) {
- image = getRegistryImage("keyVirtual.png"); //$NON-NLS-1$
- } else {
- image = getRegistryImage("keyDefault.png"); //$NON-NLS-1$
- }
-
- // Add warning icon
- if ((iconFlags & BADGE_WARNING) != 0) {
- image = overlayImage(image, "warning.gif", //$NON-NLS-1$
- OverlayImageIcon.BOTTOM_RIGHT, iconFlags);
- } else if ((iconFlags & BADGE_WARNING_GREY) != 0) {
- image = overlayImage(image, "warningGrey.gif", //$NON-NLS-1$
- OverlayImageIcon.BOTTOM_RIGHT, iconFlags);
- }
- }
- return image;
- }
-
- private Image overlayImage(
- Image baseImage, String imageName, int location, int iconFlags) {
- /* To obtain a unique key, we assume here that the baseImage and
- * location are always the same for each imageName and keyFlags
- * combination.
- */
- String imageKey = imageName + iconFlags;
- Image image = imageRegistry.get(imageKey);
- if (image == null) {
- image = new OverlayImageIcon(baseImage, getRegistryImage(
- imageName), location).createImage();
- imageRegistry.put(imageKey, image);
- }
- return image;
- }
-
- private Image getRegistryImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = UIUtils.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-
- private boolean isOneChildrenMarked(IKeyTreeNode parentNode) {
- MessagesEditorMarkers markers = editor.getMarkers();
- IKeyTreeNode[] childNodes =
- editor.getKeyTreeModel().getChildren(parentNode);
- for (int i = 0; i < childNodes.length; i++) {
- IKeyTreeNode node = childNodes[i];
- if (markers.isMarked(node.getMessageKey())) {
- return true;
- }
- if (isOneChildrenMarked(node)) {
- return true;
- }
- }
- return false;
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/AbstractTreeAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/AbstractTreeAction.java
deleted file mode 100644
index 5cb30933..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/AbstractTreeAction.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.AbstractKeyTreeModel;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-
-
-/**
- * @author Pascal Essiembre
- *
- */
-public abstract class AbstractTreeAction extends Action {
-
-// private static final KeyTreeNode[] EMPTY_TREE_NODES = new KeyTreeNode[]{};
-
- protected final TreeViewer treeViewer;
- protected final MessagesEditor editor;
-
- /**
- *
- */
- public AbstractTreeAction(
- MessagesEditor editor, TreeViewer treeViewer) {
- super();
- this.treeViewer = treeViewer;
- this.editor = editor;
- }
- /**
- *
- */
- public AbstractTreeAction(
- MessagesEditor editor, TreeViewer treeViewer, int style) {
- super("", style);
- this.treeViewer = treeViewer;
- this.editor = editor;
- }
-
- protected KeyTreeNode getNodeSelection() {
- IStructuredSelection selection =
- (IStructuredSelection) treeViewer.getSelection();
- return (KeyTreeNode) selection.getFirstElement();
- }
- protected KeyTreeNode[] getBranchNodes(KeyTreeNode node) {
- return ((AbstractKeyTreeModel) treeViewer.getInput()).getBranch(node);
-//
-// Set childNodes = new TreeSet();
-// childNodes.add(node);
-// Object[] nodes = getContentProvider().getChildren(node);
-// for (int i = 0; i < nodes.length; i++) {
-// childNodes.addAll(
-// Arrays.asList(getBranchNodes((KeyTreeNode) nodes[i])));
-// }
-// return (KeyTreeNode[]) childNodes.toArray(EMPTY_TREE_NODES);
- }
-
- protected ITreeContentProvider getContentProvider() {
- return (ITreeContentProvider) treeViewer.getContentProvider();
- }
-
- protected MessagesBundleGroup getBundleGroup() {
- return editor.getBundleGroup();
- }
-
- protected TreeViewer getTreeViewer() {
- return treeViewer;
- }
-
- protected MessagesEditor getEditor() {
- return editor;
- }
-
- protected Shell getShell() {
- return treeViewer.getTree().getShell();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/AddKeyAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/AddKeyAction.java
deleted file mode 100644
index 1712ad6b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/AddKeyAction.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.window.Window;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class AddKeyAction extends AbstractTreeAction {
-
- /**
- *
- */
- public AddKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.add")); //$NON-NLS-1$
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_ADD));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- KeyTreeNode node = getNodeSelection();
- String key = node.getMessageKey();
- String msgHead = MessagesEditorPlugin.getString("dialog.add.head");
- String msgBody = MessagesEditorPlugin.getString("dialog.add.body");
- InputDialog dialog = new InputDialog(
- getShell(), msgHead, msgBody, key, new IInputValidator() {
- public String isValid(String newText) {
- if (getBundleGroup().isMessageKey(newText)) {
- return MessagesEditorPlugin.getString(
- "dialog.error.exists");
- }
- return null;
- }
- });
- dialog.open();
- if (dialog.getReturnCode() == Window.OK ) {
- String inputKey = dialog.getValue();
- MessagesBundleGroup messagesBundleGroup = getBundleGroup();
- messagesBundleGroup.addMessages(inputKey);
- }
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/CollapseAllAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/CollapseAllAction.java
deleted file mode 100644
index 3b0a3e27..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/CollapseAllAction.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class CollapseAllAction extends AbstractTreeAction {
-
- /**
- * @param editor
- * @param treeViewer
- */
- public CollapseAllAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.collapseAll")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_COLLAPSE_ALL));
- setToolTipText("Collapse all"); //TODO put tooltip
- }
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- getTreeViewer().collapseAll();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/DeleteKeyAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/DeleteKeyAction.java
deleted file mode 100644
index 3c57f471..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/DeleteKeyAction.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.MessageBox;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class DeleteKeyAction extends AbstractTreeAction {
-
- /**
- *
- */
- public DeleteKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.delete")); //$NON-NLS-1$
- setImageDescriptor(
- PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_TOOL_DELETE));
- setToolTipText("TODO put something here"); //TODO put tooltip
-// setActionDefinitionId("org.eclilpse.babel.editor.editor.tree.delete");
-// setActionDefinitionId("org.eclipse.ui.edit.delete");
-// editor.getSite().getKeyBindingService().registerAction(this);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- KeyTreeNode node = getNodeSelection();
- String key = node.getMessageKey();
- String msgHead = null;
- String msgBody = null;
- if (getContentProvider().hasChildren(node)) {
- msgHead = MessagesEditorPlugin.getString(
- "dialog.delete.head.multiple"); //$NON-NLS-1$
- msgBody = MessagesEditorPlugin.getString(
- "dialog.delete.body.multiple", key);//$NON-NLS-1$
- } else {
- msgHead = MessagesEditorPlugin.getString(
- "dialog.delete.head.single"); //$NON-NLS-1$
- msgBody = MessagesEditorPlugin.getString(
- "dialog.delete.body.single", key); //$NON-NLS-1$
- }
- MessageBox msgBox = new MessageBox(
- getShell(), SWT.ICON_QUESTION|SWT.OK|SWT.CANCEL);
- msgBox.setMessage(msgBody);
- msgBox.setText(msgHead);
- if (msgBox.open() == SWT.OK) {
- MessagesBundleGroup messagesBundleGroup = getBundleGroup();
- KeyTreeNode[] nodesToDelete = getBranchNodes(node);
- for (int i = 0; i < nodesToDelete.length; i++) {
- KeyTreeNode nodeToDelete = nodesToDelete[i];
- messagesBundleGroup.removeMessages(nodeToDelete.getMessageKey());
- }
- }
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/ExpandAllAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/ExpandAllAction.java
deleted file mode 100644
index 5a5bda6e..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/ExpandAllAction.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class ExpandAllAction extends AbstractTreeAction {
-
- /**
- * @param editor
- * @param treeViewer
- */
- public ExpandAllAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.expandAll")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_EXPAND_ALL));
- setToolTipText("Expand All"); //TODO put tooltip
- }
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- getTreeViewer().expandAll();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/FlatModelAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/FlatModelAction.java
deleted file mode 100644
index 1414a654..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/FlatModelAction.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.KeyTreeContentProvider;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class FlatModelAction extends AbstractTreeAction {
-
- /**
- * @param editor
- * @param treeViewer
- */
- public FlatModelAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer, IAction.AS_RADIO_BUTTON);
- setText(MessagesEditorPlugin.getString("key.layout.flat")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_LAYOUT_FLAT));
- setDisabledImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_LAYOUT_FLAT));
- setToolTipText("Display in a list"); //TODO put tooltip
- }
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- KeyTreeContentProvider contentProvider = (KeyTreeContentProvider)treeViewer.getContentProvider();
- contentProvider.setTreeType(TreeType.Flat);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/RenameKeyAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/RenameKeyAction.java
deleted file mode 100644
index 9ee6b020..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/RenameKeyAction.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.babel.core.message.tree.KeyTreeNode;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring.RenameKeyProcessor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.refactoring.RenameKeyWizard;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class RenameKeyAction extends AbstractTreeAction {
-
- /**
- *
- */
- public RenameKeyAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer);
- setText(MessagesEditorPlugin.getString("key.rename")); //$NON-NLS-1$
- setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_RENAME));
- setToolTipText("TODO put something here"); //TODO put tooltip
- }
-
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- KeyTreeNode node = getNodeSelection();
-
- // Rename single item
- RenameKeyProcessor refactoring = new RenameKeyProcessor(node, getBundleGroup());
-
- RefactoringWizard wizard = new RenameKeyWizard(node, refactoring);
- try {
- RefactoringWizardOpenOperation operation= new RefactoringWizardOpenOperation(wizard);
- operation.run(getShell(), "Introduce Indirection");
- } catch (InterruptedException exception) {
- // Do nothing
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/TreeModelAction.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/TreeModelAction.java
deleted file mode 100644
index ceb7df31..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/tree/actions/TreeModelAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.KeyTreeContentProvider;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType;
-
-/**
- * @author Pascal Essiembre
- *
- */
-public class TreeModelAction extends AbstractTreeAction {
-
- /**
- * @param editor
- * @param treeViewer
- */
- public TreeModelAction(MessagesEditor editor, TreeViewer treeViewer) {
- super(editor, treeViewer, IAction.AS_RADIO_BUTTON);
- setText(MessagesEditorPlugin.getString("key.layout.tree")); //$NON-NLS-1$
- setImageDescriptor(
- UIUtils.getImageDescriptor(UIUtils.IMAGE_LAYOUT_HIERARCHICAL));
- setToolTipText("Display as in a Tree"); //TODO put tooltip
- setChecked(true);
- }
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- KeyTreeContentProvider contentProvider = (KeyTreeContentProvider)treeViewer.getContentProvider();
- contentProvider.setTreeType(TreeType.Tree);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/util/OverlayImageIcon.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/util/OverlayImageIcon.java
deleted file mode 100644
index 19bce391..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/util/OverlayImageIcon.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.util;
-
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-
-/**
- *
- * @author Pascal Essiembre
- */
-public class OverlayImageIcon extends CompositeImageDescriptor {
-
- /** Constant for overlaying icon in top left corner. */
- public static final int TOP_LEFT = 0;
- /** Constant for overlaying icon in top right corner. */
- public static final int TOP_RIGHT = 1;
- /** Constant for overlaying icon in bottom left corner. */
- public static final int BOTTOM_LEFT = 2;
- /** Constant for overlaying icon in bottom right corner. */
- public static final int BOTTOM_RIGHT = 3;
-
- private Image baseImage;
- private Image overlayImage;
- private int location;
- private Point imgSize;
-
- /**
- * Constructor.
- * @param baseImage background image
- * @param overlayImage the image to put on top of background image
- * @param location in which corner to put the icon
- */
- public OverlayImageIcon(Image baseImage, Image overlayImage, int location) {
- super();
- this.baseImage = baseImage;
- this.overlayImage = overlayImage;
- this.location = location;
- this.imgSize = new Point(
- baseImage.getImageData().width,
- baseImage.getImageData().height);
- }
-
- /**
- * @see org.eclipse.jface.resource.CompositeImageDescriptor
- * #drawCompositeImage(int, int)
- */
- protected void drawCompositeImage(int width, int height) {
- // Draw the base image
- drawImage(baseImage.getImageData(), 0, 0);
- ImageData imageData = overlayImage.getImageData();
- switch(location) {
- // Draw on the top left corner
- case TOP_LEFT:
- drawImage(imageData, 0, 0);
- break;
-
- // Draw on top right corner
- case TOP_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, 0);
- break;
-
- // Draw on bottom left
- case BOTTOM_LEFT:
- drawImage(imageData, 0, imgSize.y - imageData.height);
- break;
-
- // Draw on bottom right corner
- case BOTTOM_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width,
- imgSize.y - imageData.height);
- break;
-
- }
- }
-
- /**
- * @see org.eclipse.jface.resource.CompositeImageDescriptor#getSize()
- */
- protected Point getSize() {
- return imgSize;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/util/UIUtils.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/util/UIUtils.java
deleted file mode 100644
index 88cea8af..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/util/UIUtils.java
+++ /dev/null
@@ -1,493 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.util;
-
-import java.awt.ComponentOrientation;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.Reader;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.internal.misc.StringMatcher;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-
-/**
- * Utility methods related to application UI.
- * @author Pascal Essiembre
- */
-public final class UIUtils {
-
-
- /** Name of resource bundle image. */
- public static final String IMAGE_RESOURCE_BUNDLE =
- "resourcebundle.gif"; //$NON-NLS-1$
- /** Name of properties file image. */
- public static final String IMAGE_PROPERTIES_FILE =
- "propertiesfile.gif"; //$NON-NLS-1$
- /** Name of new properties file image. */
- public static final String IMAGE_NEW_PROPERTIES_FILE =
- "newpropertiesfile.gif"; //$NON-NLS-1$
- /** Name of hierarchical layout image. */
- public static final String IMAGE_LAYOUT_HIERARCHICAL =
- "hierarchicalLayout.gif"; //$NON-NLS-1$
- /** Name of flat layout image. */
- public static final String IMAGE_LAYOUT_FLAT =
- "flatLayout.gif"; //$NON-NLS-1$
-
- /** Name of add icon. */
- public static final String IMAGE_ADD = "add.png"; //$NON-NLS-1$
- /** Name of edit icon. */
- public static final String IMAGE_RENAME = "rename.gif"; //$NON-NLS-1$
- /** Name of "view left" icon. */
- public static final String IMAGE_VIEW_LEFT = "viewLeft.gif"; //$NON-NLS-1$
- /** Name of locale icon. */
- public static final String IMAGE_LOCALE = "locale.gif"; //$NON-NLS-1$
- /** Name of new locale icon. */
- public static final String IMAGE_NEW_LOCALE =
- "newLocale.gif"; //$NON-NLS-1$
- /** Name of expand all icon. */
- public static final String IMAGE_EXPAND_ALL =
- "expandall.png"; //$NON-NLS-1$
- /** Name of collapse all icon. */
- public static final String IMAGE_COLLAPSE_ALL =
- "collapseall.png"; //$NON-NLS-1$
-
-
- public static final String IMAGE_KEY =
- "keyDefault.png"; //$NON-NLS-1$
- public static final String IMAGE_INCOMPLETE_ENTRIES =
- "incomplete.gif"; //$NON-NLS-1$
- public static final String IMAGE_EMPTY =
- "empty.gif"; //$NON-NLS-1$
- public static final String IMAGE_MISSING_TRANSLATION =
- "missing_translation.png"; //$NON-NLS-1$
- public static final String IMAGE_UNUSED_TRANSLATION =
- "unused_translation.png"; //$NON-NLS-1$
- public static final String IMAGE_UNUSED_AND_MISSING_TRANSLATIONS =
- "unused_and_missing_translations.png"; //$NON-NLS-1$
- public static final String IMAGE_WARNED_TRANSLATION =
- "warned_translation.png"; //$NON-NLS-1$
-
- /** Image registry. */
- private static final ImageRegistry imageRegistry =
- //TODO: REMOVE this comment eventually:
- //necessary to specify the display otherwise Display.getCurrent()
- //is called and will return null if this is not the UI-thread.
- //this happens if the builder is called and initialize this class:
- //the thread will not be the UI-thread.
- new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
-
- public static final String PDE_NATURE = "org.eclipse.pde.PluginNature"; //$NON-NLS-1$
- public static final String JDT_JAVA_NATURE = "org.eclipse.jdt.core.javanature"; //$NON-NLS-1$
-
-
- /**
- * The root locale used for the original properties file.
- * This constant is defined in java.util.Local starting with jdk6.
- */
- public static final Locale ROOT_LOCALE = new Locale(""); //$NON-NLS-1$
-
- /**
- * Sort the Locales alphabetically. Make sure the root Locale is first.
- *
- * @param locales
- */
- public static final void sortLocales(Locale[] locales) {
- List<Locale> localesList = new ArrayList<Locale>(Arrays.asList(locales));
- Comparator<Locale> comp = new Comparator<Locale>() {
- public int compare(Locale l1, Locale l2) {
- if (ROOT_LOCALE.equals(l1)) {
- return -1;
- }
- if (ROOT_LOCALE.equals(l2)) {
- return 1;
- }
- String name1 = ""; //$NON-NLS-1$
- String name2 = ""; //$NON-NLS-1$
- if (l1 != null) {
- name1 = l1.getDisplayName();
- }
- if (l2 != null) {
- name2 = l2.getDisplayName();
- }
- return name1.compareTo(name2);
- }
- };
- Collections.sort(localesList, comp);
- for (int i = 0; i < locales.length; i++) {
- locales[i] = localesList.get(i);
- }
- }
-
- /**
- * @param locale
- * @return true if the locale is selected by the local-filter defined in the rpeferences
- * @see MsgEditorPreferences#getFilterLocalesStringMatcher()
- */
- public static boolean isDisplayed(Locale locale) {
- if (ROOT_LOCALE.equals(locale) || locale == null) {
- return true;
- }
- StringMatcher[] patterns =
- MsgEditorPreferences.getInstance().getFilterLocalesStringMatchers();
- if (patterns == null || patterns.length == 0) {
- return true;
- }
- String locStr = locale.toString();
- for (int i = 0; i < patterns.length; i++) {
- if (patterns[i].match(locStr)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Reads the filter of locales in the preferences and apply it
- * to filter the passed locales.
- * @param locales
- * @return The new collection of locales; removed the ones not selected by the preferences.
- */
- public static Locale[] filterLocales(Locale[] locales) {
- StringMatcher[] patterns =
- MsgEditorPreferences.getInstance().getFilterLocalesStringMatchers();
- Set<Locale> already = new HashSet<Locale>();
- //first look for the root locale:
- ArrayList<Locale> result = new ArrayList<Locale>();
- for (int j = 0; j < locales.length; j++) {
- Locale loc = locales[j];
- if (ROOT_LOCALE.equals(loc) || loc == null) {
- already.add(loc);
- result.add(loc);
- break;
- }
- }
- //now go through each pattern until already indexed locales found all locales
- //or we run out of locales.
- for (int pi = 0; pi < patterns.length; pi++) {
- StringMatcher pattern = patterns[pi];
- for (int j = 0; j < locales.length; j++) {
- Locale loc = locales[j];
- if (!already.contains(loc)) {
- if (pattern.match(loc.toString())) {
- already.add(loc);
- result.add(loc);
- if (already.size() == locales.length) {
- for (int k = 0; k < locales.length; k++) {
- locales[k] = (Locale) result.get(k);
- }
- return locales;
- }
- }
- }
- }
- }
- Locale[] filtered = new Locale[result.size()];
- for (int k = 0; k < filtered.length; k++) {
- filtered[k] = result.get(k);
- }
- return filtered;
- }
-
- /**
- * Constructor.
- */
- private UIUtils() {
- super();
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
-
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = MessagesEditorPlugin.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 cursor matching given style.
- * @param style style to apply to the new font
- * @return newly created cursor
- */
- public static Cursor createCursor(int style) {
- Display display = MessagesEditorPlugin.getDefault().getWorkbench().getDisplay();
- return new Cursor(display, style);
- }
-
- /**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return MessagesEditorPlugin.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Gets the approximate width required to display a given number of
- * characters in a control.
- * @param control the control on which to get width
- * @param numOfChars the number of chars
- * @return width
- */
- public static int getWidthInChars(Control control, int numOfChars) {
- GC gc = new GC(control);
- Point extent = gc.textExtent("W");//$NON-NLS-1$
- gc.dispose();
- return numOfChars * extent.x;
- }
-
- /**
- * Gets the approximate height required to display a given number of
- * characters in a control, assuming, they were laid out vertically.
- * @param control the control on which to get height
- * @param numOfChars the number of chars
- * @return height
- */
- public static int getHeightInChars(Control control, int numOfChars) {
- GC gc = new GC(control);
- Point extent = gc.textExtent("W");//$NON-NLS-1$
- gc.dispose();
- return numOfChars * extent.y;
- }
-
- /**
- * Shows an error dialog based on the supplied arguments.
- * @param shell the shell
- * @param exception the core exception
- * @param msgKey key to the plugin message text
- */
- public static void showErrorDialog(
- Shell shell, CoreException exception, String msgKey) {
- exception.printStackTrace();
- ErrorDialog.openError(
- shell,
- MessagesEditorPlugin.getString(msgKey),
- exception.getLocalizedMessage(),
- exception.getStatus());
- }
-
- /**
- * Shows an error dialog based on the supplied arguments.
- * @param shell the shell
- * @param exception the core exception
- * @param msgKey key to the plugin message text
- */
- public static void showErrorDialog(
- Shell shell, Exception exception, String msgKey) {
- exception.printStackTrace();
- IStatus status = new Status(
- IStatus.ERROR,
- MessagesEditorPlugin.PLUGIN_ID,
- 0,
- MessagesEditorPlugin.getString(msgKey) + " " //$NON-NLS-1$
- + MessagesEditorPlugin.getString("error.seeLogs"), //$NON-NLS-1$
- exception);
- ErrorDialog.openError(
- shell,
- MessagesEditorPlugin.getString(msgKey),
- exception.getLocalizedMessage(),
- status);
- }
-
- /**
- * Gets a locale, null-safe, display name.
- * @param locale locale to get display name
- * @return display name
- */
- public static String getDisplayName(Locale locale) {
- if (locale == null || ROOT_LOCALE.equals(locale)) {
- return MessagesEditorPlugin.getString("editor.i18nentry.rootlocale.label"); //$NON-NLS-1$
- }
- return locale.getDisplayName();
- }
-
- /**
- * Gets an image descriptor.
- * @param name image name
- * @return image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String name) {
- String iconPath = "icons/"; //$NON-NLS-1$
- try {
- URL installURL = MessagesEditorPlugin.getDefault().getBundle().getEntry(
- "/"); //$NON-NLS-1$
- URL url = new URL(installURL, iconPath + name);
- return ImageDescriptor.createFromURL(url);
- } catch (MalformedURLException e) {
- // should not happen
- return ImageDescriptor.getMissingImageDescriptor();
- }
- }
-
- /**
- * Gets an image.
- * @param imageName image name
- * @return image
- */
- public static Image getImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-
- /**
- * 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>
- */
- public static 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;
- }
-
- /**
- * Parses manually the project descriptor looking for a nature.
- * <p>
- * Calling IProject.getNature(naturedId) throws exception if the
- * Nature is not defined in the currently executed platform.
- * For example if looking for a pde nature inside an eclipse-platform.
- * </p>
- * <p>
- * This method returns the result without that constraint.
- * </p>
- * @param proj The project to examine
- * @param nature The nature to look for.
- * @return true if the nature is defined in that project.
- */
- public static boolean hasNature(
- IProject proj, String nature) {
- IFile projDescr = proj.getFile(".project"); //$NON-NLS-1$
- if (!projDescr.exists()) {
- return false;//a corrupted project
- }
-
- //<classpathentry kind="src" path="src"/>
- InputStream in = null;
- try {
- in = ((IFile)projDescr).getContents();
- //supposedly in utf-8. should not really matter for us
- Reader r = new InputStreamReader(in, "UTF-8");
- LineNumberReader lnr = new LineNumberReader(r);
- String line = lnr.readLine();
- while (line != null) {
- if (line.trim().equals("<nature>" + nature + "</nature>")) {
- lnr.close();
- r.close();
- return true;
- }
- line = lnr.readLine();
- }
- lnr.close();
- r.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) try { in.close(); } catch (IOException e) {}
- }
- return false;
- }
-
-
-}
-
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/views/MessagesBundleGroupOutline.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/views/MessagesBundleGroupOutline.java
deleted file mode 100644
index bf65e88b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/views/MessagesBundleGroupOutline.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.views;
-
-
-
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.MessagesEditor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.KeyTreeContributor;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.CollapseAllAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.ExpandAllAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.FlatModelAction;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.tree.actions.TreeModelAction;
-
-
-/**
- * This outline provides a view for the property keys coming with
- * with a ResourceBundle
- */
-public class MessagesBundleGroupOutline extends ContentOutlinePage {
-
- private final MessagesEditor editor;
-
- public MessagesBundleGroupOutline(MessagesEditor editor) {
- super();
- this.editor = editor;
- }
-
-
- /**
- * {@inheritDoc}
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
-
- KeyTreeContributor treeContributor = new KeyTreeContributor(editor);
- treeContributor.contribute(getTreeViewer());
- }
-
-// /**
-// * {@inheritDoc}
-// */
-// public void dispose() {
-// contributor.dispose();
-// super.dispose();
-// }
-//
-//
-// /**
-// * Gets the selected key tree item.
-// * @return key tree item
-// */
-// public KeyTreeItem getTreeSelection() {
-// IStructuredSelection selection = (IStructuredSelection) getTreeViewer().getSelection();
-// return((KeyTreeItem) selection.getFirstElement());
-// }
-//
-//
-// /**
-// * Gets selected key.
-// * @return selected key
-// */
-// private String getSelectedKey() {
-// String key = null;
-// KeyTreeItem item = getTreeSelection();
-// if(item != null) {
-// key = item.getId();
-// }
-// return(key);
-// }
-//
-//
- /**
- * {@inheritDoc}
- */
- public void setActionBars(IActionBars actionbars) {
- super.setActionBars(actionbars);
-// filterincomplete = new ToggleAction(UIUtils.IMAGE_INCOMPLETE_ENTRIES);
-// flataction = new ToggleAction(UIUtils.IMAGE_LAYOUT_FLAT);
-// hierarchicalaction = new ToggleAction(UIUtils.IMAGE_LAYOUT_HIERARCHICAL);
-// flataction . setToolTipText(RBEPlugin.getString("key.layout.flat")); //$NON-NLS-1$
-// hierarchicalaction . setToolTipText(RBEPlugin.getString("key.layout.tree")); //$NON-NLS-1$
-// filterincomplete . setToolTipText(RBEPlugin.getString("key.filter.incomplete")); //$NON-NLS-1$
-// flataction . setChecked( ! hierarchical );
-// hierarchicalaction . setChecked( hierarchical );
-// actionbars.getToolBarManager().add( flataction );
-// actionbars.getToolBarManager().add( hierarchicalaction );
-// actionbars.getToolBarManager().add( filterincomplete );
- IToolBarManager toolBarMgr = actionbars.getToolBarManager();
-
-// ActionGroup
-// ActionContext
-// IAction
-
- toolBarMgr.add(new TreeModelAction(editor, getTreeViewer()));
- toolBarMgr.add(new FlatModelAction(editor, getTreeViewer()));
- toolBarMgr.add(new Separator());
- toolBarMgr.add(new ExpandAllAction(editor, getTreeViewer()));
- toolBarMgr.add(new CollapseAllAction(editor, getTreeViewer()));
- }
-//
-//
-// /**
-// * Invokes ths functionality according to the toggled action.
-// *
-// * @param action The action that has been toggled.
-// */
-// private void update(ToggleAction action) {
-// int actioncode = 0;
-// if(action == filterincomplete) {
-// actioncode = TreeViewerContributor.KT_INCOMPLETE;
-// } else if(action == flataction) {
-// actioncode = TreeViewerContributor.KT_FLAT;
-// } else if(action == hierarchicalaction) {
-// actioncode = TreeViewerContributor.KT_HIERARCHICAL;
-// }
-// contributor.update(actioncode, action.isChecked());
-// flataction.setChecked((contributor.getMode() & TreeViewerContributor.KT_HIERARCHICAL) == 0);
-// hierarchicalaction.setChecked((contributor.getMode() & TreeViewerContributor.KT_HIERARCHICAL) != 0);
-// }
-//
-//
-// /**
-// * Simple toggle action which delegates it's invocation to
-// * the method {@link #update(ToggleAction)}.
-// */
-// private class ToggleAction extends Action {
-//
-// /**
-// * Initialises this action using the supplied icon.
-// *
-// * @param icon The icon which shall be displayed.
-// */
-// public ToggleAction(String icon) {
-// super(null, IAction.AS_CHECK_BOX);
-// setImageDescriptor(RBEPlugin.getImageDescriptor(icon));
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void run() {
-// update(this);
-// }
-//
-// } /* ENDCLASS */
-//
-//
-// /**
-// * Implementation of custom behaviour.
-// */
-// private class LocalBehaviour extends MouseAdapter implements IDeltaListener ,
-// ISelectionChangedListener {
-//
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void selectionChanged(SelectionChangedEvent event) {
-// String selected = getSelectedKey();
-// if(selected != null) {
-// tree.selectKey(selected);
-// }
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void add(DeltaEvent event) {
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void remove(DeltaEvent event) {
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void modify(DeltaEvent event) {
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void select(DeltaEvent event) {
-// KeyTreeItem item = (KeyTreeItem) event.receiver();
-// if(item != null) {
-// getTreeViewer().setSelection(new StructuredSelection(item));
-// }
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public void mouseDoubleClick(MouseEvent event) {
-// Object element = getSelection();
-// if (getTreeViewer().isExpandable(element)) {
-// if (getTreeViewer().getExpandedState(element)) {
-// getTreeViewer().collapseToLevel(element, 1);
-// } else {
-// getTreeViewer().expandToLevel(element, 1);
-// }
-// }
-// }
-//
-// } /* ENDCLASS */
-//
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/ActionButton.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/ActionButton.java
deleted file mode 100644
index 54fc2eb4..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/ActionButton.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.widgets;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * A button that when clicked, will execute the given action.
- * @author Pascal Essiembre ([email protected])
- */
-public class ActionButton extends Composite {
-
- /**
- * @param parent
- * @param action
- */
- public ActionButton(Composite parent, IAction action) {
- super(parent, SWT.NONE);
- RowLayout layout = new RowLayout();
- setLayout(layout);
- layout.marginBottom = 0;
- layout.marginLeft = 0;
- layout.marginRight = 0;
- layout.marginTop = 0;
-
- ToolBarManager toolBarMgr = new ToolBarManager(SWT.FLAT);
- toolBarMgr.createControl(this);
- toolBarMgr.add(action);
- toolBarMgr.update(true);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/LocaleSelector.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/LocaleSelector.java
deleted file mode 100644
index c564307a..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/LocaleSelector.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.widgets;
-
-import java.text.Collator;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Locale;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusAdapter;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-/**
- * Composite for dynamically selecting a locale from a list of available
- * locales.
- * @author Pascal Essiembre ([email protected])
- */
-public class LocaleSelector extends Composite {
-
- private static final String DEFAULT_LOCALE = "[" //$NON-NLS-1$
- + MessagesEditorPlugin.getString("editor.default") //$NON-NLS-1$
- + "]"; //$NON-NLS-1$
-
- private Locale[] availableLocales;
-
- private Combo localesCombo;
- private Text langText;
- private Text countryText;
- private Text variantText;
-
-
- /**
- * Constructor.
- * @param parent parent composite
- */
- public LocaleSelector(Composite parent) {
- super(parent, SWT.NONE);
-
- // Init available locales
- availableLocales = Locale.getAvailableLocales();
- Arrays.sort(availableLocales, new Comparator<Locale>() {
- public int compare(Locale locale1, Locale locale2) {
- return Collator.getInstance().compare(
- locale1.getDisplayName(),
- locale2.getDisplayName());
- }
- });
-
- // This layout
- GridLayout layout = new GridLayout();
- setLayout(layout);
- layout.numColumns = 1;
- layout.verticalSpacing = 20;
-
- // Group settings
- Group selectionGroup = new Group(this, SWT.NULL);
- layout = new GridLayout(3, false);
- selectionGroup.setLayout(layout);
- selectionGroup.setText(MessagesEditorPlugin.getString(
- "selector.title")); //$NON-NLS-1$
-
- // Set locales drop-down
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- localesCombo = new Combo(selectionGroup, SWT.READ_ONLY);
- localesCombo.setLayoutData(gd);
- localesCombo.add(DEFAULT_LOCALE);
- for (int i = 0; i < availableLocales.length; i++) {
- localesCombo.add(availableLocales[i].getDisplayName());
- }
- localesCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int index = localesCombo.getSelectionIndex();
- if (index == 0) { // default
- langText.setText(""); //$NON-NLS-1$
- countryText.setText(""); //$NON-NLS-1$
- } else {
- Locale locale = availableLocales[index -1];
- langText.setText(locale.getLanguage());
- countryText.setText(locale.getCountry());
- }
- variantText.setText(""); //$NON-NLS-1$
- }
- });
-
- // Language field
- gd = new GridData();
- langText = new Text(selectionGroup, SWT.BORDER);
- langText.setTextLimit(3);
- gd.widthHint = UIUtils.getWidthInChars(langText, 4);
- langText.setLayoutData(gd);
- langText.addFocusListener(new FocusAdapter() {
- public void focusLost(FocusEvent e) {
- langText.setText(langText.getText().toLowerCase());
- setLocaleOnlocalesCombo();
- }
- });
-
- // Country field
- gd = new GridData();
- countryText = new Text(selectionGroup, SWT.BORDER);
- countryText.setTextLimit(2);
- gd.widthHint = UIUtils.getWidthInChars(countryText, 4);
- countryText.setLayoutData(gd);
- countryText.addFocusListener(new FocusAdapter() {
- public void focusLost(FocusEvent e) {
- countryText.setText(
- countryText.getText().toUpperCase());
- setLocaleOnlocalesCombo();
- }
- });
-
- // Variant field
- gd = new GridData();
- variantText = new Text(selectionGroup, SWT.BORDER);
- gd.widthHint = UIUtils.getWidthInChars(variantText, 4);
- variantText.setLayoutData(gd);
- variantText.addFocusListener(new FocusAdapter() {
- public void focusLost(FocusEvent e) {
- setLocaleOnlocalesCombo();
- }
- });
-
- // Labels
- gd = new GridData();
- gd.horizontalAlignment = GridData.CENTER;
- Label lblLang = new Label(selectionGroup, SWT.NULL);
- lblLang.setText(MessagesEditorPlugin.getString("selector.language")); //$NON-NLS-1$
- lblLang.setLayoutData(gd);
-
- gd = new GridData();
- gd.horizontalAlignment = GridData.CENTER;
- Label lblCountry = new Label(selectionGroup, SWT.NULL);
- lblCountry.setText(MessagesEditorPlugin.getString(
- "selector.country")); //$NON-NLS-1$
- lblCountry.setLayoutData(gd);
-
- gd = new GridData();
- gd.horizontalAlignment = GridData.CENTER;
- Label lblVariant = new Label(selectionGroup, SWT.NULL);
- lblVariant.setText(MessagesEditorPlugin.getString(
- "selector.variant")); //$NON-NLS-1$
- lblVariant.setLayoutData(gd);
- }
-
- /**
- * Gets the selected locale. Default locale is represented by a
- * <code>null</code> value.
- * @return selected locale
- */
- public Locale getSelectedLocale() {
- String lang = langText.getText().trim();
- String country = countryText.getText().trim();
- String variant = variantText.getText().trim();
-
- if (lang.length() > 0 && country.length() > 0 && variant.length() > 0) {
- return new Locale(lang, country, variant);
- } else if (lang.length() > 0 && country.length() > 0) {
- return new Locale(lang, country);
- } else if (lang.length() > 0) {
- return new Locale(lang);
- } else {
- return null;
- }
- }
-
- /**
- * Sets an available locale on the available locales combo box.
- */
- /*default*/ void setLocaleOnlocalesCombo() {
- Locale locale = new Locale(
- langText.getText(),
- countryText.getText(),
- variantText.getText());
- int index = -1;
- for (int i = 0; i < availableLocales.length; i++) {
- Locale availLocale = availableLocales[i];
- if (availLocale.equals(locale)) {
- index = i + 1;
- }
- }
- if (index >= 1) {
- localesCombo.select(index);
- } else {
- localesCombo.clearSelection();
- }
- }
-
- /**
- * Adds a modify listener.
- * @param listener modify listener
- */
- public void addModifyListener(final ModifyListener listener) {
- langText.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- listener.modifyText(e);
- }
- });
- countryText.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- listener.modifyText(e);
- }
- });
- variantText.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- listener.modifyText(e);
- }
- });
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/NullableText.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/NullableText.java
deleted file mode 100644
index 5304518b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/widgets/NullableText.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.widgets;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.util.UIUtils;
-
-
-/**
- * Special text control that regognized the difference between a
- * <code>null</code> values and an empty string. When a <code>null</code>
- * value is supplied, the control background is of a different color.
- * Pressing the backspace button when the field is currently empty will
- * change its value from empty string to <code>null</code>.
- * @author Pascal Essiembre ([email protected])
- */
-public class NullableText extends Composite {
-
- private final Text text;
- private final Color defaultColor;
- private final Color nullColor;
-
- private boolean isnull;
-
- private KeyListener keyListener = new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- if (SWT.BS == e.character) {
- if (text.getText().length() == 0) {
- renderNull();
- }
- }
- }
- public void keyReleased(KeyEvent e) {
- if (text.getText().length() > 0) {
- renderNormal();
- }
- }
- };
-
- /**
- * Constructor.
- */
- public NullableText(Composite parent, int style) {
- super(parent, SWT.NONE);
- text = new Text(this, style);
- defaultColor = text.getBackground();
- nullColor = UIUtils.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW);
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 0;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- setLayout(gridLayout);
- GridData gd = new GridData(GridData.FILL_BOTH);
- setLayoutData(gd);
-
- initComponents();
- }
-
- public void setOrientation(int orientation) {
- text.setOrientation(orientation);
- }
-
- public void setText(String text) {
- isnull = text == null;
- if (isnull) {
- this.text.setText(""); //$NON-NLS-1$x
- renderNull();
- } else {
- this.text.setText(text);
- renderNormal();
- }
- }
- public String getText() {
- if (isnull) {
- return null;
- }
- return this.text.getText();
- }
-
- /**
- * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)
- */
- public void setEnabled(boolean enabled) {
- super.setEnabled(enabled);
- text.setEnabled(enabled);
- }
-
- private void initComponents() {
- GridData gridData = new GridData(
- GridData.FILL, GridData.FILL, true, true);
- text.setLayoutData(gridData);
-
- text.addKeyListener(keyListener);
-
- }
-
-
- private void renderNull() {
- isnull = true;
- if (isEnabled()) {
- text.setBackground(nullColor);
-// try {
-// text.setBackgroundImage(UIUtils.getImage("null.bmp"));
-// } catch (Throwable t) {
-// t.printStackTrace();
-// }
- } else {
- text.setBackground(UIUtils.getSystemColor(
- SWT.COLOR_WIDGET_BACKGROUND));
-// text.setBackgroundImage(null);
- }
- }
- private void renderNormal() {
- isnull = false;
- if (isEnabled()) {
- text.setBackground(defaultColor);
- } else {
- text.setBackground(UIUtils.getSystemColor(
- SWT.COLOR_WIDGET_BACKGROUND));
- }
-// text.setBackgroundImage(null);
- }
-
- /**
- * @see org.eclipse.swt.widgets.Control#addFocusListener(
- * org.eclipse.swt.events.FocusListener)
- */
- public void addFocusListener(FocusListener listener) {
- text.addFocusListener(listener);
- }
- /**
- * @see org.eclipse.swt.widgets.Control#addKeyListener(
- * org.eclipse.swt.events.KeyListener)
- */
- public void addKeyListener(KeyListener listener) {
- text.addKeyListener(listener);
- }
- /**
- * @see org.eclipse.swt.widgets.Control#removeFocusListener(
- * org.eclipse.swt.events.FocusListener)
- */
- public void removeFocusListener(FocusListener listener) {
- text.removeFocusListener(listener);
- }
- /**
- * @see org.eclipse.swt.widgets.Control#removeKeyListener(
- * org.eclipse.swt.events.KeyListener)
- */
- public void removeKeyListener(KeyListener listener) {
- text.removeKeyListener(listener);
- }
-
- /**
- * @param editable true if editable false otherwise.
- * If never called it is editable by default.
- */
- public void setEditable(boolean editable) {
- text.setEditable(editable);
- }
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/wizards/ResourceBundleNewWizardPage.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/wizards/ResourceBundleNewWizardPage.java
deleted file mode 100644
index 10ae7153..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/wizards/ResourceBundleNewWizardPage.java
+++ /dev/null
@@ -1,416 +0,0 @@
-/*
- * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
- *
- * This file is part of Essiembre ResourceBundle Editor.
- *
- * Essiembre ResourceBundle Editor is free software; you can redistribute it
- * and/or modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * Essiembre ResourceBundle Editor is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Essiembre ResourceBundle Editor; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307 USA
- */
-package org.eclipselabs.tapiji.translator.rap.babel.editor.wizards;
-
-import java.util.Locale;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.IDialogPage;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.List;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.ContainerSelectionDialog;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.widgets.LocaleSelector;
-
-/**
- * The "New" wizard page allows setting the container for
- * 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 $
- */
-public class ResourceBundleNewWizardPage extends WizardPage {
-
- static final String DEFAULT_LOCALE = "[" //$NON-NLS-1$
- + MessagesEditorPlugin.getString("editor.default") //$NON-NLS-1$
- + "]"; //$NON-NLS-1$
-
- private Text containerText;
- private Text fileText;
- private ISelection selection;
-
- private Button addButton;
- private Button removeButton;
-
- private List bundleLocalesList;
-
- private LocaleSelector localeSelector;
-
- /**
- * Constructor for SampleNewWizardPage.
- * @param selection workbench selection
- */
- public ResourceBundleNewWizardPage(ISelection selection) {
- super("wizardPage"); //$NON-NLS-1$
- setTitle(MessagesEditorPlugin.getString("editor.wiz.title")); //$NON-NLS-1$
- setDescription(MessagesEditorPlugin.getString("editor.wiz.desc")); //$NON-NLS-1$
- this.selection = selection;
- }
-
- /**
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 1;
- layout.verticalSpacing = 20;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- // Bundle name + location
- createTopComposite(container);
-
- // Locales
- createBottomComposite(container);
-
-
- initialize();
- dialogChanged();
- setControl(container);
- }
-
-
- /**
- * Creates the bottom part of this wizard, which is the locales to add.
- * @param parent parent container
- */
- private void createBottomComposite(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- // Available locales
- createBottomAvailableLocalesComposite(container);
-
- // Buttons
- createBottomButtonsComposite(container);
-
- // Selected locales
- createBottomSelectedLocalesComposite(container);
- }
-
- /**
- * Creates the bottom part of this wizard where selected locales
- * are stored.
- * @param parent parent container
- */
- private void createBottomSelectedLocalesComposite(Composite parent) {
-
- // Selected locales Group
- Group selectedGroup = new Group(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- layout = new GridLayout();
- layout.numColumns = 1;
- selectedGroup.setLayout(layout);
- GridData gd = new GridData(GridData.FILL_BOTH);
- selectedGroup.setLayoutData(gd);
- selectedGroup.setText(MessagesEditorPlugin.getString(
- "editor.wiz.selected")); //$NON-NLS-1$
- bundleLocalesList =
- new List(selectedGroup, SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
- gd = new GridData(GridData.FILL_BOTH);
- bundleLocalesList.setLayoutData(gd);
- bundleLocalesList.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- removeButton.setEnabled(
- bundleLocalesList.getSelectionIndices().length != 0);
- setAddButtonState();
- }
- });
- // add a single Locale so that the bundleLocalesList isn't empty on startup
- bundleLocalesList.add(DEFAULT_LOCALE);
- }
-
- /**
- * Creates the bottom part of this wizard where buttons to add/remove
- * locales are located.
- * @param parent parent container
- */
- private void createBottomButtonsComposite(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 1;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- addButton = new Button(container, SWT.NULL);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- addButton.setLayoutData(gd);
- addButton.setText(MessagesEditorPlugin.getString(
- "editor.wiz.add")); //$NON-NLS-1$
- addButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- bundleLocalesList.add(getSelectedLocaleAsString());
- setAddButtonState();
- dialogChanged(); // for the locale-check
- }
- });
-
- removeButton = new Button(container, SWT.NULL);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- removeButton.setLayoutData(gd);
- removeButton.setText(MessagesEditorPlugin.getString(
- "editor.wiz.remove")); //$NON-NLS-1$
- removeButton.setEnabled(false);
- removeButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- bundleLocalesList.remove(
- bundleLocalesList.getSelectionIndices());
- removeButton.setEnabled(false);
- setAddButtonState();
- dialogChanged(); // for the locale-check
- }
- });
- }
-
- /**
- * Creates the bottom part of this wizard where locales can be chosen
- * or created
- * @param parent parent container
- */
- private void createBottomAvailableLocalesComposite(Composite parent) {
-
- localeSelector =
- new LocaleSelector(parent);
- localeSelector.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- setAddButtonState();
- }
- });
- }
-
- /**
- * Creates the top part of this wizard, which is the bundle name
- * and location.
- * @param parent parent container
- */
- private void createTopComposite(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- container.setLayoutData(gd);
-
- // Folder
- Label label = new Label(container, SWT.NULL);
- label.setText(MessagesEditorPlugin.getString(
- "editor.wiz.folder")); //$NON-NLS-1$
-
- containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- containerText.setLayoutData(gd);
- containerText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- Button button = new Button(container, SWT.PUSH);
- button.setText(MessagesEditorPlugin.getString(
- "editor.wiz.browse")); //$NON-NLS-1$
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleBrowse();
- }
- });
-
- // Bundle name
- label = new Label(container, SWT.NULL);
- label.setText(MessagesEditorPlugin.getString(
- "editor.wiz.bundleName")); //$NON-NLS-1$
-
- fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- fileText.setLayoutData(gd);
- fileText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- label = new Label(container, SWT.NULL);
- label.setText("[locale].properties"); //$NON-NLS-1$
- }
-
- /**
- * Tests if the current workbench selection is a suitable
- * container to use.
- */
- private void initialize() {
- if (selection!=null && selection.isEmpty()==false &&
- selection instanceof IStructuredSelection) {
- IStructuredSelection ssel = (IStructuredSelection)selection;
- if (ssel.size()>1) {
- return;
- }
- Object obj = ssel.getFirstElement();
- if (obj instanceof IAdaptable) {
- IResource resource = (IResource) ((IAdaptable) obj).
- getAdapter(IResource.class);
- // check if selection is a file
- if (resource.getType() == IResource.FILE) {
- resource = resource.getParent();
- }
- // fill filepath container
- containerText.setText(resource.getFullPath().
- toPortableString());
- } else if (obj instanceof IResource) {
- // this will most likely never happen (legacy code)
- IContainer container;
- if (obj instanceof IContainer) {
- container = (IContainer)obj;
- } else {
- container = ((IResource)obj).getParent();
- }
- containerText.setText(container.getFullPath().
- toPortableString());
- }
- }
- fileText.setText("ApplicationResources"); //$NON-NLS-1$
- }
-
- /**
- * Uses the standard container selection dialog to
- * choose the new value for the container field.
- */
-
- /*default*/ void handleBrowse() {
- ContainerSelectionDialog dialog =
- new ContainerSelectionDialog(
- getShell(),
- ResourcesPlugin.getWorkspace().getRoot(),
- false,
- MessagesEditorPlugin.getString(
- "editor.wiz.selectFolder")); //$NON-NLS-1$
- if (dialog.open() == Window.OK) {
- Object[] result = dialog.getResult();
- if (result.length == 1) {
- containerText.setText(((Path)result[0]).toOSString());
- }
- }
- }
-
- /**
- * Ensures that both text fields and the Locale field are set.
- */
- /*default*/ void dialogChanged() {
- String container = getContainerName();
- String fileName = getFileName();
-
- if (container.length() == 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.container")); //$NON-NLS-1$
- return;
- }
- if (fileName.length() == 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.bundleName")); //$NON-NLS-1$
- return;
- }
- int dotLoc = fileName.lastIndexOf('.');
- if (dotLoc != -1) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.extension")); //$NON-NLS-1$
- return;
- }
- // check if at least one Locale has been added to th list
- if (bundleLocalesList.getItemCount() <= 0) {
- updateStatus(MessagesEditorPlugin.getString(
- "editor.wiz.error.locale")); //$NON-NLS-1$
- return;
- }
- updateStatus(null);
- }
-
- private void updateStatus(String message) {
- setErrorMessage(message);
- setPageComplete(message == null);
- }
-
- /**
- * Gets the container name.
- * @return container name
- */
- public String getContainerName() {
- return containerText.getText();
- }
- /**
- * Gets the file name.
- * @return file name
- */
- public String getFileName() {
- return fileText.getText();
- }
-
- /**
- * Sets the "add" button state.
- */
- /*default*/ void setAddButtonState() {
- addButton.setEnabled(bundleLocalesList.indexOf(
- getSelectedLocaleAsString()) == -1);
- }
-
- /**
- * Gets the user selected locales.
- * @return locales
- */
- /*default*/ String[] getLocaleStrings() {
- return bundleLocalesList.getItems();
- }
-
- /**
- * Gets a string representation of selected locale.
- * @return string representation of selected locale
- */
- /*default*/ String getSelectedLocaleAsString() {
- Locale selectedLocale = localeSelector.getSelectedLocale();
- if (selectedLocale != null) {
- return selectedLocale.toString();
- }
- return DEFAULT_LOCALE;
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/wizards/ResourceBundleWizard.java b/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/wizards/ResourceBundleWizard.java
deleted file mode 100644
index 060a2209..00000000
--- a/org.eclipselabs.tapiji.translator.rap.babel.editor/src/org/eclipselabs/tapiji/translator/rap/babel/editor/wizards/ResourceBundleWizard.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.babel.editor.wizards;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWizard;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.plugin.MessagesEditorPlugin;
-import org.eclipselabs.tapiji.translator.rap.babel.editor.preferences.MsgEditorPreferences;
-
-/**
- * This is the main wizard class for creating a new set of ResourceBundle
- * properties files. If the container resource
- * (a folder or a project) is selected in the workspace
- * when the wizard is opened, it will accept it as the target
- * container. The wizard creates one or several files with the extension
- * "properties".
- * @author Pascal Essiembre ([email protected])
- */
-public class ResourceBundleWizard extends Wizard implements INewWizard {
- private ResourceBundleNewWizardPage page;
- private ISelection selection;
-
- /**
- * Constructor for ResourceBundleWizard.
- */
- public ResourceBundleWizard() {
- super();
- setNeedsProgressMonitor(true);
- }
-
- /**
- * Adding the page to the wizard.
- */
-
- public void addPages() {
- page = new ResourceBundleNewWizardPage(selection);
- addPage(page);
- }
-
- /**
- * This method is called when 'Finish' button is pressed in
- * the wizard. We will create an operation and run it
- * using wizard as execution context.
- */
- public boolean performFinish() {
- final String containerName = page.getContainerName();
- final String baseName = page.getFileName();
- final String[] locales = page.getLocaleStrings();
- IRunnableWithProgress op = new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- monitor.worked(1);
- monitor.setTaskName(MessagesEditorPlugin.getString(
- "editor.wiz.creating")); //$NON-NLS-1$
- IFile file = null;
- for (int i = 0; i < locales.length; i++) {
- String fileName = baseName;
- if (locales[i].equals(
- ResourceBundleNewWizardPage.DEFAULT_LOCALE)) {
- fileName += ".properties"; //$NON-NLS-1$
- } else {
- fileName += "_" + locales[i] //$NON-NLS-1$
- + ".properties"; //$NON-NLS-1$
- }
- file = createFile(containerName, fileName, monitor);
- }
- final IFile lastFile = file;
- getShell().getDisplay().asyncExec(new Runnable() {
- public void run() {
- IWorkbenchPage wbPage = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- try {
- IDE.openEditor(wbPage, lastFile, true);
- } catch (PartInitException e) {
- }
- }
- });
- monitor.worked(1);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- try {
- getContainer().run(true, false, op);
- } catch (InterruptedException e) {
- return false;
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- MessageDialog.openError(getShell(),
- "Error", realException.getMessage()); //$NON-NLS-1$
- return false;
- }
- return true;
- }
-
- /*
- * The worker method. It will find the container, create the
- * file if missing or just replace its contents, and open
- * the editor on the newly created file.
- */
- /*default*/ IFile createFile(
- String containerName,
- String fileName,
- IProgressMonitor monitor)
- throws CoreException {
-
- monitor.beginTask(MessagesEditorPlugin.getString(
- "editor.wiz.creating") + fileName, 2); //$NON-NLS-1$
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IResource resource = root.findMember(new Path(containerName));
- if (!resource.exists() || !(resource instanceof IContainer)) {
- throwCoreException("Container \"" + containerName //$NON-NLS-1$
- + "\" does not exist."); //$NON-NLS-1$
- }
- IContainer container = (IContainer) resource;
- final IFile file = container.getFile(new Path(fileName));
- try {
- InputStream stream = openContentStream();
- if (file.exists()) {
- file.setContents(stream, true, true, monitor);
- } else {
- file.create(stream, true, monitor);
- }
- stream.close();
- } catch (IOException e) {
- }
- return file;
- }
-
- /*
- * We will initialize file contents with a sample text.
- */
- private InputStream openContentStream() {
- String contents = ""; //$NON-NLS-1$
- if (MsgEditorPreferences.getInstance().getSerializerConfig().isShowSupportEnabled()) {
-// contents = PropertiesGenerator.GENERATED_BY;
- }
- return new ByteArrayInputStream(contents.getBytes());
- }
-
- private void throwCoreException(String message) throws CoreException {
- IStatus status = new Status(IStatus.ERROR,
- "org.eclipse.babel.editor", //$NON-NLS-1$
- IStatus.OK, message, null);
- throw new CoreException(status);
- }
-
- /**
- * We will accept the selection in the workbench to see if
- * we can initialize from it.
- * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
- */
- public void init(
- IWorkbench workbench, IStructuredSelection structSelection) {
- this.selection = structSelection;
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/.classpath b/org.eclipselabs.tapiji.translator.rap.compat/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/.project b/org.eclipselabs.tapiji.translator.rap.compat/.project
new file mode 100644
index 00000000..954c64e2
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipselabs.tapiji.translator.rap.compat</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.translator.rap.compat/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..c537b630
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/.settings/org.eclipse.pde.core.prefs b/org.eclipselabs.tapiji.translator.rap.compat/.settings/org.eclipse.pde.core.prefs
new file mode 100644
index 00000000..f29e940a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/.settings/org.eclipse.pde.core.prefs
@@ -0,0 +1,3 @@
+eclipse.preferences.version=1
+pluginProject.extensions=false
+resolve.requirebundle=false
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap.compat/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..06475416
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/META-INF/MANIFEST.MF
@@ -0,0 +1,10 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RAP Compatibility for TapiJI Transaltor
+Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap.compat
+Bundle-Version: 0.0.2.qualifier
+Bundle-Activator: org.eclipselabs.tapiji.translator.compat.Activator
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.eclipse.rap.ui;bundle-version="1.5.0"
+Export-Package: org.eclipselabs.tapiji.translator.compat
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/build.properties b/org.eclipselabs.tapiji.translator.rap.compat/build.properties
new file mode 100644
index 00000000..34d2e4d2
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/build.properties
@@ -0,0 +1,4 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/src/org/eclipselabs/tapiji/translator/compat/Activator.java b/org.eclipselabs.tapiji.translator.rap.compat/src/org/eclipselabs/tapiji/translator/compat/Activator.java
new file mode 100644
index 00000000..ba84e8dc
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/src/org/eclipselabs/tapiji/translator/compat/Activator.java
@@ -0,0 +1,30 @@
+package org.eclipselabs.tapiji.translator.compat;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ private static BundleContext context;
+
+ static BundleContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext bundleContext) throws Exception {
+ Activator.context = bundleContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext bundleContext) throws Exception {
+ Activator.context = null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.compat/src/org/eclipselabs/tapiji/translator/compat/MySWT.java b/org.eclipselabs.tapiji.translator.rap.compat/src/org/eclipselabs/tapiji/translator/compat/MySWT.java
new file mode 100644
index 00000000..a39d4f67
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.compat/src/org/eclipselabs/tapiji/translator/compat/MySWT.java
@@ -0,0 +1,27 @@
+package org.eclipselabs.tapiji.translator.compat;
+
+import org.eclipse.swt.SWT;
+
+public class MySWT extends SWT {
+
+ /**
+ * Style constant for right to left orientation (value is 1<<26).
+ * <p>
+ * When orientation is not explicitly specified, orientation is
+ * inherited. This means that children will be assigned the
+ * orientation of their parent. To override this behavior and
+ * force an orientation for a child, explicitly set the orientation
+ * of the child when that child is created.
+ * <br>Note that this is a <em>HINT</em>.
+ * </p>
+ * <p><b>Used By:</b><ul>
+ * <li><code>Control</code></li>
+ * <li><code>Menu</code></li>
+ * <li><code>GC</code></li>
+ * </ul></p>
+ *
+ * @since 2.1.2
+ */
+ public static final int RIGHT_TO_LEFT = 1 << 26;
+ //public static final int RIGHT_TO_LEFT = SWT.RIGHT;
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/.project b/org.eclipselabs.tapiji.translator.rap.rbe/.project
deleted file mode 100644
index 02b06c52..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.translator.rap.rbe</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap.rbe/META-INF/MANIFEST.MF
deleted file mode 100644
index 24d58d3b..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,10 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: ResourceBundleEditorAPI
-Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap.rbe
-Bundle-Version: 0.0.2.qualifier
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Require-Bundle: org.eclipse.rap.jface;bundle-version="1.5.0"
-Export-Package: org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle,
- org.eclipselabs.tapiji.translator.rap.rbe.model.analyze,
- org.eclipselabs.tapiji.translator.rap.rbe.ui.wizards
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IAbstractKeyTreeModel.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IAbstractKeyTreeModel.java
deleted file mode 100644
index 035d19ed..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IAbstractKeyTreeModel.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-
-
-public interface IAbstractKeyTreeModel {
-
- IKeyTreeNode[] getChildren(IKeyTreeNode node);
-
- IKeyTreeNode getChild(String key);
-
- IKeyTreeNode[] getRootNodes();
-
- IKeyTreeNode getRootNode();
-
- IKeyTreeNode getParent(IKeyTreeNode node);
-
- void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeContributor.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeContributor.java
deleted file mode 100644
index e62800a1..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeContributor.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-import org.eclipse.jface.viewers.TreeViewer;
-
-
-public interface IKeyTreeContributor {
-
- void contribute(final TreeViewer treeViewer);
-
- IKeyTreeNode getKeyTreeNode(String key);
-
- IKeyTreeNode[] getRootKeyItems();
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeNode.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeNode.java
deleted file mode 100644
index fffc8dbe..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeNode.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-
-
-public interface IKeyTreeNode {
-
- /**
- * Returns the key of the corresponding Resource-Bundle entry.
- * @return The key of the Resource-Bundle entry
- */
- String getMessageKey();
-
- /**
- * Returns the set of Resource-Bundle entries of the next deeper
- * hierarchy level that share the represented entry as their common
- * parent.
- * @return The direct child Resource-Bundle entries
- */
- IKeyTreeNode[] getChildren();
-
- /**
- * The represented Resource-Bundle entry's id without the prefix defined
- * by the entry's parent.
- * @return The Resource-Bundle entry's display name.
- */
- String getName();
-
- /**
- * Returns the set of Resource-Bundle entries from all deeper hierarchy
- * levels that share the represented entry as their common parent.
- * @return All child Resource-Bundle entries
- */
-// Collection<? extends IKeyTreeItem> getNestedChildren();
-
- /**
- * Returns whether this Resource-Bundle entry is visible under the
- * given filter expression.
- * @param filter The filter expression
- * @return True if the filter expression matches the represented Resource-Bundle entry
- */
-// boolean applyFilter(String filter);
-
- /**
- * The Resource-Bundle entries parent.
- * @return The parent Resource-Bundle entry
- */
- IKeyTreeNode getParent();
-
- /**
- * The Resource-Bundles key representation.
- * @return The Resource-Bundle reference, if known
- */
- IMessagesBundleGroup getMessagesBundleGroup();
-
-
- boolean isUsedAsKey();
-
- void setParent(IKeyTreeNode parentNode);
-
- void addChild(IKeyTreeNode childNode);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeVisitor.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeVisitor.java
deleted file mode 100644
index 0f1b0e77..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IKeyTreeVisitor.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-
-/**
- * Objects implementing this interface can act as a visitor to a
- * <code>IKeyTreeModel</code>.
- * @author Pascal Essiembre ([email protected])
- */
-public interface IKeyTreeVisitor {
- /**
- * Visits a key tree node.
- * @param item key tree node to visit
- */
- void visitKeyTreeNode(IKeyTreeNode node);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessage.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessage.java
deleted file mode 100644
index f2113c18..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessage.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-import java.util.Locale;
-
-
-
-public interface IMessage {
-
- String getKey();
-
- String getValue();
-
- Locale getLocale();
-
- String getComment();
-
- boolean isActive();
-
- String toString();
-
- void setActive(boolean active);
-
- void setComment(String comment);
-
- void setComment(String comment, boolean silent);
-
- void setText(String test);
-
- void setText(String test, boolean silent);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesBundle.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesBundle.java
deleted file mode 100644
index 715e5fa4..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesBundle.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-
-
-
-
-public interface IMessagesBundle {
-
- void dispose();
-
- void renameMessageKey(String sourceKey, String targetKey);
-
- void removeMessage(String messageKey);
-
- void duplicateMessage(String sourceKey, String targetKey);
-
- Locale getLocale();
-
- String[] getKeys();
-
- String getValue(String key);
-
- Collection<IMessage> getMessages();
-
- IMessage getMessage(String key);
-
- void addMessage(IMessage message);
-
- void removeMessages(String[] messageKeys);
-
- void setComment(String comment);
-
- String getComment();
-
- IMessagesResource getResource();
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesBundleGroup.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesBundleGroup.java
deleted file mode 100644
index c92bafba..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesBundleGroup.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-
-
-public interface IMessagesBundleGroup {
-
- Collection<IMessagesBundle> getMessagesBundles();
-
- boolean containsKey(String key);
-
- IMessage[] getMessages(String key);
-
- IMessage getMessage(String key, Locale locale);
-
- IMessagesBundle getMessagesBundle(Locale locale);
-
- void removeMessages(String messageKey);
-
- boolean isKey(String key);
-
- void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
-
- String[] getMessageKeys();
-
- void addMessages(String key);
-
- int getMessagesBundleCount();
-
- String getName();
-
- String getResourceBundleId();
-
- boolean hasPropertiesFileGroupStrategy();
-
- public boolean isMessageKey(String key);
-
- public String getProjectName();
-
- public void removeMessagesBundle(IMessagesBundle messagesBundle);
-
- public void dispose();
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesResource.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesResource.java
deleted file mode 100644
index 89c3afcb..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesResource.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-import java.util.Locale;
-
-/**
- * Class abstracting the underlying native storage mechanism for persisting
- * internationalised text messages.
- * @author Pascal Essiembre
- */
-public interface IMessagesResource {
-
- /**
- * Gets the resource locale.
- * @return locale
- */
- Locale getLocale();
- /**
- * Gets the underlying object abstracted by this resource (e.g. a File).
- * @return source object
- */
- Object getSource();
- /**
- * Serializes a {@link MessagesBundle} instance to its native format.
- * @param messagesBundle the MessagesBundle to serialize
- */
- void serialize(IMessagesBundle messagesBundle);
- /**
- * Deserializes a {@link MessagesBundle} instance from its native format.
- * @param messagesBundle the MessagesBundle to deserialize
- */
- void deserialize(IMessagesBundle messagesBundle);
- /**
- * Adds a messages resource listener. Implementors are required to notify
- * listeners of changes within the native implementation.
- * @param listener the listener
- */
- void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * Removes a messages resource listener.
- * @param listener the listener
- */
- void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * @return The resource location label. or null if unknown.
- */
- String getResourceLocationLabel();
-
- /**
- * Called when the group it belongs to is disposed.
- */
- void dispose();
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesResourceChangeListener.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesResourceChangeListener.java
deleted file mode 100644
index 5712b70c..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IMessagesResourceChangeListener.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-/**
- * Listener being notified when a {@link IMessagesResource} content changes.
- * @author Pascal Essiembre
- */
-public interface IMessagesResourceChangeListener {
-
- /**
- * Method called when the messages resource has changed.
- * @param resource the resource that changed
- */
- void resourceChanged(IMessagesResource resource);
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IValuedKeyTreeNode.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IValuedKeyTreeNode.java
deleted file mode 100644
index b30fb013..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/IValuedKeyTreeNode.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-
-
-public interface IValuedKeyTreeNode extends IKeyTreeNode{
-
- public void initValues (Map<Locale, String> values);
-
- public void addValue (Locale locale, String value);
-
- public String getValue (Locale locale);
-
- public Collection<String> getValues ();
-
- public void setInfo(Object info);
-
- public Object getInfo();
-
- public Collection<Locale> getLocales ();
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/TreeType.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/TreeType.java
deleted file mode 100644
index 470b08b9..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/babel/bundle/TreeType.java
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- *
- */
-package org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle;
-
-
-/**
- * @author ala
- *
- */
-public enum TreeType {
- Tree,
- Flat
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
deleted file mode 100644
index f8d33c40..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.model.analyze;
-
-public interface ILevenshteinDistanceAnalyzer {
-
- double analyse(Object value, Object pattern);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/ui/wizards/IResourceBundleWizard.java b/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/ui/wizards/IResourceBundleWizard.java
deleted file mode 100644
index 37c25571..00000000
--- a/org.eclipselabs.tapiji.translator.rap.rbe/src/org/eclipselabs/tapiji/translator/rap/rbe/ui/wizards/IResourceBundleWizard.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.rbe.ui.wizards;
-
-public interface IResourceBundleWizard {
-
- void setBundleId(String rbName);
-
- void setDefaultPath(String pathName);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/.classpath b/org.eclipselabs.tapiji.translator.rap.supplemental/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/.project b/org.eclipselabs.tapiji.translator.rap.supplemental/.project
new file mode 100644
index 00000000..1a0c50c5
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipselabs.tapiji.translator.rap.supplemental</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.translator.rap.supplemental/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..c537b630
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipselabs.tapiji.translator.rap.babel.core/.settings/org.eclipse.pde.core.prefs b/org.eclipselabs.tapiji.translator.rap.supplemental/.settings/org.eclipse.pde.core.prefs
similarity index 100%
rename from org.eclipselabs.tapiji.translator.rap.babel.core/.settings/org.eclipse.pde.core.prefs
rename to org.eclipselabs.tapiji.translator.rap.supplemental/.settings/org.eclipse.pde.core.prefs
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..f0a5731d
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF
@@ -0,0 +1,27 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Wrappers
+Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap.supplemental;singleton:=true
+Bundle-Version: 0.0.2.qualifier
+Bundle-Activator: org.eclipselabs.tapiji.translator.rap.supplemental.Activator
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Import-Package: org.osgi.framework;version="1.3.0"
+Export-Package: org.eclipse.jdt.core,
+ org.eclipse.jface.text,
+ org.eclipse.jface.viewers,
+ org.eclipse.swt.custom,
+ org.eclipse.ui,
+ org.eclipse.ui.dialogs,
+ org.eclipse.ui.editors.text,
+ org.eclipse.ui.ide,
+ org.eclipse.ui.internal.ide,
+ org.eclipse.ui.part,
+ org.eclipse.ui.texteditor,
+ org.eclipselabs.tapiji.translator.rap.supplemental
+Require-Bundle: org.eclipse.core.filesystem;bundle-version="1.3.100",
+ org.eclipse.core.runtime,
+ org.eclipse.core.resources;bundle-version="3.7.101",
+ org.eclipse.rap.ui;bundle-version="1.5.0",
+ org.eclipse.rap.ui.workbench,
+ org.apache.commons.io;bundle-version="1.0.0"
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/build.properties b/org.eclipselabs.tapiji.translator.rap.supplemental/build.properties
new file mode 100644
index 00000000..e9863e28
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/build.properties
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/plugin.xml b/org.eclipselabs.tapiji.translator.rap.supplemental/plugin.xml
new file mode 100644
index 00000000..10977ffd
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/plugin.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+ <extension
+ point="org.eclipse.ui.editors">
+ <editor
+ class="org.eclipse.ui.editors.text.TextEditor"
+ default="false"
+ id="org.eclipselabs.tapiji.translator.rap.wrappers.TextEditor"
+ name="TextEditor">
+ </editor>
+ </extension>
+ <extension
+ point="org.eclipse.ui.elementFactories">
+ <factory
+ class="org.eclipse.ui.part.FileEditorInputFactory"
+ id="org.eclipse.ui.part.FileEditorInputFactory">
+ </factory>
+ </extension>
+
+</plugin>
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IClasspathEntry.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IClasspathEntry.java
new file mode 100644
index 00000000..cd575821
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IClasspathEntry.java
@@ -0,0 +1,475 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2010 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.jdt.core;
+
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * An entry on a Java project classpath identifying one or more package fragment
+ * roots. A classpath entry has a content kind (either source,
+ * {@link IPackageFragmentRoot#K_SOURCE}, or binary, {@link IPackageFragmentRoot#K_BINARY}), which is inherited
+ * by each package fragment root and package fragment associated with the entry.
+ * <p>
+ * A classpath entry can refer to any of the following:<ul>
+ *
+ * <li>Source code in the current project. In this case, the entry identifies a
+ * root folder in the current project containing package fragments and
+ * source files with one of the {@link JavaCore#getJavaLikeExtensions()
+ * Java-like extensions}. The root folder itself represents a default
+ * package, subfolders represent package fragments, and files with a
+ * Java-like extension (e.g. <code>.java</code> files)
+ * represent compilation units. All compilation units will be compiled when
+ * the project is built. The classpath entry must specify the
+ * absolute path to the root folder. Entries of this kind are
+ * associated with the {@link #CPE_SOURCE} constant.
+ * Source classpath entries can carry inclusion and exclusion patterns for
+ * selecting which source files appear as compilation
+ * units and get compiled when the project is built.
+ * </li>
+ *
+ * <li>A binary library in the current project, in another project, or in the external
+ * file system. In this case the entry identifies a JAR (or root folder) containing
+ * package fragments and <code>.class</code> files. The classpath entry
+ * must specify the absolute path to the JAR (or root folder), and in case it refers
+ * to an external JAR, then there is no associated resource in the workbench. Entries
+ * of this kind are associated with the {@link #CPE_LIBRARY} constant.</li>
+ *
+ * <li>A required project. In this case the entry identifies another project in
+ * the workspace. The required project is used as a binary library when compiling
+ * (that is, the builder looks in the output location of the required project
+ * for required <code>.class</code> files when building). When performing other
+ * "development" operations - such as code assist, code resolve, type hierarchy
+ * creation, etc. - the source code of the project is referred to. Thus, development
+ * is performed against a required project's source code, and compilation is
+ * performed against a required project's last built state. The
+ * classpath entry must specify the absolute path to the
+ * project. Entries of this kind are associated with the {@link #CPE_PROJECT}
+ * constant.
+ * Note: referencing a required project with a classpath entry refers to the source
+ * code or associated <code>.class</code> files located in its output location.
+ * It will also automatically include any other libraries or projects that the required project's classpath
+ * refers to, iff the corresponding classpath entries are tagged as being exported
+ * ({@link IClasspathEntry#isExported}).
+ * Unless exporting some classpath entries, classpaths are not chained by default -
+ * each project must specify its own classpath in its entirety.</li>
+ *
+ * <li> A path beginning in a classpath variable defined globally to the workspace.
+ * Entries of this kind are associated with the {@link #CPE_VARIABLE} constant.
+ * Classpath variables are created using {@link JavaCore#setClasspathVariable(String, IPath, org.eclipse.core.runtime.IProgressMonitor)},
+ * and gets resolved, to either a project or library entry, using
+ * {@link JavaCore#getResolvedClasspathEntry(IClasspathEntry)}.
+ * It is also possible to register an automatic initializer ({@link ClasspathVariableInitializer}),
+ * which will be invoked through the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
+ * After resolution, a classpath variable entry may either correspond to a project or a library entry. </li>
+ *
+ * <li> A named classpath container identified by its container path.
+ * A classpath container provides a way to indirectly reference a set of classpath entries through
+ * a classpath entry of kind {@link #CPE_CONTAINER}. Typically, a classpath container can
+ * be used to describe a complex library composed of multiple JARs, projects or classpath variables,
+ * considering also that containers can be mapped differently on each project. Several projects can
+ * reference the same generic container path, but have each of them actually bound to a different
+ * container object.
+ * The container path is a formed by a first ID segment followed with extra segments,
+ * which can be used as additional hints for resolving this container reference. If no container was ever
+ * recorded for this container path onto this project (using {@link JavaCore#setClasspathContainer},
+ * then a {@link ClasspathContainerInitializer} will be activated if any was registered for this
+ * container ID onto the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ * A classpath container entry can be resolved explicitly using {@link JavaCore#getClasspathContainer}
+ * and the resulting container entries can contain any non-container entry. In particular, it may contain variable
+ * entries, which in turn needs to be resolved before being directly used.
+ * <br> Also note that the container resolution APIs include an IJavaProject argument, so as to allow the same
+ * container path to be interpreted in different ways for different projects. </li>
+ * </ul>
+ * </p>
+ * The result of {@link IJavaProject#getResolvedClasspath} will have all entries of type
+ * {@link #CPE_VARIABLE} and {@link #CPE_CONTAINER} resolved to a set of
+ * {@link #CPE_SOURCE}, {@link #CPE_LIBRARY} or {@link #CPE_PROJECT}
+ * classpath entries.
+ * <p>
+ * Any classpath entry other than a source folder (kind {@link #CPE_SOURCE}) can
+ * be marked as being exported. Exported entries are automatically contributed to
+ * dependent projects, along with the project's default output folder, which is
+ * implicitly exported, and any auxiliary output folders specified on source
+ * classpath entries. The project's output folder(s) are always listed first,
+ * followed by the any exported entries.
+ * <p>
+ * Classpath entries can be created via methods on {@link JavaCore}.
+ * </p>
+ *
+ * @see JavaCore#newLibraryEntry(org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath)
+ * @see JavaCore#newProjectEntry(org.eclipse.core.runtime.IPath)
+ * @see JavaCore#newSourceEntry(org.eclipse.core.runtime.IPath)
+ * @see JavaCore#newVariableEntry(org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath)
+ * @see JavaCore#newContainerEntry(org.eclipse.core.runtime.IPath)
+ * @see ClasspathVariableInitializer
+ * @see ClasspathContainerInitializer
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface IClasspathEntry {
+
+ /**
+ * Entry kind constant describing a classpath entry identifying a
+ * library. A library is a folder or JAR containing package
+ * fragments consisting of pre-compiled binaries.
+ */
+ int CPE_LIBRARY = 1;
+
+ /**
+ * Entry kind constant describing a classpath entry identifying a
+ * required project.
+ */
+ int CPE_PROJECT = 2;
+
+ /**
+ * Entry kind constant describing a classpath entry identifying a
+ * folder containing package fragments with source code
+ * to be compiled.
+ */
+ int CPE_SOURCE = 3;
+
+ /**
+ * Entry kind constant describing a classpath entry defined using
+ * a path that begins with a classpath variable reference.
+ */
+ int CPE_VARIABLE = 4;
+
+ /**
+ * Entry kind constant describing a classpath entry representing
+ * a name classpath container.
+ *
+ * @since 2.0
+ */
+ int CPE_CONTAINER = 5;
+
+ /**
+ * Returns whether the access rules of the project's exported entries should be combined with this entry's access rules.
+ * Returns true for container entries.
+ * Returns false otherwise.
+ *
+ * @return whether the access rules of the project's exported entries should be combined with this entry's access rules
+ * @since 3.1
+ */
+ boolean combineAccessRules();
+
+ /**
+ * Returns the possibly empty list of access rules for this entry.
+ *
+ * @return the possibly empty list of access rules for this entry
+ * @since 3.1
+ */
+ //IAccessRule[] getAccessRules();
+ /**
+ * Returns the kind of files found in the package fragments identified by this
+ * classpath entry.
+ *
+ * @return {@link IPackageFragmentRoot#K_SOURCE} for files containing
+ * source code, and {@link IPackageFragmentRoot#K_BINARY} for binary
+ * class files.
+ * There is no specified value for an entry denoting a variable ({@link #CPE_VARIABLE})
+ * or a classpath container ({@link #CPE_CONTAINER}).
+ */
+ int getContentKind();
+
+ /**
+ * Returns the kind of this classpath entry.
+ *
+ * @return one of:
+ * <ul>
+ * <li>{@link #CPE_SOURCE} - this entry describes a source root in
+ its project
+ * <li>{@link #CPE_LIBRARY} - this entry describes a folder or JAR
+ containing binaries
+ * <li>{@link #CPE_PROJECT} - this entry describes another project
+ *
+ * <li>{@link #CPE_VARIABLE} - this entry describes a project or library
+ * indirectly via a classpath variable in the first segment of the path
+ * *
+ * <li>{@link #CPE_CONTAINER} - this entry describes set of entries
+ * referenced indirectly via a classpath container
+ * </ul>
+ */
+ int getEntryKind();
+
+ /**
+ * Returns the set of patterns used to exclude resources or classes associated with
+ * this classpath entry.
+ * <p>
+ * For source classpath entries,
+ * exclusion patterns allow specified portions of the resource tree rooted
+ * at this source entry's path to be filtered out. If no exclusion patterns
+ * are specified, this source entry includes all relevent files. Each path
+ * specified must be a relative path, and will be interpreted relative
+ * to this source entry's path. File patterns are case-sensitive. A file
+ * matched by one or more of these patterns is excluded from the
+ * corresponding package fragment root.
+ * Exclusion patterns have higher precedence than inclusion patterns;
+ * in other words, exclusion patterns can remove files for the ones that
+ * are to be included, not the other way around.
+ * </p>
+ * <p>
+ * Note that there is no need to supply a pattern to exclude ".class" files
+ * because a source entry filters these out automatically.
+ * </p>
+ * <p>
+ * The pattern mechanism is similar to Ant's. Each pattern is represented as
+ * a relative path. The path segments can be regular file or folder names or simple patterns
+ * involving standard wildcard characters.
+ * </p>
+ * <p>
+ * '*' matches 0 or more characters within a segment. So
+ * <code>*.java</code> matches <code>.java</code>, <code>a.java</code>
+ * and <code>Foo.java</code>, but not <code>Foo.properties</code>
+ * (does not end with <code>.java</code>).
+ * </p>
+ * <p>
+ * '?' matches 1 character within a segment. So <code>?.java</code>
+ * matches <code>a.java</code>, <code>A.java</code>,
+ * but not <code>.java</code> or <code>xyz.java</code> (neither have
+ * just one character before <code>.java</code>).
+ * </p>
+ * <p>
+ * Combinations of *'s and ?'s are allowed.
+ * </p>
+ * <p>
+ * The special pattern '**' matches zero or more segments. In a source entry,
+ * a path like <code>tests/</code> that ends in a trailing separator is interpreted
+ * as <code>tests/**</code>, and would match everything under
+ * the folder named <code>tests</code>.
+ * </p>
+ * <p>
+ * Example patterns in source entries (assuming that "java" is the only {@link JavaCore#getJavaLikeExtensions() Java-like extension}):
+ * <ul>
+ * <li>
+ * <code>tests/**</code> (or simply <code>tests/</code>)
+ * matches all files under a root folder
+ * named <code>tests</code>. This includes <code>tests/Foo.java</code>
+ * and <code>tests/com/example/Foo.java</code>, but not
+ * <code>com/example/tests/Foo.java</code> (not under a root folder named
+ * <code>tests</code>).
+ * </li>
+ * <li>
+ * <code>tests/*</code> matches all files directly below a root
+ * folder named <code>tests</code>. This includes <code>tests/Foo.java</code>
+ * and <code>tests/FooHelp.java</code>
+ * but not <code>tests/com/example/Foo.java</code> (not directly under
+ * a folder named <code>tests</code>) or
+ * <code>com/Foo.java</code> (not under a folder named <code>tests</code>).
+ * </li>
+ * <li>
+ * <code>**/tests/**</code> matches all files under any
+ * folder named <code>tests</code>. This includes <code>tests/Foo.java</code>,
+ * <code>com/examples/tests/Foo.java</code>, and
+ * <code>com/examples/tests/unit/Foo.java</code>, but not
+ * <code>com/example/Foo.java</code> (not under a folder named
+ * <code>tests</code>).
+ * </li>
+ * </ul>
+ * </p>
+ *
+ * @return the possibly empty list of resource exclusion patterns
+ * associated with this classpath entry, or <code>null</code> if this kind
+ * of classpath entry does not support exclusion patterns
+ * @since 2.1
+ */
+ IPath[] getExclusionPatterns();
+
+ /**
+ * Returns the extra classpath attributes for this classpath entry. Returns an empty array if this entry
+ * has no extra attributes.
+ *
+ * @return the possibly empty list of extra classpath attributes for this classpath entry
+ * @since 3.1
+ */
+ //IClasspathAttribute[] getExtraAttributes();
+
+ /**
+ * Returns the set of patterns used to explicitly define resources or classes
+ * to be included with this classpath entry.
+ * <p>
+ * For source classpath entries,
+ * when no inclusion patterns are specified, the source entry includes all
+ * relevent files in the resource tree rooted at this source entry's path.
+ * Specifying one or more inclusion patterns means that only the specified
+ * portions of the resource tree are to be included. Each path specified
+ * must be a relative path, and will be interpreted relative to this source
+ * entry's path. File patterns are case-sensitive. A file matched by one or
+ * more of these patterns is included in the corresponding package fragment
+ * root unless it is excluded by one or more of this entrie's exclusion
+ * patterns. Exclusion patterns have higher precedence than inclusion
+ * patterns; in other words, exclusion patterns can remove files for the
+ * ones that are to be included, not the other way around.
+ * </p>
+ * <p>
+ * See {@link #getExclusionPatterns()} for a discussion of the syntax and
+ * semantics of path patterns. The absence of any inclusion patterns is
+ * semantically equivalent to the explicit inclusion pattern
+ * <code>**</code>.
+ * </p>
+ * <p>
+ * Example patterns in source entries:
+ * <ul>
+ * <li>
+ * The inclusion pattern <code>src/**</code> by itself includes all
+ * files under a root folder named <code>src</code>.
+ * </li>
+ * <li>
+ * The inclusion patterns <code>src/**</code> and
+ * <code>tests/**</code> includes all files under the root folders
+ * named <code>src</code> and <code>tests</code>.
+ * </li>
+ * <li>
+ * The inclusion pattern <code>src/**</code> together with the
+ * exclusion pattern <code>src/**/Foo.java</code> includes all
+ * files under a root folder named <code>src</code> except for ones
+ * named <code>Foo.java</code>.
+ * </li>
+ * </ul>
+ * </p>
+ *
+ * @return the possibly empty list of resource inclusion patterns
+ * associated with this classpath entry, or <code>null</code> if this kind
+ * of classpath entry does not support inclusion patterns
+ * @since 3.0
+ */
+ IPath[] getInclusionPatterns();
+
+ /**
+ * Returns the full path to the specific location where the builder writes
+ * <code>.class</code> files generated for this source entry
+ * (entry kind {@link #CPE_SOURCE}).
+ * <p>
+ * Source entries can optionally be associated with a specific output location.
+ * If none is provided, the source entry will be implicitly associated with its project
+ * default output location (see {@link IJavaProject#getOutputLocation}).
+ * </p><p>
+ * NOTE: A specific output location cannot coincidate with another source/library entry.
+ * </p>
+ *
+ * @return the full path to the specific location where the builder writes
+ * <code>.class</code> files for this source entry, or <code>null</code>
+ * if using default output folder
+ * @since 2.1
+ */
+ IPath getOutputLocation();
+
+ /**
+ * Returns the path of this classpath entry.
+ *
+ * The meaning of the path of a classpath entry depends on its entry kind:<ul>
+ * <li>Source code in the current project ({@link #CPE_SOURCE}) -
+ * The path associated with this entry is the absolute path to the root folder. </li>
+ * <li>A binary library in the current project ({@link #CPE_LIBRARY}) - the path
+ * associated with this entry is the absolute path to the JAR (or root folder), and
+ * in case it refers to an external library, then there is no associated resource in
+ * the workbench.
+ * <li>A required project ({@link #CPE_PROJECT}) - the path of the entry denotes the
+ * path to the corresponding project resource.</li>
+ * <li>A variable entry ({@link #CPE_VARIABLE}) - the first segment of the path
+ * is the name of a classpath variable. If this classpath variable
+ * is bound to the path <i>P</i>, the path of the corresponding classpath entry
+ * is computed by appending to <i>P</i> the segments of the returned
+ * path without the variable.</li>
+ * <li> A container entry ({@link #CPE_CONTAINER}) - the path of the entry
+ * is the name of the classpath container, which can be bound indirectly to a set of classpath
+ * entries after resolution. The containerPath is a formed by a first ID segment followed with
+ * extra segments that can be used as additional hints for resolving this container
+ * reference (also see {@link IClasspathContainer}).
+ * </li>
+ * </ul>
+ *
+ * @return the path of this classpath entry
+ */
+ IPath getPath();
+
+ /**
+ * Returns the path to the source archive or folder associated with this
+ * classpath entry, or <code>null</code> if this classpath entry has no
+ * source attachment.
+ * <p>
+ * Only library and variable classpath entries may have source attachments.
+ * For library classpath entries, the result path (if present) locates a source
+ * archive or folder. This archive or folder can be located in a project of the
+ * workspace or outside the workspace. For variable classpath entries, the
+ * result path (if present) has an analogous form and meaning as the
+ * variable path, namely the first segment is the name of a classpath variable.
+ * </p>
+ *
+ * @return the path to the source archive or folder, or <code>null</code> if none
+ */
+ IPath getSourceAttachmentPath();
+
+ /**
+ * Returns the path within the source archive or folder where package fragments
+ * are located. An empty path indicates that packages are located at
+ * the root of the source archive or folder. Returns a non-<code>null</code> value
+ * if and only if {@link #getSourceAttachmentPath} returns
+ * a non-<code>null</code> value.
+ *
+ * @return the path within the source archive or folder, or <code>null</code> if
+ * not applicable
+ */
+ IPath getSourceAttachmentRootPath();
+
+
+ /**
+ * Returns the classpath entry that is making a reference to this classpath entry. For entry kinds
+ * {@link #CPE_LIBRARY}, the return value is the entry that is representing the JAR that includes
+ * <code>this</code> in the MANIFEST.MF file's Class-Path section. For entry kinds other than
+ * {@link #CPE_LIBRARY}, this returns <code>null</code>. For those entries that are on the raw classpath already,
+ * this returns <code>null</code>.
+ * <p>
+ * It is possible that multiple library entries refer to the same entry
+ * via the MANIFEST.MF file. In those cases, this method returns the first classpath entry
+ * that appears in the raw classpath. However, this does not mean that the other referencing
+ * entries do not relate to their referenced entries.
+ * See {@link JavaCore#getReferencedClasspathEntries(IClasspathEntry, IJavaProject)} for
+ * more details.
+ * </p>
+ *
+ * @return the classpath entry that is referencing this entry or <code>null</code> if
+ * not applicable.
+ * @since 3.6
+ */
+ IClasspathEntry getReferencingEntry();
+
+ /**
+ * Returns whether this entry is exported to dependent projects.
+ * Always returns <code>false</code> for source entries (kind
+ * {@link #CPE_SOURCE}), which cannot be exported.
+ *
+ * @return <code>true</code> if exported, and <code>false</code> otherwise
+ * @since 2.0
+ */
+ boolean isExported();
+
+ /**
+ * This is a helper method, which returns the resolved classpath entry denoted
+ * by an entry (if it is a variable entry). It is obtained by resolving the variable
+ * reference in the first segment. Returns <code>null</code> if unable to resolve using
+ * the following algorithm:
+ * <ul>
+ * <li> if variable segment cannot be resolved, returns <code>null</code></li>
+ * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
+ * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
+ * <li> if none returns <code>null</code></li>
+ * </ul>
+ * <p>
+ * Variable source attachment is also resolved and recorded in the resulting classpath entry.
+ * <p>
+ * @return the resolved library or project classpath entry, or <code>null</code>
+ * if the given path could not be resolved to a classpath entry
+ * <p>
+ * Note that this deprecated API doesn't handle CPE_CONTAINER entries.
+ *
+ * @deprecated Use {@link JavaCore#getResolvedClasspathEntry(IClasspathEntry)} instead
+ */
+ IClasspathEntry getResolvedEntry();
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJarEntryResource.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJarEntryResource.java
new file mode 100644
index 00000000..fd935222
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJarEntryResource.java
@@ -0,0 +1,11 @@
+package org.eclipse.jdt.core;
+
+/**
+ * IJarEntryResource: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IJarEntryResource extends IStorage {
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJavaElement.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJavaElement.java
new file mode 100644
index 00000000..1294babf
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJavaElement.java
@@ -0,0 +1,12 @@
+package org.eclipse.jdt.core;
+
+
+/**
+ * IJavaElement without logic, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IJavaElement {
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJavaProject.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJavaProject.java
new file mode 100644
index 00000000..093e2d91
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IJavaProject.java
@@ -0,0 +1,107 @@
+package org.eclipse.jdt.core;
+
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * IJavaProject: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IJavaProject {
+
+ /**
+ * This is a helper method returning the resolved classpath for the project
+ * as a list of simple (non-variable, non-container) classpath entries.
+ * All classpath variable and classpath container entries in the project's
+ * raw classpath will be replaced by the simple classpath entries they
+ * resolve to.
+ * <p>
+ * The resulting resolved classpath is accurate for the given point in time.
+ * If the project's raw classpath is later modified, or if classpath
+ * variables are changed, the resolved classpath can become out of date.
+ * Because of this, hanging on resolved classpath is not recommended.
+ * </p>
+ * <p>
+ * Note that if the resolution creates duplicate entries
+ * (i.e. {@link IClasspathEntry entries} which are {@link Object#equals(Object)}),
+ * only the first one is added to the resolved classpath.
+ * </p>
+ *
+ * @param ignoreUnresolvedEntry indicates how to handle unresolvable
+ * variables and containers; <code>true</code> indicates that missing
+ * variables and unresolvable classpath containers should be silently
+ * ignored, and that the resulting list should consist only of the
+ * entries that could be successfully resolved; <code>false</code> indicates
+ * that a <code>JavaModelException</code> should be thrown for the first
+ * unresolved variable or container
+ * @return the resolved classpath for the project as a list of simple
+ * classpath entries, where all classpath variable and container entries
+ * have been resolved and substituted with their final target entries
+ * @exception JavaModelException in one of the corresponding situation:
+ * <ul>
+ * <li>this element does not exist</li>
+ * <li>an exception occurs while accessing its corresponding resource</li>
+ * <li>a classpath variable or classpath container was not resolvable
+ * and <code>ignoreUnresolvedEntry</code> is <code>false</code>.</li>
+ * </ul>
+ * @see IClasspathEntry
+ */
+ IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry);
+
+ /**
+ * Returns the first existing package fragment on this project's classpath
+ * whose path matches the given (absolute) path, or <code>null</code> if none
+ * exist.
+ * The path can be:
+ * - internal to the workbench: "/Project/src"
+ * - external to the workbench: "c:/jdk/classes.zip/java/lang"
+ * @param path the given absolute path
+ * @exception JavaModelException if this project does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ * @return the first existing package fragment on this project's classpath
+ * whose path matches the given (absolute) path, or <code>null</code> if none
+ * exist
+ */
+ IPackageFragment findPackageFragment(IPath path); //throws JavaModelException;
+
+ /**
+ * Returns the existing package fragment roots identified by the given entry.
+ * A classpath entry within the current project identifies a single root.
+ * <p>
+ * If the classpath entry denotes a variable, it will be resolved and return
+ * the roots of the target entry (empty if not resolvable).
+ * <p>
+ * If the classpath entry denotes a container, it will be resolved and return
+ * the roots corresponding to the set of container entries (empty if not resolvable).
+ * <p>
+ * The result does not include package fragment roots in other projects
+ * referenced on this project's classpath.
+ *
+ * @param entry the given entry
+ * @return the existing package fragment roots identified by the given entry
+ * @see IClasspathContainer
+ * @since 2.1
+ */
+ IPackageFragmentRoot[] findPackageFragmentRoots(IClasspathEntry entry);
+
+ /**
+ * Returns an array of non-Java resources directly contained in this project.
+ * It does not transitively answer non-Java resources contained in folders;
+ * these would have to be explicitly iterated over.
+ * <p>
+ * Non-Java resources includes other files and folders located in the
+ * project not accounted for by any of it source or binary package fragment
+ * roots. If the project is a source folder itself, resources excluded from the
+ * corresponding source classpath entry by one or more exclusion patterns
+ * are considered non-Java resources and will appear in the result
+ * (possibly in a folder)
+ * </p>
+ *
+ * @return an array of non-Java resources (<code>IFile</code>s and/or
+ * <code>IFolder</code>s) directly contained in this project
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+ Object[] getNonJavaResources(); //throws JavaModelException;
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IPackageFragment.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IPackageFragment.java
new file mode 100644
index 00000000..70521ed0
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IPackageFragment.java
@@ -0,0 +1,46 @@
+package org.eclipse.jdt.core;
+
+/**
+ * IPackageFragment: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IPackageFragment {
+
+ /**
+ * Returns the dot-separated package name of this fragment, for example
+ * <code>"java.lang"</code>, or <code>""</code> (the empty string),
+ * for the default package.
+ *
+ * @return the dot-separated package name of this fragment
+ */
+ String getElementName();
+
+ /**
+ * Returns an array of non-Java resources contained in this package fragment.
+ * <p>
+ * Non-Java resources includes other files and folders located in the same
+ * directory as the compilation units or class files for this package
+ * fragment. Source files excluded from this package by virtue of
+ * inclusion/exclusion patterns on the corresponding source classpath entry
+ * are considered non-Java resources and will appear in the result
+ * (possibly in a folder).
+ * </p><p>
+ * Since 3.3, if this package fragment is inside an archive, the non-Java resources
+ * are a tree of {@link IJarEntryResource}s. One can navigate this tree using
+ * the {@link IJarEntryResource#getChildren()} and
+ * {@link IJarEntryResource#getParent()} methods.
+ * </p>
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ * @return an array of non-Java resources (<code>IFile</code>s,
+ * <code>IFolder</code>s, or <code>IStorage</code>s if the
+ * package fragment is in an archive) contained in this package
+ * fragment
+ * @see IClasspathEntry#getInclusionPatterns()
+ * @see IClasspathEntry#getExclusionPatterns()
+ */
+ Object[] getNonJavaResources(); //throws JavaModelException;
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IPackageFragmentRoot.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IPackageFragmentRoot.java
new file mode 100644
index 00000000..c002c7f6
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IPackageFragmentRoot.java
@@ -0,0 +1,11 @@
+package org.eclipse.jdt.core;
+
+/**
+ * IPackageFragmentRoot: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IPackageFragmentRoot extends IJavaElement, IParent {
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IParent.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IParent.java
new file mode 100644
index 00000000..be261214
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IParent.java
@@ -0,0 +1,20 @@
+package org.eclipse.jdt.core;
+
+/**
+ * IParent: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IParent {
+ /**
+ * Returns the immediate children of this element.
+ * Unless otherwise specified by the implementing element,
+ * the children are in no particular order.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ * @return the immediate children of this element
+ */
+ IJavaElement[] getChildren(); //throws JavaModelException;
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IStorage.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IStorage.java
new file mode 100644
index 00000000..a9be9d96
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/IStorage.java
@@ -0,0 +1,35 @@
+package org.eclipse.jdt.core;
+
+import java.io.InputStream;
+
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ * IStorage: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public interface IStorage {
+ /**
+ * Returns an open input stream on the contents of this storage.
+ * The caller is responsible for closing the stream when finished.
+ *
+ * @return an input stream containing the contents of this storage
+ * @exception CoreException if the contents of this storage could
+ * not be accessed. See any refinements for more information.
+ */
+ public InputStream getContents() throws CoreException;
+
+ /**
+ * Returns the name of this storage.
+ * The name of a storage is synonymous with the last segment
+ * of its full path though if the storage does not have a path,
+ * it may still have a name.
+ *
+ * @return the name of the data represented by this storage,
+ * or <code>null</code> if this storage has no name
+ * @see #getFullPath()
+ */
+ public String getName();
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/JavaCore.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/JavaCore.java
new file mode 100644
index 00000000..52c271a9
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jdt/core/JavaCore.java
@@ -0,0 +1,17 @@
+package org.eclipse.jdt.core;
+
+import org.eclipse.core.resources.IContainer;
+
+/**
+ * JavaCore without logic, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class JavaCore {
+
+ public static IJavaElement create(IContainer container) {
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/Document.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/Document.java
new file mode 100644
index 00000000..19e6a38a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/Document.java
@@ -0,0 +1,24 @@
+package org.eclipse.jface.text;
+
+/**
+ * Simple Document class which only hold a String object.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class Document {
+
+ private String content;
+
+ public Document(String source) {
+ content = source;
+ }
+
+ public String get() {
+ return content;
+ }
+
+ public void set(String text) {
+ content = text;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/IRegion.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/IRegion.java
new file mode 100644
index 00000000..ca61b84e
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/IRegion.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.jface.text;
+
+
+/**
+ * A region describes a certain range in an indexed text store. Text stores are
+ * for example documents or strings. A region is defined by its offset into the
+ * text store and its length.
+ * <p>
+ * A region is considered a value object. Its offset and length do not change
+ * over time.
+ * <p>
+ * Clients may implement this interface or use the standard implementation
+ * {@link org.eclipse.jface.text.Region}.
+ * </p>
+ */
+public interface IRegion {
+
+ /**
+ * Returns the length of the region.
+ *
+ * @return the length of the region
+ */
+ int getLength();
+
+ /**
+ * Returns the offset of the region.
+ *
+ * @return the offset of the region
+ */
+ int getOffset();
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/Region.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/Region.java
new file mode 100644
index 00000000..01fd5bff
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/text/Region.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.jface.text;
+
+
+/**
+ * The default implementation of the {@link org.eclipse.jface.text.IRegion} interface.
+ */
+public class Region implements IRegion {
+
+ /** The region offset */
+ private int fOffset;
+ /** The region length */
+ private int fLength;
+
+ /**
+ * Create a new region.
+ *
+ * @param offset the offset of the region
+ * @param length the length of the region
+ */
+ public Region(int offset, int length) {
+ fOffset= offset;
+ fLength= length;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.IRegion#getLength()
+ */
+ public int getLength() {
+ return fLength;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.IRegion#getOffset()
+ */
+ public int getOffset() {
+ return fOffset;
+ }
+
+ /*
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object o) {
+ if (o instanceof IRegion) {
+ IRegion r= (IRegion) o;
+ return r.getOffset() == fOffset && r.getLength() == fLength;
+ }
+ return false;
+ }
+
+ /*
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+ return (fOffset << 24) | (fLength << 16);
+ }
+
+ /*
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "offset: " + fOffset + ", length: " + fLength; //$NON-NLS-1$ //$NON-NLS-2$;
+ }
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/viewers/StyledCellLabelProvider.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/viewers/StyledCellLabelProvider.java
new file mode 100644
index 00000000..30b04cae
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/jface/viewers/StyledCellLabelProvider.java
@@ -0,0 +1,20 @@
+package org.eclipse.jface.viewers;
+
+/**
+ * StyledCellLabelProvider: added only needed parts, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public abstract class StyledCellLabelProvider extends CellLabelProvider {
+
+ private ColumnViewer viewer;
+
+ public ColumnViewer getViewer() {
+ // TODO [RAP] handle column viewer
+ /*if (viewer == null)
+ viewer = new */
+ return viewer;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/swt/custom/StyleRange.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/swt/custom/StyleRange.java
new file mode 100644
index 00000000..270d535d
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/swt/custom/StyleRange.java
@@ -0,0 +1,47 @@
+package org.eclipse.swt.custom;
+
+import org.eclipse.swt.graphics.Color;
+
+/**
+ * StyleRange without logic, just to get the source code compiled in RAP
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class StyleRange {
+ public int start;
+ public int length;
+ public int fontStyle;
+
+
+ public StyleRange() {
+
+ }
+
+ /**
+ * Create a new style range.
+ *
+ * @param start start offset of the style
+ * @param length length of the style
+ * @param foreground foreground color of the style, null if none; UNUSED in RAP
+ * @param background background color of the style, null if none; UNUSED in RAP
+ */
+ public StyleRange(int start, int length, Color foreground, Color background) {
+ this.start = start;
+ this.length = length;
+ }
+
+ /**
+ * Create a new style range.
+ *
+ * @param start start offset of the style
+ * @param length length of the style
+ * @param foreground foreground color of the style, null if none; UNUSED in RAP
+ * @param background background color of the style, null if none; UNUSED in RAP
+ * @param fontStyle font style of the style, may be SWT.NORMAL, SWT.ITALIC or SWT.BOLD
+ */
+ public StyleRange(int start, int length, Color foreground, Color background, int fontStyle) {
+ this(start, length, foreground, background);
+ this.fontStyle = fontStyle;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/swt/custom/StyledText.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/swt/custom/StyledText.java
new file mode 100644
index 00000000..8710e609
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/swt/custom/StyledText.java
@@ -0,0 +1,18 @@
+package org.eclipse.swt.custom;
+
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+
+/**
+ * StyledText class is a wrapper for a Label in RAP
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class StyledText extends Label {
+ private static final long serialVersionUID = -5801418312829430710L;
+
+ public StyledText(Composite parent, int style) {
+ super(parent, style);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IFileEditorInput.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IFileEditorInput.java
new file mode 100644
index 00000000..54943f47
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IFileEditorInput.java
@@ -0,0 +1,50 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui;
+
+import org.eclipse.core.resources.IFile;
+
+/**
+ * This interface defines a file-oriented input to an editor.
+ * <p>
+ * Clients implementing this editor input interface should override
+ * <code>Object.equals(Object)</code> to answer true for two inputs
+ * that are the same. The <code>IWorbenchPage.openEditor</code> APIs
+ * are dependent on this to find an editor with the same input.
+ * </p><p>
+ * File-oriented editors should support this as a valid input type, and allow
+ * full read-write editing of its content.
+ * </p><p>
+ * A default implementation of this interface is provided by
+ * org.eclipse.ui.part.FileEditorInput.
+ * </p><p>
+ * All editor inputs must implement the <code>IAdaptable</code> interface;
+ * extensions are managed by the platform's adapter manager.
+ * </p>
+ *
+ * @see org.eclipse.core.resources.IFile
+ */
+public interface IFileEditorInput extends IStorageEditorInput {
+ /**
+ * Returns the file resource underlying this editor input.
+ * <p>
+ * The <code>IFile</code> returned can be a handle to a resource
+ * that does not exist in the workspace. As such, an editor should
+ * provide appropriate feedback to the user instead of simply failing
+ * during input validation. For example, a text editor could open
+ * in read-only mode with a message in the text area to inform the
+ * user that the file does not exist.
+ * </p>
+ *
+ * @return the underlying file
+ */
+ public IFile getFile();
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IStorageEditorInput.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IStorageEditorInput.java
new file mode 100644
index 00000000..b640a5c3
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IStorageEditorInput.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui;
+
+import org.eclipse.core.resources.IStorage;
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ * Interface for a <code>IStorage</code> input to an editor.
+ * <p>
+ * Clients implementing this editor input interface should override
+ * <code>Object.equals(Object)</code> to answer true for two inputs
+ * that are the same. The <code>IWorbenchPage.openEditor</code> APIs
+ * are dependent on this to find an editor with the same input.
+ * </p><p>
+ * Clients should implement this interface to declare new types of
+ * <code>IStorage</code> editor inputs.
+ * </p><p>
+ * File-oriented editors should support this as a valid input type, and display
+ * its content for viewing (but not allow modification).
+ * Within the editor, the "save" and "save as" operations should create a new
+ * file resource within the workspace.
+ * </p><p>
+ * All editor inputs must implement the <code>IAdaptable</code> interface;
+ * extensions are managed by the platform's adapter manager.
+ * </p>
+ */
+public interface IStorageEditorInput extends IEditorInput {
+ /**
+ * Returns the underlying IStorage object.
+ *
+ * @return an IStorage object.
+ * @exception CoreException if this method fails
+ */
+ public IStorage getStorage() throws CoreException;
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IURIEditorInput.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IURIEditorInput.java
new file mode 100644
index 00000000..7d111113
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/IURIEditorInput.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Copyright (c) 2006, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui;
+
+import java.net.URI;
+
+import org.eclipse.ui.IEditorInput;
+
+/**
+ * This interface defines an editor input based on a URI.
+ * <p>
+ * Clients implementing this editor input interface should override
+ * <code>Object.equals(Object)</code> to answer true for two inputs
+ * that are the same. The <code>IWorkbenchPage.openEditor</code> APIs
+ * are dependent on this to find an editor with the same input.
+ * </p><p>
+ * Path-oriented editors should support this as a valid input type, and
+ * can allow full read-write editing of its content.
+ * </p><p>
+ * All editor inputs must implement the <code>IAdaptable</code> interface;
+ * extensions are managed by the platform's adapter manager.
+ * </p>
+ *
+ * @see URI
+ * @since 3.3
+ */
+public interface IURIEditorInput extends IEditorInput {
+ /**
+ * Returns the {@link URI} of the file underlying this editor input.
+ *
+ * @return {@link URI}
+ */
+ public URI getURI();
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/dialogs/ContainerSelectionDialog.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/dialogs/ContainerSelectionDialog.java
new file mode 100644
index 00000000..32c1670e
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/dialogs/ContainerSelectionDialog.java
@@ -0,0 +1,26 @@
+package org.eclipse.ui.dialogs;
+
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.swt.widgets.Shell;
+
+
+/**
+ * ContainerSelectionDialog without logic, just to get the source code compiled in RAP.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class ContainerSelectionDialog {
+
+ public ContainerSelectionDialog(Shell s, IWorkspaceRoot wr, boolean b, String str) {
+
+ }
+
+ public int open() {
+ return 0;
+ }
+
+ public Object[] getResult() {
+ return null;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/editors/text/TextEditor.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/editors/text/TextEditor.java
new file mode 100644
index 00000000..3803da4c
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/editors/text/TextEditor.java
@@ -0,0 +1,234 @@
+package org.eclipse.ui.editors.text;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.commons.io.FileUtils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.part.EditorPart;
+import org.eclipse.ui.texteditor.DocumentProvider;
+import org.eclipse.ui.texteditor.ITextEditor;
+
+/**
+ * Simple text editor, which operates on a file and uses a text widget as interface.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class TextEditor extends EditorPart implements ITextEditor {
+
+ public static final String ID = "org.eclipselabs.tapiji.translator.rap.wrappers.TextEditor";
+
+ private File file;
+ private Text textField;
+ private boolean editable = true;
+ private boolean dirty = false;
+ private DocumentProvider documentProvider;
+
+ public TextEditor() {
+ }
+
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ if (monitor != null)
+ monitor.beginTask("Saving file...", 1);
+ writeFile();
+ setDirty(false);
+ if (monitor != null)
+ monitor.done();
+ }
+
+ @Override
+ public void doSaveAs() {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ if ((input instanceof IFileEditorInput)) {
+ IFileEditorInput ifei = (IFileEditorInput) input;
+ IFile ifile = ifei.getFile();
+ file = ifile.getRawLocation().makeAbsolute().toFile();
+ } else {
+ throw new RuntimeException("Input not of type " + IFileEditorInput.class.getName());
+ }
+ setSite(site);
+ setInput(input);
+ setPartName(input.getName());
+ }
+
+ @Override
+ public boolean isDirty() {
+ return dirty;
+ }
+
+ private void setDirty(boolean value) {
+ dirty = value;
+ firePropertyChange( PROP_DIRTY );
+ }
+
+ @Override
+ public boolean isSaveAsAllowed() {
+ return true;
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ textField = new Text(parent, SWT.HORIZONTAL);
+ textField.setText(readFile());
+
+ textField.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent event) {
+ if (!dirty) {
+ setDirty(true);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void setFocus() {
+ textField.setFocus();
+ }
+
+ private void setText(String text) {
+ if (textField != null)
+ textField.setText(text);
+ }
+
+ private String getText() {
+ if (textField != null)
+ return textField.getText();
+ else if (file != null)
+ return readFile();
+ else
+ return null;
+ }
+
+ public DocumentProvider getDocumentProvider() {
+ if (documentProvider == null) {
+ documentProvider = new DocumentProvider(getText());
+ }
+ return documentProvider;
+ }
+
+ private String readFile() {
+ String content = null;
+ try {
+ content = FileUtils.readFileToString(file);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return content;
+ }
+
+ private void writeFile() {
+ String content = textField.getText();
+ try {
+ FileUtils.writeStringToFile(file, content);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void selectAndReveal(int selectionIndex, int selectionLength) {
+ textField.setSelection(selectionIndex, selectionIndex+selectionLength);
+ textField.setFocus();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ @Override
+ public void doRevertToSaved() {
+ textField.setText(readFile());
+ }
+
+ @Override
+ public void close(boolean save) {
+ if (save)
+ doSave(null);
+ }
+
+ @Override
+ public void setAction(String actionID, IAction action) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setActionActivationCode(String actionId,
+ char activationCharacter, int activationKeyCode,
+ int activationStateMask) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void removeActionActivationCode(String actionId) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean showsHighlightRangeOnly() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void showHighlightRangeOnly(boolean showHighlightRangeOnly) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setHighlightRange(int offset, int length, boolean moveCursor) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public IRegion getHighlightRange() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void resetHighlightRange() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public ISelectionProvider getSelectionProvider() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IAction getAction(String actionId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/FileStoreEditorInput.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/FileStoreEditorInput.java
new file mode 100644
index 00000000..89f6699c
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/FileStoreEditorInput.java
@@ -0,0 +1,170 @@
+/*******************************************************************************
+ * Copyright (c) 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui.ide;
+
+import java.net.URI;
+
+import org.eclipse.core.filesystem.IFileStore;
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.IPersistableElement;
+import org.eclipse.ui.IURIEditorInput;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+
+/**
+ * Implements an IEditorInput instance appropriate for
+ * <code>IFileStore</code> elements that represent files
+ * that are not part of the current workspace.
+ *
+ * @since 3.3
+ *
+ */
+public class FileStoreEditorInput implements IURIEditorInput, IPersistableElement {
+
+ /**
+ * The workbench adapter which simply provides the label.
+ *
+ * @since 3.3
+ */
+ private static class WorkbenchAdapter implements IWorkbenchAdapter {
+ /*
+ * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object)
+ */
+ public Object[] getChildren(Object o) {
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.ui.model.IWorkbenchAdapter#getImageDescriptor(java.lang.Object)
+ */
+ public ImageDescriptor getImageDescriptor(Object object) {
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object)
+ */
+ public String getLabel(Object o) {
+ return ((FileStoreEditorInput) o).getName();
+ }
+
+ /*
+ * @see org.eclipse.ui.model.IWorkbenchAdapter#getParent(java.lang.Object)
+ */
+ public Object getParent(Object o) {
+ return null;
+ }
+ }
+
+ private IFileStore fileStore;
+ private WorkbenchAdapter workbenchAdapter = new WorkbenchAdapter();
+
+ /**
+ * @param fileStore
+ */
+ public FileStoreEditorInput(IFileStore fileStore) {
+ Assert.isNotNull(fileStore);
+ this.fileStore = fileStore;
+ workbenchAdapter = new WorkbenchAdapter();
+ }
+
+ /*
+ * @see org.eclipse.ui.IEditorInput#exists()
+ */
+ public boolean exists() {
+ return fileStore.fetchInfo().exists();
+ }
+
+ /*
+ * @see org.eclipse.ui.IEditorInput#getImageDescriptor()
+ */
+ public ImageDescriptor getImageDescriptor() {
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.ui.IEditorInput#getName()
+ */
+ public String getName() {
+ return fileStore.getName();
+ }
+
+ /*
+ * @see org.eclipse.ui.IEditorInput#getPersistable()
+ */
+ public IPersistableElement getPersistable() {
+ return this;
+ }
+
+ /*
+ * @see org.eclipse.ui.IEditorInput#getToolTipText()
+ */
+ public String getToolTipText() {
+ return fileStore.toString();
+ }
+
+ /*
+ * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
+ */
+ public Object getAdapter(Class adapter) {
+ if (IWorkbenchAdapter.class.equals(adapter))
+ return workbenchAdapter;
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
+
+ /*
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+
+ if (o instanceof FileStoreEditorInput) {
+ FileStoreEditorInput input = (FileStoreEditorInput) o;
+ return fileStore.equals(input.fileStore);
+ }
+
+ return false;
+ }
+
+ /*
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+ return fileStore.hashCode();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IURIEditorInput#getURI()
+ */
+ public URI getURI() {
+ return fileStore.toURI();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.IPersistableElement#getFactoryId()
+ */
+ public String getFactoryId() {
+ return FileStoreEditorInputFactory.ID;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)
+ */
+ public void saveState(IMemento memento) {
+ FileStoreEditorInputFactory.saveState(memento, this);
+
+ }
+
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/FileStoreEditorInputFactory.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/FileStoreEditorInputFactory.java
new file mode 100644
index 00000000..72fc12ae
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/FileStoreEditorInputFactory.java
@@ -0,0 +1,83 @@
+/*******************************************************************************
+ * Copyright (c) 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ ******************************************************************************/
+package org.eclipse.ui.ide;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.eclipse.core.filesystem.EFS;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IAdaptable;
+
+import org.eclipse.ui.IElementFactory;
+import org.eclipse.ui.IMemento;
+
+
+/**
+ * Factory for saving and restoring a <code>FileStoreEditorInput</code>.
+ * The stored representation of a <code>FileStoreEditorInput</code> remembers
+ * the path of the editor input.
+ * <p>
+ * The workbench will automatically create instances of this class as required.
+ * It is not intended to be instantiated or subclassed by the client.</p>
+ *
+ * @since 3.3
+ */
+public class FileStoreEditorInputFactory implements IElementFactory {
+
+ /**
+ * This factory's ID.
+ * <p>
+ * The editor plug-in registers a factory by this name with
+ * the <code>"org.eclipse.ui.elementFactories"<code> extension point.
+ */
+ static final String ID = "org.eclipse.ui.ide.FileStoreEditorInputFactory"; //$NON-NLS-1$
+
+ /**
+ * Saves the state of the given editor input into the given memento.
+ *
+ * @param memento the storage area for element state
+ * @param input the file editor input
+ */
+ static void saveState(IMemento memento, FileStoreEditorInput input) {
+ URI uri = input.getURI();
+ memento.putString(TAG_URI, uri.toString());
+ }
+
+ /**
+ * Tag for the URI string.
+ */
+ private static final String TAG_URI = "uri"; //$NON-NLS-1$
+
+ /*
+ * @see org.eclipse.ui.IElementFactory#createElement(org.eclipse.ui.IMemento)
+ */
+ public IAdaptable createElement(IMemento memento) {
+ // Get the file name.
+ String uriString = memento.getString(TAG_URI);
+ if (uriString == null)
+ return null;
+
+ URI uri;
+ try {
+ uri = new URI(uriString);
+ } catch (URISyntaxException e) {
+ return null;
+ }
+
+ try {
+ return new FileStoreEditorInput(EFS.getStore(uri));
+ } catch (CoreException e) {
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IDE.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IDE.java
new file mode 100644
index 00000000..14622a11
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IDE.java
@@ -0,0 +1,1648 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2010 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui.ide;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.core.filesystem.EFS;
+import org.eclipse.core.filesystem.IFileStore;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceStatus;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.resources.mapping.IModelProviderDescriptor;
+import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
+import org.eclipse.core.resources.mapping.ModelProvider;
+import org.eclipse.core.resources.mapping.ModelStatus;
+import org.eclipse.core.resources.mapping.ResourceChangeValidator;
+import org.eclipse.core.resources.mapping.ResourceMapping;
+import org.eclipse.core.resources.mapping.ResourceMappingContext;
+import org.eclipse.core.resources.mapping.ResourceTraversal;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IAdapterFactory;
+import org.eclipse.core.runtime.IAdapterManager;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.MultiStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.QualifiedName;
+import org.eclipse.core.runtime.SafeRunner;
+import org.eclipse.core.runtime.content.IContentDescription;
+import org.eclipse.core.runtime.content.IContentType;
+import org.eclipse.core.runtime.content.IContentTypeMatcher;
+import org.eclipse.jface.dialogs.ErrorDialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.util.SafeRunnable;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IEditorDescriptor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorReference;
+import org.eclipse.ui.IEditorRegistry;
+//import org.eclipse.ui.IMarkerHelpRegistry;
+import org.eclipse.ui.ISaveableFilter;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.IWorkbenchPartReference;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.MultiPartInitException;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.Saveable;
+import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
+/*import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
+import org.eclipse.ui.internal.ide.model.StandardPropertiesAdapterFactory;
+import org.eclipse.ui.internal.ide.model.WorkbenchAdapterFactory;
+import org.eclipse.ui.internal.ide.registry.MarkerHelpRegistry;
+import org.eclipse.ui.internal.ide.registry.MarkerHelpRegistryReader; */
+import org.eclipse.ui.internal.misc.UIStats;
+import org.eclipse.ui.part.FileEditorInput;
+
+/**
+ * Collection of IDE-specific APIs factored out of existing workbench. This
+ * class cannot be instantiated; all functionality is provided by static methods
+ * and fields.
+ *
+ * @since 3.0
+ */
+public final class IDE {
+ /**
+ * The persistent property key used on IFile resources to contain the
+ * preferred editor ID to use.
+ * <p>
+ * Example of retrieving the persisted editor id:
+ *
+ * <pre><code>
+ * IFile file = ...
+ * IEditorDescriptor editorDesc = null;
+ * try {
+ * String editorID = file.getPersistentProperty(EDITOR_KEY);
+ * if (editorID != null) {
+ * editorDesc = editorReg.findEditor(editorID);
+ * }
+ * } catch (CoreException e) {
+ * // handle problem accessing persistent property here
+ * }
+ * </code></pre>
+ *
+ * </p>
+ * <p>
+ * Example of persisting the editor id:
+ *
+ * <pre><code>
+ * IFile file = ...
+ * try {
+ * file.setPersistentProperty(EDITOR_KEY, editorDesc.getId());
+ * } catch (CoreException e) {
+ * // handle problem setting persistent property here
+ * }
+ * </code></pre>
+ *
+ * </p>
+ */
+ public static final QualifiedName EDITOR_KEY = new QualifiedName(
+ "org.eclipse.ui.internal.registry.ResourceEditorRegistry", "EditorProperty");//$NON-NLS-2$//$NON-NLS-1$
+
+ /**
+ * An optional attribute within a workspace marker (<code>IMarker</code>)
+ * which identifies the preferred editor type to be opened.
+ */
+ public static final String EDITOR_ID_ATTR = "org.eclipse.ui.editorID"; //$NON-NLS-1$
+
+ /**
+ * The resource based perspective identifier.
+ */
+ public static final String RESOURCE_PERSPECTIVE_ID = "org.eclipse.ui.resourcePerspective"; //$NON-NLS-1$
+
+ /**
+ * Marker help registry mapping markers to help context ids and resolutions;
+ * lazily initialized on fist access.
+ */
+ //private static MarkerHelpRegistry markerHelpRegistry = null;
+
+ /**
+ * Standard shared images defined by the IDE. These are over and above the
+ * standard workbench images declared in {@link org.eclipse.ui.ISharedImages
+ * ISharedImages}.
+ * <p>
+ * This interface is not intended to be implemented by clients.
+ * </p>
+ *
+ * @see org.eclipse.ui.ISharedImages
+ */
+ public interface SharedImages {
+ /**
+ * Identifies a project image.
+ */
+ public final static String IMG_OBJ_PROJECT = "IMG_OBJ_PROJECT"; //$NON-NLS-1$
+
+ /**
+ * Identifies a closed project image.
+ */
+ public final static String IMG_OBJ_PROJECT_CLOSED = "IMG_OBJ_PROJECT_CLOSED"; //$NON-NLS-1$
+
+ /**
+ * Identifies the image used for "open marker".
+ */
+ public final static String IMG_OPEN_MARKER = "IMG_OPEN_MARKER"; //$NON-NLS-1$
+
+ /**
+ * Identifies the default image used to indicate a task.
+ */
+ public final static String IMG_OBJS_TASK_TSK = "IMG_OBJS_TASK_TSK"; //$NON-NLS-1$
+
+ /**
+ * Identifies the default image used to indicate a bookmark.
+ */
+ public final static String IMG_OBJS_BKMRK_TSK = "IMG_OBJS_BKMRK_TSK"; //$NON-NLS-1$
+ }
+
+ /**
+ * Preferences defined by the IDE workbench.
+ * <p>
+ * This interface is not intended to be implemented by clients.
+ * </p>
+ */
+ public interface Preferences {
+
+ /**
+ * A named preference for how a new perspective should be opened when a
+ * new project is created.
+ * <p>
+ * Value is of type <code>String</code>. The possible values are
+ * defined by the constants
+ * <code>OPEN_PERSPECTIVE_WINDOW, OPEN_PERSPECTIVE_PAGE,
+ * OPEN_PERSPECTIVE_REPLACE, and NO_NEW_PERSPECTIVE</code>.
+ * </p>
+ *
+ * @see org.eclipse.ui.IWorkbenchPreferenceConstants#OPEN_PERSPECTIVE_WINDOW
+ * @see org.eclipse.ui.IWorkbenchPreferenceConstants#OPEN_PERSPECTIVE_PAGE
+ * @see org.eclipse.ui.IWorkbenchPreferenceConstants#OPEN_PERSPECTIVE_REPLACE
+ * @see org.eclipse.ui.IWorkbenchPreferenceConstants#NO_NEW_PERSPECTIVE
+ */
+ public static final String PROJECT_OPEN_NEW_PERSPECTIVE = "PROJECT_OPEN_NEW_PERSPECTIVE"; //$NON-NLS-1$
+
+ /**
+ * <p>
+ * Specifies whether or not the workspace selection dialog should be
+ * shown on startup.
+ * </p>
+ * <p>
+ * The default value for this preference is <code>true</code>.
+ * </p>
+ *
+ * @since 3.1
+ */
+ public static final String SHOW_WORKSPACE_SELECTION_DIALOG = "SHOW_WORKSPACE_SELECTION_DIALOG"; //$NON-NLS-1$
+
+ /**
+ * <p>
+ * Stores the maximum number of workspaces that should be displayed in
+ * the ChooseWorkspaceDialog.
+ * </p>
+ *
+ * @since 3.1
+ */
+ public static final String MAX_RECENT_WORKSPACES = "MAX_RECENT_WORKSPACES"; //$NON-NLS-1$
+
+ /**
+ * <p>
+ * Stores a comma separated list of the recently used workspace paths.
+ * </p>
+ *
+ * @since 3.1
+ */
+ public static final String RECENT_WORKSPACES = "RECENT_WORKSPACES"; //$NON-NLS-1$
+
+ /**
+ * <p>
+ * Stores the version of the protocol used to decode/encode the list of
+ * recent workspaces.
+ * </p>
+ *
+ * @since 3.1
+ */
+ public static final String RECENT_WORKSPACES_PROTOCOL = "RECENT_WORKSPACES_PROTOCOL"; //$NON-NLS-1$
+
+ }
+
+ /**
+ * A saveable filter that selects savables that contain resources that
+ * are descendants of the roots of the filter.
+ * @since 3.3
+ *
+ */
+ /* private static class SaveFilter implements ISaveableFilter {
+ private final IResource[] roots;
+
+ /**
+ * Create the filter
+ * @param roots the save roots
+ */
+ /* public SaveFilter(IResource[] roots) {
+ this.roots = roots;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.ISaveableFilter#select(org.eclipse.ui.Saveable, org.eclipse.ui.IWorkbenchPart[])
+ */
+ /* public boolean select(Saveable saveable,
+ IWorkbenchPart[] containingParts) {
+ if (isDescendantOfRoots(saveable)) {
+ return true;
+ }
+ // For backwards compatibility, we need to check the parts
+ for (int i = 0; i < containingParts.length; i++) {
+ IWorkbenchPart workbenchPart = containingParts[i];
+ if (workbenchPart instanceof IEditorPart) {
+ IEditorPart editorPart = (IEditorPart) workbenchPart;
+ if (isEditingDescendantOf(editorPart)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ } */
+
+ /**
+ * Return whether the given saveable contains any resources that
+ * are descendants of the root resources.
+ * @param saveable the saveable
+ * @return whether the given saveable contains any resources that
+ * are descendants of the root resources
+ */
+ /*private boolean isDescendantOfRoots(Saveable saveable) {
+ // First, try and adapt the saveable to a resource mapping.
+ ResourceMapping mapping = ResourceUtil.getResourceMapping(saveable);
+ if (mapping != null) {
+ try {
+ ResourceTraversal[] traversals = mapping.getTraversals(
+ ResourceMappingContext.LOCAL_CONTEXT, null);
+ for (int i = 0; i < traversals.length; i++) {
+ ResourceTraversal traversal = traversals[i];
+ IResource[] resources = traversal.getResources();
+ for (int j = 0; j < resources.length; j++) {
+ IResource resource = resources[j];
+ if (isDescendantOfRoots(resource)) {
+ return true;
+ }
+ }
+ }
+ } catch (CoreException e) {
+ IDEWorkbenchPlugin
+ .log(
+ NLS
+ .bind(
+ "An internal error occurred while determining the resources for {0}", saveable.getName()), e); //$NON-NLS-1$
+ }
+ } else {
+ // If there is no mapping, try to adapt to a resource or file directly
+ IFile file = ResourceUtil.getFile(saveable);
+ if (file != null) {
+ return isDescendantOfRoots(file);
+ }
+ }
+ return false;
+ } */
+
+ /**
+ * Return whether the given resource is either equal to or a descendant of
+ * one of the given roots.
+ *
+ * @param resource the resource to be tested
+ * @return whether the given resource is either equal to or a descendant of
+ * one of the given roots
+ */
+ /* private boolean isDescendantOfRoots(IResource resource) {
+ for (int l = 0; l < roots.length; l++) {
+ IResource root = roots[l];
+ if (root.getFullPath().isPrefixOf(resource.getFullPath())) {
+ return true;
+ }
+ }
+ return false;
+ } */
+
+ /**
+ * Return whether the given dirty editor part is editing resources that are
+ * descendants of the given roots.
+ *
+ * @param part the dirty editor part
+ * @return whether the given dirty editor part is editing resources that are
+ * descendants of the given roots
+ */
+ /* private boolean isEditingDescendantOf(IEditorPart part) {
+ IFile file = ResourceUtil.getFile(part.getEditorInput());
+ if (file != null) {
+ return isDescendantOfRoots(file);
+ }
+ return false;
+ }
+
+ } */
+
+ /**
+ * Block instantiation.
+ */
+ private IDE() {
+ // do nothing
+ }
+
+ /**
+ * Returns the marker help registry for the workbench.
+ *
+ * @return the marker help registry
+ */
+ /* public static IMarkerHelpRegistry getMarkerHelpRegistry() {
+ if (markerHelpRegistry == null) {
+ markerHelpRegistry = new MarkerHelpRegistry();
+ new MarkerHelpRegistryReader().addHelp(markerHelpRegistry);
+ }
+ return markerHelpRegistry;
+ } */
+
+ /**
+ * Sets the cursor and selection state for the given editor to reveal the
+ * position of the given marker. This is done on a best effort basis. If the
+ * editor does not provide an <code>IGotoMarker</code> interface (either
+ * directly or via <code>IAdaptable.getAdapter</code>), this has no
+ * effect.
+ *
+ * @param editor
+ * the editor
+ * @param marker
+ * the marker
+ */
+ public static void gotoMarker(IEditorPart editor, IMarker marker) {
+ IGotoMarker gotoMarker = null;
+ if (editor instanceof IGotoMarker) {
+ gotoMarker = (IGotoMarker) editor;
+ } else {
+ gotoMarker = (IGotoMarker) editor.getAdapter(IGotoMarker.class);
+ }
+ if (gotoMarker != null) {
+ gotoMarker.gotoMarker(marker);
+ }
+ }
+
+ /**
+ * Opens an editor on the given object.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @param editorId
+ * the id of the editor extension to use
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page,
+ IEditorInput input, String editorId) throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // open the editor on the file
+ return page.openEditor(input, editorId);
+ }
+
+ /**
+ * Opens an editor on the given IFileStore object.
+ * <p>
+ * Unlike the other <code>openEditor</code> methods, this one can be used
+ * to open files that reside outside the workspace resource set.
+ * </p>
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened.
+ * </p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param uri
+ * the URI of the file store representing the file to open
+ * @param editorId
+ * the id of the editor extension to use
+ * @param activate
+ * if <code>true</code> the editor will be activated opened
+ * @return an open editor or <code>null</code> if an external editor was
+ * @exception PartInitException
+ * if the editor could not be initialized
+ *
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String)
+ * @see EFS#getStore(URI)
+ *
+ * @since 3.3
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, URI uri,
+ String editorId, boolean activate) throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ IFileStore fileStore;
+ try {
+ fileStore = EFS.getStore(uri);
+ } catch (CoreException e) {
+ throw new PartInitException(
+ IDEWorkbenchMessages.IDE_coreExceptionFileStore, e);
+ }
+
+ IEditorInput input = getEditorInput(fileStore);
+
+ // open the editor on the file
+ return page.openEditor(input, editorId, activate);
+ }
+
+ /**
+ * Create the Editor Input appropriate for the given <code>IFileStore</code>.
+ * The result is a normal file editor input if the file exists in the
+ * workspace and, if not, we create a wrapper capable of managing an
+ * 'external' file using its <code>IFileStore</code>.
+ *
+ * @param fileStore
+ * The file store to provide the editor input for
+ * @return The editor input associated with the given file store
+ * @since 3.3
+ */
+ private static IEditorInput getEditorInput(IFileStore fileStore) {
+ IFile workspaceFile = getWorkspaceFile(fileStore);
+ if (workspaceFile != null)
+ return new FileEditorInput(workspaceFile);
+ return new FileStoreEditorInput(fileStore);
+ }
+
+ /**
+ * Determine whether or not the <code>IFileStore</code> represents a file
+ * currently in the workspace.
+ *
+ * @param fileStore
+ * The <code>IFileStore</code> to test
+ * @return The workspace's <code>IFile</code> if it exists or
+ * <code>null</code> if not
+ */
+ private static IFile getWorkspaceFile(IFileStore fileStore) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IFile[] files = root.findFilesForLocationURI(fileStore.toURI());
+ files = filterNonExistentFiles(files);
+ if (files == null || files.length == 0)
+ return null;
+
+ // for now only return the first file
+ return files[0];
+ }
+
+ /**
+ * Filter the incoming array of <code>IFile</code> elements by removing
+ * any that do not currently exist in the workspace.
+ *
+ * @param files
+ * The array of <code>IFile</code> elements
+ * @return The filtered array
+ */
+ private static IFile[] filterNonExistentFiles(IFile[] files) {
+ if (files == null)
+ return null;
+
+ int length = files.length;
+ ArrayList existentFiles = new ArrayList(length);
+ for (int i = 0; i < length; i++) {
+ if (files[i].exists())
+ existentFiles.add(files[i]);
+ }
+ return (IFile[]) existentFiles.toArray(new IFile[existentFiles.size()]);
+ }
+
+ /**
+ * Opens an editor on the given object.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened. If
+ * <code>activate == true</code> the editor will be activated.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @param editorId
+ * the id of the editor extension to use
+ * @param activate
+ * if <code>true</code> the editor will be activated
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String,
+ * boolean)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page,
+ IEditorInput input, String editorId, boolean activate)
+ throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // open the editor on the file
+ return page.openEditor(input, editorId, activate);
+ }
+
+ /**
+ * Opens an editor on the given file resource. This method will attempt to
+ * resolve the editor based on content-type bindings as well as traditional
+ * name/extension bindings.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened. If
+ * <code>activate == true</code> the editor will be activated.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @param activate
+ * if <code>true</code> the editor will be activated
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(org.eclipse.ui.IEditorInput,
+ * String, boolean)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile input,
+ boolean activate) throws PartInitException {
+ return openEditor(page, input, activate, true);
+ }
+
+ /**
+ * Opens an editor on the given file resource. This method will attempt to
+ * resolve the editor based on content-type bindings as well as traditional
+ * name/extension bindings if <code>determineContentType</code> is
+ * <code>true</code>.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened. If
+ * <code>activate == true</code> the editor will be activated.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @param activate
+ * if <code>true</code> the editor will be activated
+ * @param determineContentType
+ * attempt to resolve the content type for this file
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(org.eclipse.ui.IEditorInput,
+ * String, boolean)
+ * @since 3.1
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile input,
+ boolean activate, boolean determineContentType)
+ throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // open the editor on the file
+ IEditorDescriptor editorDesc = getEditorDescriptor(input,
+ determineContentType);
+ return page.openEditor(new FileEditorInput(input), editorDesc.getId(),
+ activate);
+ }
+
+ /**
+ * Opens an editor on the given file resource. This method will attempt to
+ * resolve the editor based on content-type bindings as well as traditional
+ * name/extension bindings.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile input)
+ throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // open the editor on the file
+ IEditorDescriptor editorDesc = getEditorDescriptor(input);
+ return page.openEditor(new FileEditorInput(input), editorDesc.getId());
+ }
+
+ /**
+ * Opens an editor on the given file resource.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @param editorId
+ * the id of the editor extension to use
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile input,
+ String editorId) throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // open the editor on the file
+ return page.openEditor(new FileEditorInput(input), editorId);
+ }
+
+ /**
+ * Opens an editor on the given file resource.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened. If
+ * <code>activate == true</code> the editor will be activated.
+ * <p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param input
+ * the editor input
+ * @param editorId
+ * the id of the editor extension to use
+ * @param activate
+ * if <code>true</code> the editor will be activated
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String,
+ * boolean)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IFile input,
+ String editorId, boolean activate) throws PartInitException {
+ // sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // open the editor on the file
+ return page.openEditor(new FileEditorInput(input), editorId, activate);
+ }
+
+ /**
+ * Returns an editor descriptor appropriate for opening the given file
+ * resource.
+ * <p>
+ * The editor descriptor is determined using a multi-step process. This
+ * method will attempt to resolve the editor based on content-type bindings
+ * as well as traditional name/extension bindings.
+ * </p>
+ * <ol>
+ * <li>The <code>IResource</code> is consulted for a persistent property named
+ * <code>IDE.EDITOR_KEY</code> containing the preferred editor id to be
+ * used.</li>
+ * <li>The workbench editor registry is consulted to determine if an editor
+ * extension has been registered for the file type. If so, an instance of
+ * the editor extension is opened on the file. See
+ * <code>IEditorRegistry.getDefaultEditor(String)</code>.</li>
+ * <li>The operating system is consulted to determine if an in-place
+ * component editor is available (e.g. OLE editor on Win32 platforms).</li>
+ * <li>The operating system is consulted to determine if an external editor
+ * is available.</li>
+ * <li>The workbench editor registry is consulted to determine if the
+ * default text editor is available.</li>
+ * </ol>
+ * </p>
+ *
+ * @param file
+ * the file
+ * @return an editor descriptor, appropriate for opening the file
+ * @throws PartInitException
+ * if no editor can be found
+ */
+ public static IEditorDescriptor getEditorDescriptor(IFile file)
+ throws PartInitException {
+ return getEditorDescriptor(file, true);
+ }
+
+ /**
+ * Returns an editor descriptor appropriate for opening the given file
+ * resource.
+ * <p>
+ * The editor descriptor is determined using a multi-step process. This
+ * method will attempt to resolve the editor based on content-type bindings
+ * as well as traditional name/extension bindings if
+ * <code>determineContentType</code>is <code>true</code>.
+ * </p>
+ * <ol>
+ * <li>The <code>IResource</code> is consulted for a persistent property named
+ * <code>IDE.EDITOR_KEY</code> containing the preferred editor id to be
+ * used.</li>
+ * <li>The workbench editor registry is consulted to determine if an editor
+ * extension has been registered for the file type. If so, an instance of
+ * the editor extension is opened on the file. See
+ * <code>IEditorRegistry.getDefaultEditor(String)</code>.</li>
+ * <li>The operating system is consulted to determine if an in-place
+ * component editor is available (e.g. OLE editor on Win32 platforms).</li>
+ * <li>The operating system is consulted to determine if an external editor
+ * is available.</li>
+ * <li>The workbench editor registry is consulted to determine if the
+ * default text editor is available.</li>
+ * </ol>
+ * </p>
+ *
+ * @param file
+ * the file
+ * @param determineContentType
+ * query the content type system for the content type of the file
+ * @return an editor descriptor, appropriate for opening the file
+ * @throws PartInitException
+ * if no editor can be found
+ * @since 3.1
+ */
+ public static IEditorDescriptor getEditorDescriptor(IFile file,
+ boolean determineContentType) throws PartInitException {
+
+ if (file == null) {
+ throw new IllegalArgumentException();
+ }
+
+ return getEditorDescriptor(file.getName(), PlatformUI.getWorkbench()
+ .getEditorRegistry(), getDefaultEditor(file,
+ determineContentType));
+ }
+
+ /**
+ * Returns an editor id appropriate for opening the given file
+ * store.
+ * <p>
+ * The editor descriptor is determined using a multi-step process. This
+ * method will attempt to resolve the editor based on content-type bindings
+ * as well as traditional name/extension bindings.
+ * </p>
+ * <ol>
+ * <li>The workbench editor registry is consulted to determine if an editor
+ * extension has been registered for the file type. If so, an instance of
+ * the editor extension is opened on the file. See
+ * <code>IEditorRegistry.getDefaultEditor(String)</code>.</li>
+ * <li>The operating system is consulted to determine if an in-place
+ * component editor is available (e.g. OLE editor on Win32 platforms).</li>
+ * <li>The operating system is consulted to determine if an external editor
+ * is available.</li>
+ * <li>The workbench editor registry is consulted to determine if the
+ * default text editor is available.</li>
+ * </ol>
+ * </p>
+ *
+ * @param fileStore
+ * the file store
+ * @return the id of an editor, appropriate for opening the file
+ * @throws PartInitException
+ * if no editor can be found
+ */
+ private static String getEditorId(IFileStore fileStore) throws PartInitException {
+ String name = fileStore.fetchInfo().getName();
+ if (name == null) {
+ throw new IllegalArgumentException();
+ }
+
+ IContentType contentType= null;
+ try {
+ InputStream is = null;
+ try {
+ is = fileStore.openInputStream(EFS.NONE, null);
+ contentType= Platform.getContentTypeManager().findContentTypeFor(is, name);
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ } catch (CoreException ex) {
+ // continue without content type
+ } catch (IOException ex) {
+ // continue without content type
+ }
+
+ IEditorRegistry editorReg= PlatformUI.getWorkbench().getEditorRegistry();
+
+ return getEditorDescriptor(name, editorReg, editorReg.getDefaultEditor(name, contentType)).getId();
+ }
+
+ /**
+ * Returns an editor descriptor appropriate for opening a file resource with
+ * the given name.
+ * <p>
+ * The editor descriptor is determined using a multi-step process. This
+ * method will attempt to infer content type from the file name.
+ * </p>
+ * <ol>
+ * <li>The workbench editor registry is consulted to determine if an editor
+ * extension has been registered for the file type. If so, an instance of
+ * the editor extension is opened on the file. See
+ * <code>IEditorRegistry.getDefaultEditor(String)</code>.</li>
+ * <li>The operating system is consulted to determine if an in-place
+ * component editor is available (e.g. OLE editor on Win32 platforms).</li>
+ * <li>The operating system is consulted to determine if an external editor
+ * is available.</li>
+ * <li>The workbench editor registry is consulted to determine if the
+ * default text editor is available.</li>
+ * </ol>
+ * </p>
+ *
+ * @param name
+ * the file name
+ * @return an editor descriptor, appropriate for opening the file
+ * @throws PartInitException
+ * if no editor can be found
+ * @since 3.1
+ */
+ public static IEditorDescriptor getEditorDescriptor(String name)
+ throws PartInitException {
+ return getEditorDescriptor(name, true);
+ }
+
+ /**
+ * Returns an editor descriptor appropriate for opening a file resource with
+ * the given name.
+ * <p>
+ * The editor descriptor is determined using a multi-step process. This
+ * method will attempt to infer the content type of the file if
+ * <code>inferContentType</code> is <code>true</code>.
+ * </p>
+ * <ol>
+ * <li>The workbench editor registry is consulted to determine if an editor
+ * extension has been registered for the file type. If so, an instance of
+ * the editor extension is opened on the file. See
+ * <code>IEditorRegistry.getDefaultEditor(String)</code>.</li>
+ * <li>The operating system is consulted to determine if an in-place
+ * component editor is available (e.g. OLE editor on Win32 platforms).</li>
+ * <li>The operating system is consulted to determine if an external editor
+ * is available.</li>
+ * <li>The workbench editor registry is consulted to determine if the
+ * default text editor is available.</li>
+ * </ol>
+ * </p>
+ *
+ * @param name
+ * the file name
+ * @param inferContentType
+ * attempt to infer the content type from the file name if this
+ * is <code>true</code>
+ * @return an editor descriptor, appropriate for opening the file
+ * @throws PartInitException
+ * if no editor can be found
+ * @since 3.1
+ */
+ public static IEditorDescriptor getEditorDescriptor(String name,
+ boolean inferContentType) throws PartInitException {
+
+ if (name == null) {
+ throw new IllegalArgumentException();
+ }
+
+ IContentType contentType = inferContentType ? Platform
+ .getContentTypeManager().findContentTypeFor(name) : null;
+ IEditorRegistry editorReg = PlatformUI.getWorkbench()
+ .getEditorRegistry();
+
+ return getEditorDescriptor(name, editorReg, editorReg.getDefaultEditor(
+ name, contentType));
+ }
+
+ /**
+ * Get the editor descriptor for a given name using the editorDescriptor
+ * passed in as a default as a starting point.
+ *
+ * @param name
+ * The name of the element to open.
+ * @param editorReg
+ * The editor registry to do the lookups from.
+ * @param defaultDescriptor
+ * IEditorDescriptor or <code>null</code>
+ * @return IEditorDescriptor
+ * @throws PartInitException
+ * if no valid editor can be found
+ *
+ * @since 3.1
+ */
+ private static IEditorDescriptor getEditorDescriptor(String name,
+ IEditorRegistry editorReg, IEditorDescriptor defaultDescriptor)
+ throws PartInitException {
+
+ if (defaultDescriptor != null) {
+ return defaultDescriptor;
+ }
+
+ IEditorDescriptor editorDesc = defaultDescriptor;
+
+ // next check the OS for in-place editor (OLE on Win32)
+ if (editorReg.isSystemInPlaceEditorAvailable(name)) {
+ editorDesc = editorReg
+ .findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID);
+ }
+
+ // next check with the OS for an external editor
+ if (editorDesc == null
+ && editorReg.isSystemExternalEditorAvailable(name)) {
+ editorDesc = editorReg
+ .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
+ }
+
+ // next lookup the default text editor
+ if (editorDesc == null) {
+ editorDesc = editorReg
+ .findEditor(IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID);
+ }
+
+ // if no valid editor found, bail out
+ if (editorDesc == null) {
+ throw new PartInitException(
+ IDEWorkbenchMessages.IDE_noFileEditorFound);
+ }
+
+ return editorDesc;
+ }
+
+ /**
+ * Opens an editor on the file resource of the given marker.
+ * <p>
+ * If this page already has an editor open on the marker resource file that
+ * editor is brought to front; otherwise, a new editor is opened.The cursor
+ * and selection state of the editor are then updated from information
+ * recorded in the marker.
+ * </p>
+ * <p>
+ * If the marker contains an <code>EDITOR_ID_ATTR</code> attribute the
+ * attribute value will be used to determine the editor type to be opened.
+ * If not, the registered editor for the marker resource file will be used.
+ * </p>
+ *
+ * @param page
+ * the workbench page to open the editor in
+ * @param marker
+ * the marker to open
+ * @return an open editor or <code>null</code> not possible
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see #openEditor(org.eclipse.ui.IWorkbenchPage,
+ * org.eclipse.core.resources.IMarker, boolean)
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IMarker marker)
+ throws PartInitException {
+ return openEditor(page, marker, true);
+ }
+
+ /**
+ * Opens an editor on the file resource of the given marker.
+ * <p>
+ * If this page already has an editor open on the marker resource file that
+ * editor is brought to front; otherwise, a new editor is opened. If
+ * <code>activate == true</code> the editor will be activated. The cursor
+ * and selection state of the editor are then updated from information
+ * recorded in the marker.
+ * </p>
+ * <p>
+ * If the marker contains an <code>EDITOR_ID_ATTR</code> attribute the
+ * attribute value will be used to determine the editor type to be opened.
+ * If not, the registered editor for the marker resource file will be used.
+ * </p>
+ *
+ * @param page
+ * the workbench page to open the editor in
+ * @param marker
+ * the marker to open
+ * @param activate
+ * if <code>true</code> the editor will be activated
+ * @return an open editor or <code>null</code> not possible
+ * @exception PartInitException
+ * if the editor could not be initialized
+ */
+ public static IEditorPart openEditor(IWorkbenchPage page, IMarker marker,
+ boolean activate) throws PartInitException {
+ // sanity checks
+ if (page == null || marker == null) {
+ throw new IllegalArgumentException();
+ }
+
+ // get the marker resource file
+ if (!(marker.getResource() instanceof IFile)) {
+ IDEWorkbenchPlugin
+ .log("Open editor on marker failed; marker resource not an IFile"); //$NON-NLS-1$
+ return null;
+ }
+ IFile file = (IFile) marker.getResource();
+
+ // get the preferred editor id from the marker
+ IEditorRegistry editorReg = PlatformUI.getWorkbench()
+ .getEditorRegistry();
+ IEditorDescriptor editorDesc = null;
+ try {
+ String editorID = (String) marker.getAttribute(EDITOR_ID_ATTR);
+ if (editorID != null) {
+ editorDesc = editorReg.findEditor(editorID);
+ }
+ } catch (CoreException e) {
+ // ignore this
+ }
+
+ // open the editor on the marker resource file
+ IEditorPart editor = null;
+ if (editorDesc == null) {
+ editor = openEditor(page, file, activate);
+ } else {
+ editor = page.openEditor(new FileEditorInput(file), editorDesc
+ .getId(), activate, IWorkbenchPage.MATCH_ID | IWorkbenchPage.MATCH_INPUT);
+ }
+
+ // get the editor to update its position based on the marker
+ if (editor != null) {
+ gotoMarker(editor, marker);
+ }
+
+ return editor;
+ }
+
+ /**
+ * Opens an editor on the given IFileStore object.
+ * <p>
+ * Unlike the other <code>openEditor</code> methods, this one
+ * can be used to open files that reside outside the workspace
+ * resource set.
+ * </p>
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened.
+ * </p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param fileStore
+ * the IFileStore representing the file to open
+ * @return an open editor or <code>null</code> if an external editor was opened
+ * @exception PartInitException
+ * if the editor could not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String)
+ * @since 3.3
+ */
+ public static IEditorPart openEditorOnFileStore(IWorkbenchPage page, IFileStore fileStore) throws PartInitException {
+ //sanity checks
+ if (page == null) {
+ throw new IllegalArgumentException();
+ }
+
+ IEditorInput input = getEditorInput(fileStore);
+ String editorId = getEditorId(fileStore);
+
+ // open the editor on the file
+ return page.openEditor(input, editorId);
+ }
+
+ /**
+ * Opens an internal editor on the given IFileStore object.
+ * <p>
+ * Unlike the other <code>openEditor</code> methods, this one can be used to
+ * open files that reside outside the workspace resource set.
+ * </p>
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened.
+ * </p>
+ *
+ * @param page
+ * the page in which the editor will be opened
+ * @param fileStore
+ * the IFileStore representing the file to open
+ * @return an open editor or <code>null</code> if an external editor was
+ * opened
+ * @exception PartInitException
+ * if no internal editor can be found or if the editor could
+ * not be initialized
+ * @see org.eclipse.ui.IWorkbenchPage#openEditor(IEditorInput, String)
+ * @since 3.6
+ */
+ public static IEditorPart openInternalEditorOnFileStore(IWorkbenchPage page, IFileStore fileStore) throws PartInitException {
+ if (page == null)
+ throw new IllegalArgumentException();
+ if (fileStore == null)
+ throw new IllegalArgumentException();
+
+ IEditorInput input = getEditorInput(fileStore);
+ String name = fileStore.fetchInfo().getName();
+ if (name == null)
+ throw new IllegalArgumentException();
+
+ IContentType[] contentTypes = null;
+ InputStream is = null;
+ try {
+ is = fileStore.openInputStream(EFS.NONE, null);
+ contentTypes = Platform.getContentTypeManager().findContentTypesFor(is, name);
+ } catch (CoreException ex) {
+ // it's OK, ignore
+ } catch (IOException ex) {
+ // it's OK, ignore
+ } finally {
+ if (is != null) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ // nothing good can be done here, ignore
+ }
+ }
+ }
+
+ IEditorRegistry editorReg = PlatformUI.getWorkbench().getEditorRegistry();
+ if (contentTypes != null) {
+ for(int i = 0 ; i < contentTypes.length; i++) {
+ IEditorDescriptor editorDesc = editorReg.getDefaultEditor(name, contentTypes[i]);
+ if ((editorDesc != null) && (editorDesc.isInternal()))
+ return page.openEditor(input, editorDesc.getId());
+ }
+ }
+
+ // no content types are available, use file name associations
+ IEditorDescriptor[] editors = editorReg.getEditors(name);
+ if (editors != null) {
+ for(int i = 0 ; i < editors.length; i++) {
+ if ((editors[i] != null) && (editors[i].isInternal()))
+ return page.openEditor(input, editors[i].getId());
+ }
+ }
+
+ // fallback to the default text editor
+ IEditorDescriptor textEditor = editorReg.findEditor(IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID);
+ if (textEditor == null)
+ throw new PartInitException(IDEWorkbenchMessages.IDE_noFileEditorFound);
+ return page.openEditor(input, textEditor.getId());
+ }
+
+ /**
+ * Save all dirty editors in the workbench whose editor input is a child
+ * resource of one of the <code>IResource</code>'s provided. Opens a
+ * dialog to prompt the user if <code>confirm</code> is true. Return true
+ * if successful. Return false if the user has canceled the command.
+ *
+ * @since 3.0
+ *
+ * @param resourceRoots the resource roots under which editor input should
+ * be saved, other will be left dirty
+ * @param confirm <code>true</code> to ask the user before saving unsaved
+ * changes (recommended), and <code>false</code> to save
+ * unsaved changes without asking
+ * @return <code>true</code> if the command succeeded, and
+ * <code>false</code> if the operation was canceled by the user or
+ * an error occurred while saving
+ */
+ public static boolean saveAllEditors(final IResource[] resourceRoots,
+ final boolean confirm) {
+
+ if (resourceRoots.length == 0) {
+ return true;
+ }
+
+ final boolean[] result = new boolean[] { true };
+ SafeRunner.run(new SafeRunnable(IDEWorkbenchMessages.ErrorOnSaveAll) {
+ public void run() {
+ IWorkbenchWindow w = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ if (w == null) {
+ IWorkbenchWindow[] windows = PlatformUI.getWorkbench()
+ .getWorkbenchWindows();
+ if (windows.length > 0)
+ w = windows[0];
+ }
+ if (w != null) {
+ result[0] = PlatformUI.getWorkbench().saveAll(w, w,
+ new SaveFilter(resourceRoots), confirm);
+ }
+ }
+ });
+ return result[0];
+ }
+
+ /**
+ * Sets the default editor id for a given file. This value will be used to
+ * determine the default editor descriptor for the file in future calls to
+ * <code>getDefaultEditor(IFile)</code>.
+ *
+ * @param file
+ * the file
+ * @param editorID
+ * the editor id
+ */
+ public static void setDefaultEditor(IFile file, String editorID) {
+ try {
+ file.setPersistentProperty(EDITOR_KEY, editorID);
+ } catch (CoreException e) {
+ // do nothing
+ }
+ }
+
+ /**
+ * Returns the default editor for a given file. This method will attempt to
+ * resolve the editor based on content-type bindings as well as traditional
+ * name/extension bindings.
+ * <p>
+ * A default editor id may be registered for a specific file using
+ * <code>setDefaultEditor</code>. If the given file has a registered
+ * default editor id the default editor will derived from it. If not, the
+ * default editor is determined by taking the file name for the file and
+ * obtaining the default editor for that name.
+ * </p>
+ *
+ * @param file
+ * the file
+ * @return the descriptor of the default editor, or <code>null</code> if
+ * not found
+ */
+ public static IEditorDescriptor getDefaultEditor(IFile file) {
+ return getDefaultEditor(file, true);
+ }
+
+ /**
+ * Returns the default editor for a given file. This method will attempt to
+ * resolve the editor based on content-type bindings as well as traditional
+ * name/extension bindings if <code>determineContentType</code> is
+ * <code>true</code>.
+ * <p>
+ * A default editor id may be registered for a specific file using
+ * <code>setDefaultEditor</code>. If the given file has a registered
+ * default editor id the default editor will derived from it. If not, the
+ * default editor is determined by taking the file name for the file and
+ * obtaining the default editor for that name.
+ * </p>
+ *
+ * @param file
+ * the file
+ * @param determineContentType
+ * determine the content type for the given file
+ * @return the descriptor of the default editor, or <code>null</code> if
+ * not found
+ * @since 3.1
+ */
+ public static IEditorDescriptor getDefaultEditor(IFile file,
+ boolean determineContentType) {
+ // Try file specific editor.
+ IEditorRegistry editorReg = PlatformUI.getWorkbench()
+ .getEditorRegistry();
+ try {
+ String editorID = file.getPersistentProperty(EDITOR_KEY);
+ if (editorID != null) {
+ IEditorDescriptor desc = editorReg.findEditor(editorID);
+ if (desc != null) {
+ return desc;
+ }
+ }
+ } catch (CoreException e) {
+ // do nothing
+ }
+
+ IContentType contentType = null;
+ if (determineContentType) {
+ contentType = getContentType(file);
+ }
+ // Try lookup with filename
+ return editorReg.getDefaultEditor(file.getName(), contentType);
+ }
+
+ /**
+ * Extracts and returns the <code>IResource</code>s in the given
+ * selection or the resource objects they adapts to.
+ *
+ * @param originalSelection
+ * the original selection, possibly empty
+ * @return list of resources (element type: <code>IResource</code>),
+ * possibly empty
+ */
+ public static List computeSelectedResources(
+ IStructuredSelection originalSelection) {
+ List resources = null;
+ for (Iterator e = originalSelection.iterator(); e.hasNext();) {
+ Object next = e.next();
+ Object resource = null;
+ if (next instanceof IResource) {
+ resource = next;
+ } else if (next instanceof IAdaptable) {
+ resource = ((IAdaptable) next).getAdapter(IResource.class);
+ }
+ if (resource != null) {
+ if (resources == null) {
+ // lazy init to avoid creating empty lists
+ // assume selection contains mostly resources most times
+ resources = new ArrayList(originalSelection.size());
+ }
+ resources.add(resource);
+ }
+ }
+ if (resources == null) {
+ return Collections.EMPTY_LIST;
+ }
+ return resources;
+
+ }
+
+ /**
+ * Return the content type for the given file.
+ *
+ * @param file
+ * the file to test
+ * @return the content type, or <code>null</code> if it cannot be
+ * determined.
+ * @since 3.1
+ */
+ public static IContentType getContentType(IFile file) {
+ try {
+ UIStats.start(UIStats.CONTENT_TYPE_LOOKUP, file.getName());
+ IContentDescription contentDescription = file
+ .getContentDescription();
+ if (contentDescription == null) {
+ return null;
+ }
+ return contentDescription.getContentType();
+ } catch (CoreException e) {
+ if (e.getStatus().getCode() == IResourceStatus.OUT_OF_SYNC_LOCAL) {
+ // Determine the content type from the file name.
+ return Platform.getContentTypeManager()
+ .findContentTypeFor(file.getName());
+ }
+ return null;
+ } finally {
+ UIStats.end(UIStats.CONTENT_TYPE_LOOKUP, file, file.getName());
+ }
+ }
+
+ /**
+ * Guess at the content type of the given file based on the filename.
+ *
+ * @param file
+ * the file to test
+ * @return the content type, or <code>null</code> if it cannot be
+ * determined.
+ * @since 3.2
+ */
+ public static IContentType guessContentType(IFile file) {
+ String fileName = file.getName();
+ try {
+ UIStats.start(UIStats.CONTENT_TYPE_LOOKUP, fileName);
+ IContentTypeMatcher matcher = file.getProject()
+ .getContentTypeMatcher();
+ return matcher.findContentTypeFor(fileName);
+ } catch (CoreException e) {
+ return null;
+ } finally {
+ UIStats.end(UIStats.CONTENT_TYPE_LOOKUP, file, fileName);
+ }
+ }
+
+ /**
+ * Prompt the user to inform them of the possible side effects of an
+ * operation on resources. Do not prompt for side effects from ignored model
+ * providers. A model provider can be ignored if it is the client calling
+ * this API. Any message from the provided model provider id or any model
+ * providers it extends will be ignored.
+ *
+ * @param shell
+ * the shell to parent the prompt dialog
+ * @param title
+ * the title of the dialog
+ * @param message
+ * the message for the dialog
+ * @param delta
+ * a delta built using an
+ * {@link IResourceChangeDescriptionFactory}
+ * @param ignoreModelProviderIds
+ * model providers to be ignored
+ * @param syncExec
+ * prompt in a sync exec (required when called from a non-UI
+ * thread)
+ * @return whether the user chose to continue
+ * @since 3.2
+ */
+ public static boolean promptToConfirm(final Shell shell,
+ final String title, String message, IResourceDelta delta,
+ String[] ignoreModelProviderIds, boolean syncExec) {
+ IStatus status = ResourceChangeValidator.getValidator().validateChange(
+ delta, null);
+ if (status.isOK()) {
+ return true;
+ }
+ final IStatus displayStatus;
+ if (status.isMultiStatus()) {
+ List result = new ArrayList();
+ IStatus[] children = status.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ IStatus child = children[i];
+ if (!isIgnoredStatus(child, ignoreModelProviderIds)) {
+ result.add(child);
+ }
+ }
+ if (result.isEmpty()) {
+ return true;
+ }
+ if (result.size() == 1) {
+ displayStatus = (IStatus) result.get(0);
+ } else {
+ displayStatus = new MultiStatus(status.getPlugin(), status
+ .getCode(), (IStatus[]) result
+ .toArray(new IStatus[result.size()]), status
+ .getMessage(), status.getException());
+ }
+ } else {
+ if (isIgnoredStatus(status, ignoreModelProviderIds)) {
+ return true;
+ }
+ displayStatus = status;
+ }
+
+ if (message == null) {
+ message = IDEWorkbenchMessages.IDE_sideEffectWarning;
+ }
+ final String dialogMessage = NLS.bind(
+ IDEWorkbenchMessages.IDE_areYouSure, message);
+
+ final boolean[] result = new boolean[] { false };
+ Runnable runnable = new Runnable() {
+ public void run() {
+ ErrorDialog dialog = new ErrorDialog(shell, title,
+ dialogMessage, displayStatus, IStatus.ERROR
+ | IStatus.WARNING | IStatus.INFO) {
+ protected void createButtonsForButtonBar(Composite parent) {
+ createButton(parent, IDialogConstants.YES_ID,
+ IDialogConstants.YES_LABEL, false);
+ createButton(parent, IDialogConstants.NO_ID,
+ IDialogConstants.NO_LABEL, true);
+ createDetailsButton(parent);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.dialogs.ErrorDialog#buttonPressed(int)
+ */
+ protected void buttonPressed(int id) {
+ if (id == IDialogConstants.YES_ID) {
+ super.buttonPressed(IDialogConstants.OK_ID);
+ } else if (id == IDialogConstants.NO_ID) {
+ super.buttonPressed(IDialogConstants.CANCEL_ID);
+ }
+ super.buttonPressed(id);
+ }
+ protected int getShellStyle() {
+ return super.getShellStyle() | SWT.SHEET;
+ }
+ };
+ int code = dialog.open();
+ result[0] = code == 0;
+ }
+ };
+ if (syncExec) {
+ shell.getDisplay().syncExec(runnable);
+ } else {
+ runnable.run();
+ }
+ return result[0];
+ }
+
+ /**
+ * Register workbench adapters programmatically. This is necessary to enable
+ * certain types of content in the explorers.
+ * <p>
+ * <b>Note:</b> this method should only be called once, in your
+ * application's WorkbenchAdvisor#initialize(IWorkbenchConfigurer) method.
+ * </p>
+ *
+ * @since 3.5
+ */
+ public static void registerAdapters() {
+ IAdapterManager manager = Platform.getAdapterManager();
+ IAdapterFactory factory = new WorkbenchAdapterFactory();
+ manager.registerAdapters(factory, IWorkspace.class);
+ manager.registerAdapters(factory, IWorkspaceRoot.class);
+ manager.registerAdapters(factory, IProject.class);
+ manager.registerAdapters(factory, IFolder.class);
+ manager.registerAdapters(factory, IFile.class);
+ manager.registerAdapters(factory, IMarker.class);
+
+ // properties adapters
+ IAdapterFactory paFactory = new StandardPropertiesAdapterFactory();
+ manager.registerAdapters(paFactory, IWorkspace.class);
+ manager.registerAdapters(paFactory, IWorkspaceRoot.class);
+ manager.registerAdapters(paFactory, IProject.class);
+ manager.registerAdapters(paFactory, IFolder.class);
+ manager.registerAdapters(paFactory, IFile.class);
+ manager.registerAdapters(paFactory, IMarker.class);
+ }
+
+ private static boolean isIgnoredStatus(IStatus status,
+ String[] ignoreModelProviderIds) {
+ if (ignoreModelProviderIds == null) {
+ return false;
+ }
+ if (status instanceof ModelStatus) {
+ ModelStatus ms = (ModelStatus) status;
+ for (int i = 0; i < ignoreModelProviderIds.length; i++) {
+ String id = ignoreModelProviderIds[i];
+ if (ms.getModelProviderId().equals(id)) {
+ return true;
+ }
+ IModelProviderDescriptor desc = ModelProvider
+ .getModelProviderDescriptor(id);
+ String[] extended = desc.getExtendedModels();
+ if (isIgnoredStatus(status, extended)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Opens editors on given file resources.
+ * <p>
+ * If the page already has an editor open on the target object then that
+ * editor is brought to front; otherwise, a new editor is opened. The editor created
+ * for the first input will be activated.
+ * </p>
+ * @param page the page in which the editor will be opened
+ * @param inputs the inputs for the editors
+ * @return references to the editors opened; the corresponding editors might not be materialized
+ * @exception MultiPartInitException if at least one of the editors could not be initialized
+ * @since 3.5
+ */
+ public static IEditorReference[] openEditors(IWorkbenchPage page, IFile[] inputs) throws MultiPartInitException {
+ if ((page == null) || (inputs == null))
+ throw new IllegalArgumentException();
+
+ String[] editorDescriptions = new String[inputs.length];
+ IEditorInput[] editorInputs = new IEditorInput[inputs.length];
+ for(int i = 0 ; i < inputs.length; i++) {
+ editorInputs[i] = new FileEditorInput(inputs[i]);
+ try {
+ editorDescriptions[i] = getEditorDescriptor(inputs[i]).getId();
+ } catch (PartInitException e) {
+ PartInitException[] exceptions = new PartInitException[inputs.length];
+ exceptions[i] = e;
+ throw new MultiPartInitException(new IWorkbenchPartReference[inputs.length], exceptions);
+ }
+ }
+ return page.openEditors(editorInputs, editorDescriptions, IWorkbenchPage.MATCH_INPUT);
+ }
+
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IDEActionFactory.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IDEActionFactory.java
new file mode 100644
index 00000000..ce897294
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IDEActionFactory.java
@@ -0,0 +1,36 @@
+package org.eclipse.ui.ide;
+
+import org.eclipse.ui.IWorkbenchCommandConstants;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.actions.ActionFactory;
+import org.eclipse.ui.actions.RetargetAction;
+import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
+
+/**
+ * IDEActionFactory, only copied parts which are needed in babel editor, to get it working in RAP
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class IDEActionFactory {
+
+ /**
+ * IDE-specific workbench action (id: "bookmark", commandId: "org.eclipse.ui.edit.addBookmark"): Add bookmark.
+ * This action is a {@link RetargetAction}. This action maintains its enablement state.
+ */
+ public static final ActionFactory BOOKMARK = new ActionFactory("bookmark", //$NON-NLS-1$
+ IWorkbenchCommandConstants.EDIT_ADD_BOOKMARK) {
+ /* (non-javadoc) method declared on ActionFactory */
+ public IWorkbenchAction create(IWorkbenchWindow window) {
+ if (window == null) {
+ throw new IllegalArgumentException();
+ }
+ RetargetAction action = new RetargetAction(getId(), IDEWorkbenchMessages.Workbench_addBookmark);
+ action.setToolTipText(IDEWorkbenchMessages.Workbench_addBookmarkToolTip);
+ window.getPartService().addPartListener(action);
+ action.setActionDefinitionId(getCommandId());
+ return action;
+ }
+ };
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IGotoMarker.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IGotoMarker.java
new file mode 100644
index 00000000..5b343107
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/ide/IGotoMarker.java
@@ -0,0 +1,29 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui.ide;
+
+import org.eclipse.core.resources.IMarker;
+
+/**
+ * An adapter interface for editors, which allows the editor
+ * to reveal the position of a given marker.
+ *
+ * @since 3.0
+ */
+public interface IGotoMarker {
+ /**
+ * Sets the cursor and selection state for an editor to
+ * reveal the position of the given marker.
+ *
+ * @param marker the marker
+ */
+ public void gotoMarker(IMarker marker);
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/internal/ide/IDEWorkbenchMessages.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/internal/ide/IDEWorkbenchMessages.java
new file mode 100644
index 00000000..e3ff4dba
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/internal/ide/IDEWorkbenchMessages.java
@@ -0,0 +1,990 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2011 IBM Corporation 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:
+ * IBM - Initial API and implementation
+ * Benjamin Muskalla - bug 29633
+ * Oakland Software Incorporated (Francis Upton) <[email protected]>
+ * - Bug 224997 [Workbench] Impossible to copy project
+ * Dina Sayed, [email protected], IBM - bug 269844
+ * Serge Beauchamp (Freescale Semiconductor) - [252996] Resource filters
+ * Markus Schorn (Wind River Systems) - bug 284447
+ * James Blackburn (Broadcom Corp.) - bug 340978
+ *******************************************************************************/
+package org.eclipse.ui.internal.ide;
+
+import org.eclipse.osgi.util.NLS;
+
+public class IDEWorkbenchMessages extends NLS {
+ private static final String BUNDLE_NAME = "org.eclipse.ui.internal.ide.messages";//$NON-NLS-1$
+ // package: org.eclipse.ui.ide
+
+ public static String IDEWorkbenchAdvisor_noPerspective;
+ public static String IDEWorkbenchAdvisor_cancelHistoryPruning;
+ public static String IDEWorkbenchAdvisor_preHistoryCompaction;
+ public static String IDEWorkbenchAdvisor_postHistoryCompaction;
+
+ public static String IDE_noFileEditorFound;
+ public static String IDE_coreExceptionFileStore;
+
+ public static String OpenWithMenu_Other;
+ public static String OpenWithMenu_OtherDialogDescription;
+
+ public static String QuickStartAction_errorDialogTitle;
+ public static String QuickStartAction_infoReadError;
+
+ public static String ConfigurationLogUpdateSection_installConfiguration;
+ public static String ConfigurationLogUpdateSection_lastChangedOn;
+ public static String ConfigurationLogUpdateSection_location;
+ public static String ConfigurationLogUpdateSection_IU;
+ public static String ConfigurationLogUpdateSection_IUHeader;
+ public static String ConfigurationLogUpdateSection_bundle;
+ public static String ConfigurationLogUpdateSection_bundleHeader;
+ public static String ConfigurationLogUpdateSection_timestamp;
+
+ public static String ErrorClosing;
+ public static String ErrorOnSaveAll;
+
+ public static String ResourceInfoPage_noResource;
+
+ public static String ResourceFilterPage_title;
+ public static String ResourceFilterPage_noResource;
+ public static String ResourceFilterPage_addButtonLabel;
+ public static String ResourceFilterPage_addGroupButtonLabel;
+ public static String ResourceFilterPage_editButtonLabel;
+ public static String ResourceFilterPage_removeButtonLabel;
+ public static String ResourceFilterPage_columnFilterMode;
+ public static String ResourceFilterPage_columnFilterDescription;
+ public static String ResourceFilterPage_columnFilterTarget;
+ public static String ResourceFilterPage_columnFilterPattern;
+ public static String ResourceFilterPage_applyRecursivelyToFolderStructure;
+ public static String ResourceFilterPage_recursive;
+ public static String ResourceFilterPage_details;
+ public static String ResourceFilterPage_caseSensitive;
+ public static String ResourceFilterPage_regularExpression;
+ public static String ResourceFilterPage_multiMatcher_Matcher;
+ public static String ResourceFilterPage_multiMatcher_FileLength;
+ public static String ResourceFilterPage_multiMatcher_TimeInterval;
+ public static String ResourceFilterPage_multiMatcher_InvalidFileLength;
+ public static String ResourceFilterPage_multiMatcher_InvalidTimeInterval;
+ public static String ResourceFilterPage_includeOnly;
+ public static String ResourceFilterPage_excludeAll;
+ public static String ResourceFilterPage_includeOnlyColumn;
+ public static String ResourceFilterPage_excludeAllColumn;
+ public static String ResourceFilterPage_filesAndFolders;
+ public static String ResourceFilterPage_files;
+ public static String ResourceFilterPage_folders;
+ public static String ResourceFilterPage_editFilterDialogTitle;
+ public static String ResourceFilterPage_newFilterDialogTitleFolder;
+ public static String ResourceFilterPage_newFilterDialogTitleProject;
+ public static String ResourceFilterPage_addSubFilterActionLabel;
+ public static String ResourceFilterPage_addSubFilterGroupActionLabel;
+ public static String ResourceFilterPage_removeFilterActionLabel;
+ public static String ResourceFilterPage_editFilterActionLabel;
+ public static String ResourceFilterPage_multiKeyName;
+ public static String ResourceFilterPage_multiKeyProjectRelativePath;
+ public static String ResourceFilterPage_multiKeyLocation;
+ public static String ResourceFilterPage_multiKeyLastModified;
+ public static String ResourceFilterPage_multiKeyCreated;
+ public static String ResourceFilterPage_multiKeyLength;
+ public static String ResourceFilterPage_multiKeyReadOnly;
+ public static String ResourceFilterPage_multiKeySymLink;
+ public static String ResourceFilterPage_multiEquals;
+ public static String ResourceFilterPage_multiMatches;
+ public static String ResourceFilterPage_multiLargerThan;
+ public static String ResourceFilterPage_multiSmallerThan;
+ public static String ResourceFilterPage_multiBefore;
+ public static String ResourceFilterPage_multiAfter;
+ public static String ResourceFilterPage_multiWithin;
+ public static String ResourceFilterPage_true;
+ public static String ResourceFilterPage_false;
+
+ //
+ //
+ // Copies from org.eclipse.ui.workbench
+ //
+ public static String showAdvanced;
+ public static String hideAdvanced;
+ public static String editfilters;
+ public static String useDefaultLocation;
+ public static String createLinkedFolder;
+ public static String createVirtualFolder;
+
+ // ==============================================================================
+ // Workbench Actions
+ // ==============================================================================
+
+ // --- File Menu ---
+ public static String Workbench_file;
+ public static String Workbench_new;
+ public static String OpenWorkspaceAction_text;
+ public static String OpenWorkspaceAction_toolTip;
+ public static String OpenWorkspaceAction_errorTitle;
+ public static String OpenWorkspaceAction_errorMessage;
+ public static String OpenWorkspaceAction_other;
+ public static String NewProjectAction_text;
+ public static String NewProjectAction_toolTip;
+ public static String NewExampleAction_text;
+ public static String NewExampleAction_toolTip;
+ public static String SaveAsDialog_title;
+ public static String SaveAsDialog_message;
+ public static String SaveAsDialog_text;
+ public static String SaveAsDialog_fileLabel;
+ public static String SaveAsDialog_file;
+ public static String SaveAsDialog_overwriteQuestion;
+ public static String SaveAsDialog_closedProjectMessage;
+ public static String Workbench_projectProperties;
+ public static String Workbench_projectPropertiesToolTip;
+
+
+ // --- Edit Menu ---
+ public static String Workbench_edit;
+ public static String Workbench_addBookmark;
+ public static String Workbench_addBookmarkToolTip;
+ public static String Workbench_addTask;
+ public static String Workbench_addTaskToolTip;
+
+
+ // --- Navigate Menu ---
+ public static String Workbench_navigate;
+ public static String Workbench_goTo;
+
+ public static String Workbench_showIn;
+
+ // --- Project Menu ---
+ public static String Workbench_project;
+
+ public static String Workbench_buildProject;
+ public static String Workbench_buildProjectToolTip;
+ public static String Workbench_rebuildProject;
+ public static String Workbench_rebuildProjectToolTip;
+ public static String Workbench_buildClean;
+ public static String Workbench_buildSet;
+ public static String Workbench_buildAutomatically;
+
+ public static String GlobalBuildAction_text;
+ public static String GlobalBuildAction_toolTip;
+ public static String GlobalBuildAction_rebuildText;
+ public static String GlobalBuildAction_rebuildToolTip;
+ public static String GlobalBuildAction_buildProblems;
+ public static String GlobalBuildAction_internalError;
+ public static String GlobalBuildAction_buildOperationTitle;
+ public static String GlobalBuildAction_rebuildAllOperationTitle;
+ public static String GlobalBuildAction_jobTitle;
+
+ public static String BuildSetAction_noBuildTitle;
+ public static String BuildSetAction_noProjects;
+
+
+ // --- Window Menu ---
+ public static String Workbench_window;
+ public static String Workbench_openPerspective;
+ public static String Workbench_showView;
+
+ public static String PromptOnExitDialog_shellTitle;
+ public static String PromptOnExitDialog_message0;
+ public static String PromptOnExitDialog_message1;
+ public static String PromptOnExitDialog_choice;
+
+ public static String Workbench_shortcuts;
+ public static String Workbench_openNewWindow;
+
+
+ // --- Help Menu ---
+ public static String Workbench_help;
+ public static String QuickStart_text;
+ public static String QuickStart_toolTip;
+ public static String QuickStartMessageDialog_title;
+ public static String QuickStartMessageDialog_message;
+ public static String WelcomePageSelectionDialog_title;
+ public static String WelcomePageSelectionDialog_message;
+ public static String TipsAndTricks_text;
+ public static String TipsAndTricks_toolTip;
+ public static String TipsAndTricksMessageDialog_title;
+ public static String TipsAndTricksMessageDialog_message;
+ public static String TipsAndTricksPageSelectionDialog_title;
+ public static String TipsAndTricksPageSelectionDialog_message;
+ public static String TipsAndTricksErrorDialog_title;
+ public static String TipsAndTricksErrorDialog_noHref;
+ public static String TipsAndTricksErrorDialog_noFeatures;
+
+ // ==============================================================================
+ // Navigator Actions
+ // ==============================================================================
+ public static String OpenWithMenu_dialogTitle;
+
+ public static String CopyProjectAction_title;
+ public static String CopyProjectAction_toolTip;
+ public static String CopyProjectAction_copyTitle;
+ public static String CopyProjectAction_copyNameOneArg;
+ public static String CopyProjectAction_copyNameTwoArgs;
+ public static String CopyProjectAction_alreadyExists;
+ public static String CopyProjectAction_copyFailedTitle;
+ public static String CopyProjectAction_internalError;
+
+ public static String CopyResourceAction_title;
+ public static String CopyResourceAction_toolTip;
+ public static String CopyResourceAction_selectDestination;
+
+ public static String MoveProjectAction_text;
+ public static String MoveProjectAction_toolTip;
+ public static String MoveProjectAction_moveTitle;
+ public static String MoveProjectAction_dialogTitle;
+ public static String MoveProjectAction_internalError;
+
+ public static String MoveResourceAction_text;
+ public static String MoveResourceAction_toolTip;
+ public static String MoveResourceAction_title;
+ public static String MoveResourceAction_checkMoveMessage;
+
+ public static String ReadOnlyCheck_problems;
+
+ public static String RenameResourceAction_text;
+ public static String RenameResourceAction_toolTip;
+ public static String RenameResourceAction_operationTitle;
+ public static String RenameResourceAction_inputDialogTitle;
+ public static String RenameResourceAction_inputDialogMessage;
+ public static String RenameResourceAction_checkTitle;
+ public static String RenameResourceAction_readOnlyCheck;
+ public static String RenameResourceAction_resourceExists;
+ public static String RenameResourceAction_projectExists;
+ public static String RenameResourceAction_nameExists;
+ public static String RenameResourceAction_overwriteQuestion;
+ public static String RenameResourceAction_overwriteProjectQuestion;
+ public static String RenameResourceAction_problemTitle;
+ public static String RenameResourceAction_progress;
+ public static String RenameResourceAction_nameMustBeDifferent;
+ public static String RenameResourceAction_problemMessage;
+
+ public static String DeleteResourceAction_text;
+ public static String DeleteResourceAction_toolTip;
+ public static String DeleteResourceAction_title1;
+ public static String DeleteResourceAction_titleN;
+ public static String DeleteResourceAction_confirm1;
+ public static String DeleteResourceAction_confirmN;
+ public static String DeleteResourceAction_titleProject1;
+ public static String DeleteResourceAction_titleProjectN;
+ public static String DeleteResourceAction_confirmProject1;
+ public static String DeleteResourceAction_confirmProjectN;
+ public static String DeleteResourceAction_deleteContents1;
+ public static String DeleteResourceAction_deleteContentsN;
+ public static String DeleteResourceAction_deleteContentsDetails;
+ public static String DeleteResourceAction_doNotDeleteContents;
+ public static String DeleteResourceAction_confirmLinkedResource1;
+ public static String DeleteResourceAction_confirmLinkedResourceN;
+ public static String DeleteResourceAction_readOnlyQuestion;
+ public static String DeleteResourceAction_jobName;
+ public static String DeleteResourceAction_checkJobName;
+ public static String DeleteResourceAction_operationLabel;
+
+ public static String AddBookmarkLabel;
+ public static String AddBookmarkToolTip;
+ public static String AddBookmarkDialog_title;
+ public static String AddBookmarkDialog_message;
+
+ public static String AddTaskLabel;
+ public static String AddTaskToolTip;
+
+ public static String OpenFileAction_text;
+ public static String OpenFileAction_toolTip;
+ public static String OpenFileAction_openFileShellTitle;
+
+ public static String OpenLocalFileAction_title;
+ public static String OpenLocalFileAction_message_fileNotFound;
+ public static String OpenLocalFileAction_message_filesNotFound;
+ public static String OpenLocalFileAction_message_errorOnOpen;
+ public static String OpenLocalFileAction_title_selectWorkspaceFile;
+ public static String OpenLocalFileAction_message_fileLinkedToMultiple;
+
+ public static String OpenResourceAction_text;
+ public static String OpenResourceAction_toolTip;
+ public static String OpenResourceAction_dialogTitle;
+ public static String OpenResourceAction_problemMessage;
+ public static String OpenResourceAction_operationMessage;
+ public static String OpenResourceAction_openRequiredProjects;
+
+ public static String CloseResourceAction_text;
+ public static String CloseResourceAction_warningForOne;
+ public static String CloseResourceAction_warningForMultiple;
+ public static String CloseResourceAction_confirm;
+ public static String CloseResourceAction_toolTip;
+ public static String CloseResourceAction_title;
+ public static String CloseResourceAction_problemMessage;
+ public static String CloseResourceAction_operationMessage;
+
+ public static String CloseUnrelatedProjectsAction_text;
+ public static String CloseUnrelatedProjectsAction_toolTip;
+ public static String CloseUnrelatedProjectsAction_confirmMsg1;
+ public static String CloseUnrelatedProjectsAction_confirmMsgN;
+ public static String CloseUnrelatedProjectsAction_AlwaysClose;
+ public static String CloseUnrelatedProjectsAction_AlwaysCloseWithoutPrompt;
+
+ public static String BuildAction_text;
+ public static String BuildAction_toolTip;
+ public static String BuildAction_problemMessage;
+ public static String BuildAction_problemTitle;
+ public static String BuildAction_operationMessage;
+
+ public static String RebuildAction_text;
+ public static String RebuildAction_tooltip;
+
+ public static String RefreshAction_text;
+ public static String RefreshAction_toolTip;
+ public static String RefreshAction_progressMessage;
+ public static String RefreshAction_problemTitle;
+ public static String RefreshAction_problemMessage;
+ public static String RefreshAction_locationDeletedMessage;
+ public static String RefreshAction_dialogTitle;
+
+ public static String SelectWorkingSetAction_text;
+
+ // --- Operations ---
+ public static String CopyProjectOperation_progressTitle;
+ public static String CopyProjectOperation_copyFailedMessage;
+ public static String CopyProjectOperation_copyFailedTitle;
+ public static String CopyProjectOperation_internalError;
+ public static String CopyProjectOperation_copyProject;
+
+ public static String CopyFilesAndFoldersOperation_copyFailedTitle;
+ public static String CopyFilesAndFoldersOperation_problemMessage;
+ public static String CopyFilesAndFoldersOperation_operationTitle;
+ public static String CopyFilesAndFoldersOperation_nameCollision;
+ public static String CopyFilesAndFoldersOperation_internalError;
+ public static String CopyFilesAndFoldersOperation_resourceExists;
+ public static String CopyFilesAndFoldersOperation_overwriteQuestion;
+ public static String CopyFilesAndFoldersOperation_overwriteWithDetailsQuestion;
+ public static String CopyFilesAndFoldersOperation_overwriteMergeQuestion;
+ public static String CopyFilesAndFoldersOperation_overwriteNoMergeLinkQuestion;
+ public static String CopyFilesAndFoldersOperation_overwriteNoMergeNoLinkQuestion;
+ public static String CopyFilesAndFoldersOperation_deepCopyQuestion;
+ public static String CopyFilesAndFoldersOperation_deepMoveQuestion;
+ public static String CopyFilesAndFoldersOperation_copyNameTwoArgs;
+ public static String CopyFilesAndFoldersOperation_copyNameOneArg;
+ public static String CopyFilesAndFoldersOperation_destinationAccessError;
+ public static String CopyFilesAndFoldersOperation_destinationDescendentError;
+ public static String CopyFilesAndFoldersOperation_overwriteProblem;
+ public static String CopyFilesAndFoldersOperation_question;
+ public static String CopyFilesAndFoldersOperation_inputDialogTitle;
+ public static String CopyFilesAndFoldersOperation_inputDialogMessage;
+ public static String CopyFilesAndFoldersOperation_nameExists;
+ public static String CopyFilesAndFoldersOperation_nameMustBeDifferent;
+ public static String CopyFilesAndFoldersOperation_sameSourceAndDest;
+ public static String CopyFilesAndFoldersOperation_importSameSourceAndDest;
+ public static String CopyFilesAndFoldersOperation_resourceDeleted;
+ public static String CopyFilesAndFoldersOperation_missingPathVariable;
+ public static String CopyFilesAndFoldersOperation_missingLinkTarget;
+ public static String CopyFilesAndFoldersOperation_CopyResourcesTask;
+ public static String CopyFilesAndFoldersOperation_parentNotEqual;
+ public static String CopyFilesAndFoldersOperation_infoNotFound;
+ public static String CopyFilesAndFoldersOperation_sourceCannotBeCopiedIntoAVirtualFolder;
+ public static String CopyFilesAndFoldersOperation_copyTitle;
+ public static String CopyFilesAndFoldersOperation_moveTitle;
+
+ public static String MoveFilesAndFoldersOperation_sameSourceAndDest;
+ public static String MoveFilesAndFoldersOperation_moveFailedTitle;
+ public static String MoveFilesAndFoldersOperation_problemMessage;
+ public static String MoveFilesAndFoldersOperation_operationTitle;
+
+ public static String WizardDataTransfer_existsQuestion;
+ public static String WizardDataTransfer_overwriteNameAndPathQuestion;
+ public static String WizardDataTransfer_exceptionMessage;
+ public static String WizardTransferPage_selectTypes;
+ public static String WizardTransferPage_selectAll;
+ public static String WizardTransferPage_deselectAll;
+
+ // --- Import ---
+ public static String WizardImportPage_specifyFolder;
+ public static String WizardImportPage_specifyProject;
+ public static String WizardImportPage_folderMustExist;
+ public static String WizardImportPage_errorDialogTitle;
+ public static String WizardImportPage_folder;
+ public static String WizardImportPage_browseLabel;
+ public static String WizardImportPage_browse2;
+ public static String WizardImportPage_selectFolderLabel;
+ public static String WizardImportPage_selectFolderTitle;
+ public static String WizardImportPage_destinationLabel;
+ public static String WizardImportPage_options;
+ public static String WizardImportPage_projectNotExist;
+ public static String WizardImportPage_importOnReceiver;
+ public static String WizardImportPage_noOpenProjects;
+ public static String WizardImportPage_undefinedPathVariable;
+ public static String WizardImportPage_containerNotExist;
+
+ // --- Export ---
+ public static String WizardExportPage_errorDialogTitle;
+ public static String WizardExportPage_mustExistMessage;
+ public static String WizardExportPage_mustBeAccessibleMessage;
+ public static String WizardExportPage_detailsMessage;
+ public static String WizardExportPage_whatLabel;
+ public static String WizardExportPage_whereLabel;
+ public static String WizardExportPage_options;
+ public static String WizardExportPage_selectionDialogMessage;
+ public static String WizardExportPage_resourceTypeDialog;
+ public static String WizardExportPage_folder;
+ public static String WizardExportPage_browse;
+ public static String WizardExportPage_allTypes;
+ public static String WizardExportPage_specificTypes;
+ public static String WizardExportPage_edit;
+ public static String WizardExportPage_details;
+ public static String WizardExportPage_selectResourcesTitle;
+ public static String WizardExportPage_oneResourceSelected;
+ public static String WizardExportPage_selectResourcesToExport;
+ public static String WizardExportPage_internalErrorTitle;
+ public static String WizardExportPage_resourceCountMessage;
+
+ // --- New Example ---
+ public static String NewExample_title;
+
+ public static String WizardNewProjectCreationPage_projectNameEmpty;
+ public static String WizardNewProjectCreationPage_projectLocationEmpty;
+ public static String WizardNewProjectCreationPage_projectExistsMessage;
+ public static String WizardNewProjectCreationPage_nameLabel;
+ public static String WizardNewProjectReferences_title;
+
+ // --- New Folder ---
+ public static String WizardNewFolderMainPage_folderName;
+ public static String WizardNewFolderMainPage_folderLabel;
+ public static String WizardNewFolderMainPage_description;
+ public static String WizardNewFolderCreationPage_progress;
+ public static String WizardNewFolderCreationPage_errorTitle;
+ public static String WizardNewFolderCreationPage_internalErrorTitle;
+ public static String WizardNewFolderCreationPage_resourceWillBeFilteredWarning;
+ public static String WizardNewFolderCreationPage_title;
+ public static String WizardNewFolder_internalError;
+ public static String WizardNewFolderCreationPage_createLinkLocationTitle;
+ public static String WizardNewFolderCreationPage_createLinkLocationQuestion;
+
+ // --- New File ---
+ public static String WizardNewFileCreationPage_progress;
+ public static String WizardNewFileCreationPage_errorTitle;
+ public static String WizardNewFileCreationPage_fileLabel;
+ public static String WizardNewFileCreationPage_file;
+ public static String WizardNewFileCreationPage_internalErrorTitle;
+ public static String WizardNewFileCreationPage_internalErrorMessage;
+ public static String WizardNewFileCreationPage_title;
+ public static String WizardNewFileCreationPage_resourceWillBeFilteredWarning;
+ public static String WizardNewFileCreationPage_createLinkLocationTitle;
+ public static String WizardNewFileCreationPage_createLinkLocationQuestion;
+
+
+ // --- Linked Resource ---
+ public static String WizardNewLinkPage_linkFileButton;
+ public static String WizardNewLinkPage_linkFolderButton;
+ public static String WizardNewLinkPage_browseButton;
+ public static String WizardNewLinkPage_variablesButton;
+ public static String WizardNewLinkPage_targetSelectionLabel;
+ public static String WizardNewLinkPage_linkTargetEmpty;
+ public static String WizardNewLinkPage_linkTargetInvalid;
+ public static String WizardNewLinkPage_linkTargetLocationInvalid;
+ public static String WizardNewLinkPage_linkTargetNonExistent;
+ public static String WizardNewLinkPage_linkTargetNotFile;
+ public static String WizardNewLinkPage_linkTargetNotFolder;
+
+ // ==============================================================================
+ // Preference Pages
+ // ==============================================================================
+ public static String Preference_note;
+
+ // --- Workbench ---
+ public static String WorkbenchPreference_encoding;
+ public static String WorkbenchPreference_defaultEncoding;
+ public static String WorkbenchPreference_otherEncoding;
+ public static String WorkbenchPreference_unsupportedEncoding;
+ public static String WorkbenchPreference_encoding_encodingMessage;
+
+ // ---workspace ---
+ public static String IDEWorkspacePreference_autobuild;
+ public static String IDEWorkspacePreference_autobuildToolTip;
+ public static String IDEWorkspacePreference_savePriorToBuilding;
+ public static String IDEWorkspacePreference_savePriorToBuildingToolTip;
+ public static String IDEWorkspacePreference_RefreshButtonText;
+ public static String IDEWorkspacePreference_RefreshButtonToolTip;
+ public static String IDEWorkspacePreference_RefreshLightweightButtonText;
+ public static String IDEWorkspacePreference_RefreshLightweightButtonToolTip;
+ public static String IDEWorkspacePreference_fileLineDelimiter;
+ public static String IDEWorkspacePreference_defaultLineDelim;
+ public static String IDEWorkspacePreference_defaultLineDelimProj;
+ public static String IDEWorkspacePreference_otherLineDelim;
+ public static String IDEWorkspacePreference_relatedLink;
+ public static String IDEWorkspacePreference_openReferencedProjects;
+ public static String IDEWorkspacePreference_closeUnrelatedProjectsToolTip;
+ public static String IDEWorkspacePreference_workspaceName;
+
+ // --- Linked Resources ---
+ public static String LinkedResourcesPreference_explanation;
+ public static String LinkedResourcesPreference_enableLinkedResources;
+ public static String LinkedResourcesPreference_linkedResourcesWarningTitle;
+ public static String LinkedResourcesPreference_linkedResourcesWarningMessage;
+ public static String LinkedResourcesPreference_dragAndDropHandlingMessage;
+ public static String LinkedResourcesPreference_dragAndDropVirtualFolderHandlingMessage;
+ public static String LinkedResourcesPreference_link;
+ public static String linkedResourcesPreference_copy;
+ public static String LinkedResourcesPreference_promptVirtual;
+ public static String LinkedResourcesPreference_linkAndVirtualFolder;
+ public static String LinkedResourcesPreference_linkVirtual;
+ public static String linkedResourcesPreference_copyVirtual;
+ public static String LinkedResourcesPreference_linkAndVirtualFolderVirtual;
+
+ // The following six keys are marked as unused by the NLS search, but they are indirectly used
+ // and should be removed.
+ public static String PathVariableDialog_shellTitle_newVariable;
+ public static String PathVariableDialog_shellTitle_existingVariable;
+ public static String PathVariableDialog_shellTitle_editLocation;
+ public static String PathVariableDialog_dialogTitle_newVariable;
+ public static String PathVariableDialog_dialogTitle_existingVariable;
+ public static String PathVariableDialog_dialogTitle_editLinkLocation;
+ public static String PathVariableDialog_message_newVariable;
+ public static String PathVariableDialog_message_existingVariable;
+ public static String PathVariableDialog_message_editLocation;
+
+ public static String PathVariableDialog_variableName;
+ public static String PathVariableDialog_variableValue;
+ public static String PathVariableDialog_variableResolvedValue;
+ public static String PathVariableDialog_variableNameEmptyMessage;
+ public static String PathVariableDialog_variableValueEmptyMessage;
+ public static String PathVariableDialog_variableValueInvalidMessage;
+ public static String PathVariableDialog_file;
+ public static String PathVariableDialog_folder;
+ public static String PathVariableDialog_variable;
+ public static String PathVariableDialog_selectFileTitle;
+ public static String PathVariableDialog_selectFolderTitle;
+ public static String PathVariableDialog_selectFolderMessage;
+ public static String PathVariableDialog_variableAlreadyExistsMessage;
+ public static String PathVariableDialog_pathIsRelativeMessage;
+ public static String PathVariableDialog_pathDoesNotExistMessage;
+ public static String PathVariableDialog_variableValueIsWrongTypeFolder;
+ public static String PathVariableDialog_variableValueIsWrongTypeFile;
+
+ // --- Local History ---
+ public static String FileHistory_longevity;
+ public static String FileHistory_entries;
+ public static String FileHistory_diskSpace;
+ public static String FileHistory_applyPolicy;
+ public static String FileHistory_mustBePositive;
+ public static String FileHistory_invalid;
+ public static String FileHistory_exceptionSaving;
+ public static String FileHistory_aboveMaxEntries;
+ public static String FileHistory_aboveMaxFileSize;
+ public static String FileHistory_restartNote;
+
+ // --- Perspectives ---
+ public static String ProjectSwitchPerspectiveMode_optionsTitle;
+ public static String ProjectSwitchPerspectiveMode_always;
+ public static String ProjectSwitchPerspectiveMode_never;
+ public static String ProjectSwitchPerspectiveMode_prompt;
+
+ // --- Build Order ---
+ public static String BuildOrderPreference_up;
+ public static String BuildOrderPreference_down;
+ public static String BuildOrderPreference_add;
+ public static String BuildOrderPreference_remove;
+ public static String BuildOrderPreference_selectOtherProjects;
+ public static String BuildOrderPreference_useDefaults;
+ public static String BuildOrderPreference_projectBuildOrder;
+ public static String BuildOrderPreference_removeNote;
+ public static String BuildOrderPreference_maxIterationsLabel;
+
+ // --- Startup preferences ---
+ public static String StartupPreferencePage_refreshButton;
+ public static String StartupPreferencePage_launchPromptButton;
+ public static String StartupPreferencePage_exitPromptButton;
+
+ // --- Startup -> Workspaces preferences ---
+ public static String RecentWorkspacesPreferencePage_NumberOfWorkspaces_label;
+ public static String RecentWorkspacesPreferencePage_PromptAtStartup_label;
+ public static String RecentWorkspacesPreferencePage_RecentWorkspacesList_label;
+ public static String RecentWorkspacesPreferencePage_RemoveButton_label;
+
+
+ // --- Info ---
+ public static String ResourceInfo_readOnly;
+ public static String ResourceInfo_executable;
+ public static String ResourceInfo_locked;
+ public static String ResourceInfo_archive;
+ public static String ResourceInfo_derived;
+ public static String ResourceInfo_derivedHasDerivedAncestor;
+ public static String ResourceInfo_type;
+ public static String ResourceInfo_location;
+ public static String ResourceInfo_resolvedLocation;
+ public static String ResourceInfo_size;
+ public static String ResourceInfo_bytes;
+ public static String ResourceInfo_file;
+ public static String ResourceInfo_fileTypeFormat;
+ public static String ResourceInfo_folder;
+ public static String ResourceInfo_project;
+ public static String ResourceInfo_linkedFile;
+ public static String ResourceInfo_linkedFolder;
+ public static String ResourceInfo_virtualFolder;
+ public static String ResourceInfo_unknown;
+ public static String ResourceInfo_notLocal;
+ public static String ResourceInfo_undefinedPathVariable;
+ public static String ResourceInfo_notExist;
+ public static String ResourceInfo_fileNotExist;
+ public static String ResourceInfo_path;
+ public static String ResourceInfo_lastModified;
+ public static String ResourceInfo_fileEncodingTitle;
+ public static String ResourceInfo_fileContentEncodingFormat;
+ public static String ResourceInfo_fileContentTypeEncodingFormat;
+ public static String ResourceInfo_fileContainerEncodingFormat;
+ public static String ResourceInfo_containerEncodingFormat;
+ public static String ResourceInfo_exWarning;
+ public static String ResourceInfo_isVirtualFolder;
+ public static String ResourceInfo_edit;
+ public static String ResourceInfo_attributes;
+ public static String ResourceInfo_permissions;
+ public static String ResourceInfo_owner;
+ public static String ResourceInfo_group;
+ public static String ResourceInfo_other;
+ public static String ResourceInfo_read;
+ public static String ResourceInfo_write;
+ public static String ResourceInfo_execute;
+
+ // --- Project References ---
+ public static String ProjectReferencesPage_label;
+
+ // --- Project Linked Resources References ---
+ public static String ProjectLinkedResourcePage_description;
+ public static String ProjectLinkedResourcePage_pathVariableTabTitle;
+ public static String ProjectLinkedResourcePage_linkedResourcesTabTitle;
+
+ // --- Linked Resource Editor ---
+ public static String LinkedResourceEditor_editLinkedLocation;
+ public static String LinkedResourceEditor_convertToVariableLocation;
+ public static String LinkedResourceEditor_remove;
+ public static String LinkedResourceEditor_resourceName;
+ public static String LinkedResourceEditor_path;
+ public static String LinkedResourceEditor_location;
+ public static String LinkedResourceEditor_fixed;
+ public static String LinkedResourceEditor_broken;
+ public static String LinkedResourceEditor_absolute;
+ public static String LinkedResourceEditor_changedTo;
+ public static String LinkedResourceEditor_unableToSetLinkLocationForResource;
+ public static String LinkedResourceEditor_convertRelativePathLocations;
+ public static String LinkedResourceEditor_convertionResults;
+ public static String linkedResourceEditor_OK;
+ public static String LinkedResourceEditor_unableToCreateVariable;
+ public static String LinkedResourceEditor_unableToFindCommonPathSegments;
+ public static String LinkedResourceEditor_convertAbsolutePathLocations;
+ public static String LinkedResourceEditor_descriptionBlock;
+ public static String LinkedResourceEditor_convertTitle;
+ public static String LinkedResourceEditor_convertMessage;
+ public static String LinkedResourceEditor_removeTitle;
+ public static String LinkedResourceEditor_removeMessage;
+ public static String LinkedResourceEditor_removingMessage;
+
+ // ==============================================================================
+ // Editors
+ // ==============================================================================
+ public static String DefaultEditorDescription_name;
+
+ public static String WelcomeEditor_accessException;
+ public static String WelcomeEditor_readFileError;
+ public static String WelcomeEditor_title;
+ public static String WelcomeEditor_toolTip;
+ public static String WelcomeEditor_copy_text;
+
+ public static String WelcomeItem_unableToLoadClass;
+ public static String WelcomeParser_parseError;
+ public static String WelcomeParser_parseException;
+ public static String Workbench_openEditorErrorDialogTitle;
+ public static String Workbench_openEditorErrorDialogMessage;
+ public static String QuickStartAction_openEditorException;
+
+ // ==============================================================================
+ // Dialogs
+ // ==============================================================================
+ public static String Question;
+ public static String Always;
+ public static String Never;
+ public static String Prompt;
+
+ public static String ContainerSelectionDialog_title;
+ public static String ContainerSelectionDialog_message;
+
+ public static String ContainerGroup_message;
+ public static String ContainerGroup_selectFolder;
+
+ public static String ContainerGenerator_progressMessage;
+ public static String ContainerGenerator_pathOccupied;
+
+ public static String ResourceGroup_resource;
+ public static String ResourceGroup_nameExists;
+ public static String ResourceGroup_folderEmpty;
+ public static String ResourceGroup_noProject;
+ public static String ResourceGroup_emptyName;
+ public static String ResourceGroup_invalidFilename;
+ public static String ResourceGroup_pathOccupied;
+
+ public static String FileSelectionDialog_title;
+ public static String FileSelectionDialog_message;
+
+ public static String ProjectLocationSelectionDialog_nameLabel;
+ public static String ProjectLocationSelectionDialog_locationLabel;
+ public static String ProjectLocationSelectionDialog_browseLabel;
+ public static String ProjectLocationSelectionDialog_directoryLabel;
+ public static String ProjectLocationSelectionDialog_locationError;
+ public static String ProjectLocationSelectionDialog_locationIsSelf;
+ public static String ProjectLocationSelectionDialog_selectionTitle;
+ public static String ProjectLocationSelectionDialog_useDefaultLabel;
+
+ public static String ResourceSelectionDialog_title;
+ public static String ResourceSelectionDialog_message;
+
+ public static String MarkerResolutionSelectionDialog_title;
+ public static String MarkerResolutionSelectionDialog_messageLabel;
+ public static String MarkerDeleteHandler_JobTitle;
+ public static String MarkerDeleteHandler_JobMessageLabel;
+
+ public static String FilteredResourcesSelectionDialog_showDerivedResourcesAction;
+
+ public static String ResourceSelectionDialog_label;
+ public static String ResourceSelectionDialog_matching;
+ public static String ResourceSelectionDialog_folders;
+ public static String ResourceSelectionDialog_showDerived;
+
+ public static String OpenResourceDialog_title;
+ public static String OpenResourceDialog_openWithMenu_label;
+ public static String OpenResourceDialog_openButton_text;
+ public static String OpenResourceDialog_openWithButton_toolTip;
+
+ public static String NewFolderDialog_title;
+ public static String NewFolderDialog_nameLabel;
+ public static String NewFolderDialog_alreadyExists;
+ public static String NewFolderDialog_folderNameEmpty;
+ public static String NewFolderDialog_progress;
+ public static String NewFolderDialog_errorTitle;
+ public static String NewFolderDialog_internalError;
+
+ public static String CreateLinkedResourceGroup_linkFileButton;
+ public static String CreateLinkedResourceGroup_linkFolderButton;
+ public static String CreateLinkedResourceGroup_browseButton;
+ public static String CreateLinkedResourceGroup_variablesButton;
+ public static String CreateLinkedResourceGroup_resolvedPathLabel;
+ public static String CreateLinkedResourceGroup_targetSelectionLabel;
+ public static String CreateLinkedResourceGroup_targetSelectionTitle;
+ public static String CreateLinkedResourceGroup_linkTargetNotFile;
+ public static String CreateLinkedResourceGroup_linkTargetNotFolder;
+ public static String CreateLinkedResourceGroup_linkTargetNonExistent;
+ public static String CreateLinkedResourceGroup_unableToValidateLinkTarget;
+ public static String CreateLinkedResourceGroup_linkRequiredUnderAGroup;
+
+ public static String PathVariablesBlock_variablesLabel;
+ public static String PathVariablesBlock_variablesLabelForResource;
+ public static String PathVariablesBlock_addVariableButton;
+ public static String PathVariablesBlock_editVariableButton;
+ public static String PathVariablesBlock_removeVariableButton;
+ public static String PathVariablesBlock_nameColumn;
+ public static String PathVariablesBlock_valueColumn;
+
+ public static String ResourceFilterEditDialog_title;
+
+ public static String PathVariableSelectionDialog_title;
+ public static String PathVariableSelectionDialog_extendButton;
+ public static String PathVariableSelectionDialog_ExtensionDialog_title;
+ public static String PathVariableSelectionDialog_ExtensionDialog_description;
+
+ public static String ImportTypeDialog_title;
+ public static String ImportTypeDialog_titleFilesOnly;
+ public static String ImportTypeDialog_titleFilesLinking;
+ public static String ImportTypeDialog_question;
+ public static String ImportTypeDialog_questionFilesOnly;
+ public static String ImportTypeDialog_moveFilesAndDirectories;
+ public static String ImportTypeDialog_copyFilesAndDirectories;
+ public static String ImportTypeDialog_moveFiles;
+ public static String ImportTypeDialog_copyFiles;
+ public static String ImportTypeDialog_recreateFilesAndDirectories;
+ public static String ImportTypeDialog_createLinks;
+ public static String ImportTypeDialog_linkFiles;
+ public static String ImportTypeDialog_importElementsAs;
+ public static String ImportTypeDialog_importElementsAsTooltip;
+ public static String ImportTypeDialog_importElementsAsTooltipSet;
+ public static String ImportTypeDialog_editVariables;
+ public static String ImportTypeDialog_alwaysPerformThisOperation;
+ public static String ImportTypeDialog_configureSettings;
+
+ // ==============================================================================
+ // Editor Framework
+ // ==============================================================================
+ public static String EditorManager_saveResourcesMessage;
+ public static String EditorManager_saveResourcesTitle;
+
+ public static String OpenSystemEditorAction_dialogTitle;
+ public static String OpenSystemEditorAction_text;
+ public static String OpenSystemEditorAction_toolTip;
+
+ // ==============================================================================
+ // Workspace
+ // ==============================================================================
+ public static String WorkspaceAction_problemsTitle;
+ public static String WorkspaceAction_logTitle;
+ public static String WorkbenchAction_problemsMessage;
+ public static String WorkbenchAction_internalError;
+ public static String Workspace;
+
+
+ // ==============================================================================
+ // Workbench
+ // ==============================================================================
+ public static String WorkbenchWindow_shellTitle;
+
+ public static String Internal_error;
+ public static String InternalError;
+ public static String InternalErrorNoArg;
+ public static String InternalErrorOneArg;
+
+ public static String FatalError_RecursiveError;
+ public static String FatalError_OutOfMemoryError;
+ public static String FatalError_StackOverflowError;
+ public static String FatalError_VirtualMachineError;
+ public static String FatalError_SWTError;
+ public static String FatalError;
+
+ public static String ProblemSavingWorkbench;
+ public static String ProblemsSavingWorkspace;
+
+ public static String Problems_Opening_Page;
+
+ public static String Workspace_refreshing;
+
+ public static String IDEExceptionHandler_ExceptionHandledMessage;
+ // ==============================================================================
+ // Keys with references but don't show in the UI
+ // ==============================================================================
+ public static String CreateFileAction_text;
+ public static String CreateFileAction_toolTip;
+ public static String CreateFileAction_title;
+
+ public static String CreateFolderAction_text;
+ public static String CreateFolderAction_toolTip;
+ public static String CreateFolderAction_title;
+
+ public static String ScrubLocalAction_problemsMessage;
+ public static String ScrubLocalAction_text;
+ public static String ScrubLocalAction_toolTip;
+ public static String ScrubLocalAction_problemsTitle;
+ public static String ScrubLocalAction_progress;
+
+ public static String TextAction_selectAll;
+ public static String Cut;
+ public static String Copy;
+ public static String Paste;
+ public static String Delete;
+
+ // ==============================================================================
+ // Keys used in the reuse editor which is released as experimental.
+ // ==============================================================================
+ public static String WorkbenchPreference_saveInterval;
+ public static String WorkbenchPreference_saveIntervalError;
+
+ // ==============================================================================
+ // Working Set Framework.
+ // ==============================================================================
+ public static String ResourceWorkingSetPage_title;
+ public static String ResourceWorkingSetPage_description;
+ public static String ResourceWorkingSetPage_message;
+ public static String ResourceWorkingSetPage_label_tree;
+ public static String ResourceWorkingSetPage_warning_nameMustNotBeEmpty;
+ public static String ResourceWorkingSetPage_warning_nameWhitespace;
+ public static String ResourceWorkingSetPage_warning_workingSetExists;
+ public static String ResourceWorkingSetPage_warning_resourceMustBeChecked;
+ public static String ResourceWorkingSetPage_error;
+ public static String ResourceWorkingSetPage_error_updateCheckedState;
+ public static String ResourceWorkingSetPage_selectAll_label;
+ public static String ResourceWorkingSetPage_selectAll_toolTip;
+ public static String ResourceWorkingSetPage_deselectAll_label;
+ public static String ResourceWorkingSetPage_deselectAll_toolTip;
+
+ public static String ResourceEncodingFieldEditor_ErrorLoadingMessage;
+ public static String ResourceEncodingFieldEditor_ErrorStoringMessage;
+ public static String ResourceEncodingFieldEditor_EncodingConflictTitle;
+ public static String ResourceEncodingFieldEditor_EncodingConflictMessage;
+ public static String ResourceEncodingFieldEditor_SeparateDerivedEncodingsLabel;
+
+ public static String ChooseWorkspaceDialog_dialogName;
+ public static String ChooseWorkspaceDialog_dialogTitle;
+ public static String ChooseWorkspaceDialog_dialogMessage;
+ public static String ChooseWorkspaceDialog_defaultProductName;
+ public static String ChooseWorkspaceDialog_workspaceEntryLabel;
+ public static String ChooseWorkspaceDialog_browseLabel;
+ public static String ChooseWorkspaceDialog_directoryBrowserTitle;
+ public static String ChooseWorkspaceDialog_directoryBrowserMessage;
+ public static String ChooseWorkspaceDialog_useDefaultMessage;
+
+ public static String ChooseWorkspaceWithSettingsDialog_SettingsGroupName;
+ public static String ChooseWorkspaceWithSettingsDialog_ProblemsTransferTitle;
+ public static String ChooseWorkspaceWithSettingsDialog_TransferFailedMessage;
+ public static String ChooseWorkspaceWithSettingsDialog_SaveSettingsFailed;
+ public static String ChooseWorkspaceWithSettingsDialog_ClassCreationFailed;
+
+ public static String IDEApplication_workspaceMandatoryTitle;
+ public static String IDEApplication_workspaceMandatoryMessage;
+ public static String IDEApplication_workspaceInUseTitle;
+ public static String IDEApplication_workspaceInUseMessage;
+ public static String IDEApplication_workspaceEmptyTitle;
+ public static String IDEApplication_workspaceEmptyMessage;
+ public static String IDEApplication_workspaceInvalidTitle;
+ public static String IDEApplication_workspaceInvalidMessage;
+ public static String IDEApplication_workspaceCannotBeSetTitle;
+ public static String IDEApplication_workspaceCannotBeSetMessage;
+ public static String IDEApplication_workspaceCannotLockTitle;
+ public static String IDEApplication_workspaceCannotLockMessage;
+ public static String IDEApplication_versionTitle;
+ public static String IDEApplication_versionMessage;
+ public static String GlobalBuildAction_BuildRunningTitle;
+ public static String GlobalBuildAction_BuildRunningMessage;
+ public static String CleanDialog_buildCleanAuto;
+ public static String CleanDialog_buildCleanManual;
+ public static String CleanDialog_title;
+ public static String CleanDialog_cleanAllButton;
+ public static String CleanDialog_cleanSelectedButton;
+ public static String CleanDialog_buildNowButton;
+ public static String CleanDialog_globalBuildButton;
+ public static String CleanDialog_buildSelectedProjectsButton;
+ public static String CleanDialog_cleanSelectedTaskName;
+ public static String CleanDialog_cleanAllTaskName;
+ public static String IDEEncoding_EncodingJob;
+ public static String IDEEditorsPreferencePage_WorkbenchPreference_viewsRelatedLink;
+ public static String IDEEditorsPreferencePage_WorkbenchPreference_FileEditorsRelatedLink;
+ public static String IDEEditorsPreferencePage_WorkbenchPreference_contentTypesRelatedLink;
+ public static String WorkbenchEncoding_invalidCharset;
+ public static String CopyProjectAction_confirm;
+ public static String CopyProjectAction_warning;
+ public static String DeleteResourceAction_confirm;
+ public static String DeleteResourceAction_warning;
+ public static String CopyFilesAndFoldersOperation_confirmMove;
+ public static String CopyFilesAndFoldersOperation_warningMove;
+ public static String CopyFilesAndFoldersOperation_confirmCopy;
+ public static String CopyFilesAndFoldersOperation_warningCopy;
+ public static String RenameResourceAction_confirm;
+ public static String RenameResourceAction_warning;
+
+ public static String IDE_sideEffectWarning;
+
+ public static String IDE_areYouSure;
+
+ public static String IDEIdleHelper_backgroundGC;
+
+ public static String SystemSettingsChange_title;
+ public static String SystemSettingsChange_message;
+ public static String SystemSettingsChange_yes;
+ public static String SystemSettingsChange_no;
+
+ public static String UnsupportedVM_message;
+
+ public static String IDEWorkbenchActivityHelper_jobName;
+
+ public static String OpenDelayedFileAction_title;
+ public static String OpenDelayedFileAction_message_errorOnOpen;
+ public static String OpenDelayedFileAction_message_fileNotFound;
+ public static String OpenDelayedFileAction_message_noWindow;
+
+ static {
+ // load message values from bundle file
+ NLS.initializeMessages(BUNDLE_NAME, IDEWorkbenchMessages.class);
+ }
+
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/part/FileEditorInput.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/part/FileEditorInput.java
new file mode 100644
index 00000000..22611c11
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/part/FileEditorInput.java
@@ -0,0 +1,265 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui.part;
+
+import java.net.URI;
+
+import org.eclipse.core.filesystem.EFS;
+import org.eclipse.core.filesystem.IFileStore;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.PlatformObject;
+import org.eclipse.core.runtime.content.IContentType;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IStorage;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.IPathEditorInput;
+import org.eclipse.ui.IPersistableElement;
+import org.eclipse.ui.IURIEditorInput;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.ide.IDE;
+// import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+
+/**
+ * Adapter for making a file resource a suitable input for an editor.
+ * <p>
+ * This class may be instantiated; it is not intended to be subclassed.
+ * </p>
+ * @noextend This class is not intended to be subclassed by clients.
+ */
+public class FileEditorInput extends PlatformObject implements IFileEditorInput, IPathEditorInput, IURIEditorInput,
+ IPersistableElement {
+ private IFile file;
+
+ /**
+ * Return whether or not file is local. Only {@link IFile}s with a local
+ * value should call {@link IPathEditorInput#getPath()}
+ * @param file
+ * @return boolean <code>true</code> if the file has a local implementation.
+ * @since 3.4
+ */
+ public static boolean isLocalFile(IFile file){
+
+ IPath location = file.getLocation();
+ if (location != null)
+ return true;
+ //this is not a local file, so try to obtain a local file
+ try {
+ final URI locationURI = file.getLocationURI();
+ if (locationURI == null)
+ return false;
+ IFileStore store = EFS.getStore(locationURI);
+ //first try to obtain a local file directly fo1r this store
+ java.io.File localFile = store.toLocalFile(EFS.NONE, null);
+ //if no local file is available, obtain a cached file
+ if (localFile == null)
+ localFile = store.toLocalFile(EFS.CACHE, null);
+ if (localFile == null)
+ return false;
+ return true;
+ } catch (CoreException e) {
+ //this can only happen if the file system is not available for this scheme
+ /*IDEWorkbenchPlugin.log(
+ "Failed to obtain file store for resource", e); //$NON-NLS-1$*/
+ return false;
+ }
+
+ }
+
+ /**
+ * Creates an editor input based of the given file resource.
+ *
+ * @param file the file resource
+ */
+ public FileEditorInput(IFile file) {
+ if (file == null)
+ throw new IllegalArgumentException();
+ this.file = file;
+
+ }
+
+ /* (non-Javadoc)
+ * Method declared on Object.
+ */
+ public int hashCode() {
+ return file.hashCode();
+ }
+
+ /* (non-Javadoc)
+ * Method declared on Object.
+ *
+ * The <code>FileEditorInput</code> implementation of this <code>Object</code>
+ * method bases the equality of two <code>FileEditorInput</code> objects on the
+ * equality of their underlying <code>IFile</code> resources.
+ */
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof IFileEditorInput)) {
+ return false;
+ }
+ IFileEditorInput other = (IFileEditorInput) obj;
+ return file.equals(other.getFile());
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IEditorInput.
+ */
+ public boolean exists() {
+ return file.exists();
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IPersistableElement.
+ */
+ public String getFactoryId() {
+ return FileEditorInputFactory.getFactoryId();
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IFileEditorInput.
+ */
+ public IFile getFile() {
+ return file;
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IEditorInput.
+ */
+ public ImageDescriptor getImageDescriptor() {
+ IContentType contentType = IDE.getContentType(file);
+ return PlatformUI.getWorkbench().getEditorRegistry()
+ .getImageDescriptor(file.getName(), contentType);
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IEditorInput.
+ */
+ public String getName() {
+ return file.getName();
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IEditorInput.
+ */
+ public IPersistableElement getPersistable() {
+ return this;
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IStorageEditorInput.
+ */
+ public IStorage getStorage() {
+ return file;
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IEditorInput.
+ */
+ public String getToolTipText() {
+ return file.getFullPath().makeRelative().toString();
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IPersistableElement.
+ */
+ public void saveState(IMemento memento) {
+ FileEditorInputFactory.saveState(memento, this);
+ }
+
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IURIEditorInput#getURI()
+ */
+ public URI getURI() {
+ return file.getLocationURI();
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IPathEditorInput#getPath()
+ */
+ public IPath getPath() {
+ IPath location = file.getLocation();
+ if (location != null)
+ return location;
+ //this is not a local file, so try to obtain a local file
+ try {
+ final URI locationURI = file.getLocationURI();
+ if (locationURI == null)
+ throw new IllegalArgumentException();
+ IFileStore store = EFS.getStore(locationURI);
+ //first try to obtain a local file directly fo1r this store
+ java.io.File localFile = store.toLocalFile(EFS.NONE, null);
+ //if no local file is available, obtain a cached file
+ if (localFile == null)
+ localFile = store.toLocalFile(EFS.CACHE, null);
+ if (localFile == null)
+ throw new IllegalArgumentException();
+ return Path.fromOSString(localFile.getAbsolutePath());
+ } catch (CoreException e) {
+ //this can only happen if the file system is not available for this scheme
+ /*IDEWorkbenchPlugin.log(
+ "Failed to obtain file store for resource", e); //$NON-NLS-1$*/
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return getClass().getName() + "(" + getFile().getFullPath() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /*
+ * Allows for the return of an {@link IWorkbenchAdapter} adapter.
+ *
+ * @since 3.5
+ *
+ * @see org.eclipse.core.runtime.PlatformObject#getAdapter(java.lang.Class)
+ */
+ public Object getAdapter(Class adapter) {
+ if (IWorkbenchAdapter.class.equals(adapter)) {
+ return new IWorkbenchAdapter() {
+
+ public Object[] getChildren(Object o) {
+ return new Object[0];
+ }
+
+ public ImageDescriptor getImageDescriptor(Object object) {
+ return FileEditorInput.this.getImageDescriptor();
+ }
+
+ public String getLabel(Object o) {
+ return FileEditorInput.this.getName();
+ }
+
+ public Object getParent(Object o) {
+ return FileEditorInput.this.getFile().getParent();
+ }
+ };
+ }
+
+ return super.getAdapter(adapter);
+ }
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/part/FileEditorInputFactory.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/part/FileEditorInputFactory.java
new file mode 100644
index 00000000..e8b40bf5
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/part/FileEditorInputFactory.java
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui.part;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.Path;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.ResourcesPlugin;
+
+import org.eclipse.ui.IElementFactory;
+import org.eclipse.ui.IMemento;
+
+/**
+ * Factory for saving and restoring a <code>FileEditorInput</code>.
+ * The stored representation of a <code>FileEditorInput</code> remembers
+ * the full path of the file (that is, <code>IFile.getFullPath</code>).
+ * <p>
+ * The workbench will automatically create instances of this class as required.
+ * It is not intended to be instantiated or subclassed by the client.
+ * </p>
+ * @noinstantiate This class is not intended to be instantiated by clients.
+ * @noextend This class is not intended to be subclassed by clients.
+ */
+public class FileEditorInputFactory implements IElementFactory {
+ /**
+ * Factory id. The workbench plug-in registers a factory by this name
+ * with the "org.eclipse.ui.elementFactories" extension point.
+ */
+ private static final String ID_FACTORY = "org.eclipse.ui.part.FileEditorInputFactory"; //$NON-NLS-1$
+
+ /**
+ * Tag for the IFile.fullPath of the file resource.
+ */
+ private static final String TAG_PATH = "path"; //$NON-NLS-1$
+
+ /**
+ * Creates a new factory.
+ */
+ public FileEditorInputFactory() {
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IElementFactory.
+ */
+ public IAdaptable createElement(IMemento memento) {
+ // Get the file name.
+ String fileName = memento.getString(TAG_PATH);
+ if (fileName == null) {
+ return null;
+ }
+
+ // Get a handle to the IFile...which can be a handle
+ // to a resource that does not exist in workspace
+ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(
+ new Path(fileName));
+ if (file != null) {
+ return new FileEditorInput(file);
+ }
+ return null;
+ }
+
+ /**
+ * Returns the element factory id for this class.
+ *
+ * @return the element factory id
+ */
+ public static String getFactoryId() {
+ return ID_FACTORY;
+ }
+
+ /**
+ * Saves the state of the given file editor input into the given memento.
+ *
+ * @param memento the storage area for element state
+ * @param input the file editor input
+ */
+ public static void saveState(IMemento memento, FileEditorInput input) {
+ IFile file = input.getFile();
+ memento.putString(TAG_PATH, file.getFullPath().toString());
+ }
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java
new file mode 100644
index 00000000..4e9f1583
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java
@@ -0,0 +1,206 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.ui.texteditor;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleException;
+import org.osgi.framework.Constants;
+
+import org.eclipse.osgi.util.ManifestElement;
+
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+
+//TODO [RAP] import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
+
+/**
+ * Allows to sort an array based on their elements' configuration elements
+ * according to the prerequisite relation of their defining plug-ins.
+ * <p>
+ * This class may be subclassed.
+ * </p>
+ *
+ * @since 3.0
+ */
+public abstract class ConfigurationElementSorter {
+
+ /**
+ * Sorts the given array based on its elements' configuration elements
+ * according to the prerequisite relation of their defining plug-ins.
+ *
+ * @param elements the array to be sorted
+ */
+ public final void sort(Object[] elements) {
+ Arrays.sort(elements, new ConfigurationElementComparator(elements));
+ }
+
+ /**
+ * Returns the configuration element for the given object.
+ *
+ * @param object the object
+ * @return the object's configuration element, must not be <code>null</code>
+ */
+ public abstract IConfigurationElement getConfigurationElement(Object object);
+
+ /**
+ * Compare configuration elements according to the prerequisite relation
+ * of their defining plug-ins.
+ */
+ private class ConfigurationElementComparator implements Comparator {
+
+ private Map fDescriptorMapping;
+ private Map fPrereqsMapping;
+
+ public ConfigurationElementComparator(Object[] elements) {
+ Assert.isNotNull(elements);
+ initialize(elements);
+ }
+
+ /*
+ * @see Comparator#compare(java.lang.Object, java.lang.Object)
+ * @since 2.0
+ */
+ public int compare(Object object0, Object object1) {
+
+ if (dependsOn(object0, object1))
+ return -1;
+
+ if (dependsOn(object1, object0))
+ return +1;
+
+ return 0;
+ }
+
+ /**
+ * Returns whether one configuration element depends on the other element.
+ * This is done by checking the dependency chain of the defining plug-ins.
+ *
+ * @param element0 the first element
+ * @param element1 the second element
+ * @return <code>true</code> if <code>element0</code> depends on <code>element1</code>.
+ * @since 2.0
+ */
+ private boolean dependsOn(Object element0, Object element1) {
+ if (element0 == null || element1 == null)
+ return false;
+
+ String pluginDesc0= (String)fDescriptorMapping.get(element0);
+ String pluginDesc1= (String)fDescriptorMapping.get(element1);
+
+ // performance tuning - code below would give same result
+ if (pluginDesc0.equals(pluginDesc1))
+ return false;
+
+ Set prereqUIds0= (Set)fPrereqsMapping.get(pluginDesc0);
+
+ return prereqUIds0.contains(pluginDesc1);
+ }
+
+ /**
+ * Initialize this comparator.
+ *
+ * @param elements an array of Java editor hover descriptors
+ */
+ private void initialize(Object[] elements) {
+ int length= elements.length;
+ fDescriptorMapping= new HashMap(length);
+ fPrereqsMapping= new HashMap(length);
+ Set fBundleSet= new HashSet(length);
+
+ for (int i= 0; i < length; i++) {
+ IConfigurationElement configElement= getConfigurationElement(elements[i]);
+ Bundle bundle= Platform.getBundle(configElement.getContributor().getName());
+ fDescriptorMapping.put(elements[i], bundle.getSymbolicName());
+ fBundleSet.add(bundle);
+ }
+
+ Iterator iter= fBundleSet.iterator();
+ while (iter.hasNext()) {
+ Bundle bundle= (Bundle)iter.next();
+ List toTest= new ArrayList(fBundleSet);
+ toTest.remove(bundle);
+ Set prereqUIds= new HashSet(Math.max(0, toTest.size() - 1));
+ fPrereqsMapping.put(bundle.getSymbolicName(), prereqUIds);
+
+ String requires = (String)bundle.getHeaders().get(Constants.REQUIRE_BUNDLE);
+ ManifestElement[] manifestElements;
+ try {
+ manifestElements = ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, requires);
+ } catch (BundleException e) {
+ String uid= getExtensionPointUniqueIdentifier(bundle);
+ String message= "ConfigurationElementSorter for '" + uid + "': getting required plug-ins for '" + bundle.getSymbolicName() + "' failed"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ /*TODO [RAP] Status status= new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, IStatus.OK, message, e);
+ TextEditorPlugin.getDefault().getLog().log(status);*/
+ continue;
+ }
+
+ if (manifestElements == null)
+ continue;
+
+ int i= 0;
+ while (i < manifestElements.length && !toTest.isEmpty()) {
+ String prereqUId= manifestElements[i].getValue();
+ for (int j= 0; j < toTest.size();) {
+ Bundle toTest_j= (Bundle)toTest.get(j);
+ if (toTest_j.getSymbolicName().equals(prereqUId)) {
+ toTest.remove(toTest_j);
+ prereqUIds.add(toTest_j.getSymbolicName());
+ } else
+ j++;
+ }
+ i++;
+ }
+ }
+ }
+
+ /**
+ * Returns the unique extension point identifier for the
+ * configuration element which belongs to the given bundle.
+ *
+ * @param bundle the bundle
+ * @return the unique extension point identifier or "unknown" if not found
+ * @since 3.0.1
+ */
+ private String getExtensionPointUniqueIdentifier(Bundle bundle) {
+ if (bundle != null) {
+ String bundleName= bundle.getSymbolicName();
+ if (bundleName != null) {
+ Set entries= fDescriptorMapping.entrySet();
+ Iterator iter= entries.iterator();
+ while (iter.hasNext()) {
+ Map.Entry entry= (Map.Entry)iter.next();
+ if (bundleName.equals(entry.getValue())) {
+ IExtension extension = getConfigurationElement(entry.getKey()).getDeclaringExtension();
+ return extension.getExtensionPointUniqueIdentifier();
+ }
+ }
+ }
+ }
+ return "unknown"; //$NON-NLS-1$
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/DocumentProvider.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/DocumentProvider.java
new file mode 100644
index 00000000..6f2c06a0
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/DocumentProvider.java
@@ -0,0 +1,27 @@
+package org.eclipse.ui.texteditor;
+
+import org.eclipse.jface.text.Document;
+import org.eclipse.ui.IEditorInput;
+
+/**
+ * Simple DocumentProvider class, only holds an Document object.
+ *
+ * @author Matthias Lettmayer
+ *
+ */
+public class DocumentProvider {
+
+ private Document document;
+
+ public DocumentProvider(Document document) {
+ this.document = document;
+ }
+
+ public DocumentProvider(String source) {
+ this.document = new Document(source);
+ }
+ // TODO [RAP] handle EditorInputs
+ public Document getDocument(IEditorInput editorInput) {
+ return document;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ITextEditor.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ITextEditor.java
new file mode 100644
index 00000000..786c3456
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ITextEditor.java
@@ -0,0 +1,198 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2010 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.ui.texteditor;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelectionProvider;
+
+import org.eclipse.jface.text.IRegion;
+
+import org.eclipse.ui.IEditorPart;
+
+
+/**
+ * Interface to a text editor. This interface defines functional extensions to
+ * <code>IEditorPart</code> as well as the configuration capabilities of a text editor.
+ * <p>
+ * Text editors are configured with an <code>IDocumentProvider</code> which delivers a textual
+ * presentation (<code>IDocument</code>) of the editor's input. The editor works on the document and
+ * forwards all input element related calls, such as <code>save</code>, to the document provider.
+ * The provider also delivers the input's annotation model which is used by the editor's vertical
+ * ruler.
+ * </p>
+ * <p>
+ * Clients may implement this interface from scratch, but the recommended way is to subclass the
+ * abstract base class <code>AbstractTextEditor</code>.
+ * </p>
+ * <p>
+ * In order to provided backward compatibility for clients of <code>ITextEditor</code>, extension
+ * interfaces are used to provide a means of evolution. The following extension interfaces exist:
+ * <ul>
+ * <li>{@link org.eclipse.ui.texteditor.ITextEditorExtension} since version 2.0 introducing status
+ * fields, read-only state and ruler context menu listeners.</li>
+ * <li>{@link org.eclipse.ui.texteditor.ITextEditorExtension2} since version 2.1 introducing
+ * modifiable state for the editor input and validate state handling.</li>
+ * <li>{@link org.eclipse.ui.texteditor.ITextEditorExtension3} since version 3.0 adding input state
+ * and change information control.</li>
+ * <li>{@link org.eclipse.ui.texteditor.ITextEditorExtension4} since version 3.2 adding annotation
+ * navigation and revision information display.</li>
+ * <li>{@link org.eclipse.ui.texteditor.ITextEditorExtension5} since version 3.5 adding block
+ * selection mode.</li>
+ * </ul>
+ * </p>
+ *
+ * @see org.eclipse.ui.texteditor.IDocumentProvider
+ * @see org.eclipse.jface.text.source.IAnnotationModel
+ * @see org.eclipse.ui.texteditor.ITextEditorExtension
+ * @see org.eclipse.ui.texteditor.ITextEditorExtension2
+ * @see org.eclipse.ui.texteditor.ITextEditorExtension3
+ * @see org.eclipse.ui.texteditor.ITextEditorExtension4
+ * @see org.eclipse.ui.texteditor.ITextEditorExtension5
+ */
+public interface ITextEditor extends IEditorPart {
+
+ /**
+ * Returns this text editor's document provider.
+ *
+ * @return the document provider or <code>null</code> if none, e.g. after closing the editor
+ */
+ DocumentProvider getDocumentProvider();
+
+ /**
+ * Closes this text editor after optionally saving changes.
+ *
+ * @param save <code>true</code> if unsaved changed should be saved, and
+ * <code>false</code> if unsaved changed should be discarded
+ */
+ void close(boolean save);
+
+ /**
+ * Returns whether the text in this text editor can be changed by the user.
+ *
+ * @return <code>true</code> if it can be edited, and <code>false</code> if it is read-only
+ */
+ boolean isEditable();
+
+ /**
+ * Abandons all modifications applied to this text editor's input element's
+ * textual presentation since the last save operation.
+ */
+ void doRevertToSaved();
+
+ /**
+ * Installs the given action under the given action id.
+ *
+ * @param actionID the action id
+ * @param action the action, or <code>null</code> to clear it
+ * @see #getAction(String)
+ */
+ void setAction(String actionID, IAction action);
+
+ /**
+ * Returns the action installed under the given action id.
+ *
+ * @param actionId the action id
+ * @return the action, or <code>null</code> if none
+ * @see #setAction(String, IAction)
+ */
+ IAction getAction(String actionId);
+
+ /**
+ * Sets the given activation code for the specified action. If
+ * there is an activation code already registered, it is replaced.
+ * The activation code consists of the same information as
+ * a <code>KeyEvent</code>. If the activation code is triggered
+ * and the associated action is enabled, the action is performed
+ * and the triggering <code>KeyEvent</code> is considered consumed.
+ * If the action is disabled, the <code>KeyEvent</code> is passed
+ * on unmodified. Thus, action activation codes and action accelerators
+ * differ in their model of event consumption. The key code parameter
+ * can be <code>-1</code> to indicate a wild card. The state mask
+ * parameter can be SWT.DEFAULT to indicate a wild card.
+ *
+ * @param actionId the action id
+ * @param activationCharacter the activation code character
+ * @param activationKeyCode the activation code key code or <code>-1</code> for wild card
+ * @param activationStateMask the activation code state mask or <code>SWT.DEFAULT</code> for wild card
+ */
+ void setActionActivationCode(String actionId, char activationCharacter, int activationKeyCode, int activationStateMask);
+
+ /**
+ * Removes any installed activation code for the specified action.
+ * If no activation code is installed, this method does not have
+ * any effect.
+ *
+ * @param actionId the action id
+ */
+ void removeActionActivationCode(String actionId);
+
+ /**
+ * Returns whether this text editor is configured to show only the
+ * highlighted range of the text.
+ *
+ * @return <code>true</code> if only the highlighted range is shown, and
+ * <code>false</code> if this editor shows the entire text of the document
+ * @see #showHighlightRangeOnly(boolean)
+ */
+ boolean showsHighlightRangeOnly();
+
+ /**
+ * Configures this text editor to show only the highlighted range of the
+ * text.
+ *
+ * @param showHighlightRangeOnly <code>true</code> if only the highlighted
+ * range is shown, and <code>false</code> if this editor shows the entire
+ * text of the document
+ * @see #showsHighlightRangeOnly()
+ */
+ void showHighlightRangeOnly(boolean showHighlightRangeOnly);
+
+ /**
+ * Sets the highlighted range of this text editor to the specified region.
+ *
+ * @param offset the offset of the highlighted range
+ * @param length the length of the highlighted range
+ * @param moveCursor <code>true</code> if the cursor should be moved to the start of the
+ * highlighted range, and <code>false</code> to leave the cursor unaffected - has no
+ * effect if the range to highlight is already the highlighted one
+ * @see #getHighlightRange()
+ */
+ void setHighlightRange(int offset, int length, boolean moveCursor);
+
+ /**
+ * Returns the highlighted range of this text editor.
+ *
+ * @return the highlighted range
+ * @see #setHighlightRange(int, int, boolean)
+ */
+ IRegion getHighlightRange();
+
+ /**
+ * Resets the highlighted range of this text editor.
+ */
+ void resetHighlightRange();
+
+ /**
+ * Returns this text editor's selection provider. Repeated calls to this
+ * method return the same selection provider.
+ *
+ * @return the selection provider
+ */
+ ISelectionProvider getSelectionProvider();
+
+ /**
+ * Selects and reveals the specified range in this text editor.
+ *
+ * @param offset the offset of the selection
+ * @param length the length of the selection
+ */
+ void selectAndReveal(int offset, int length);
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ITextEditorActionConstants.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ITextEditorActionConstants.java
new file mode 100644
index 00000000..7432dc0d
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipse/ui/texteditor/ITextEditorActionConstants.java
@@ -0,0 +1,696 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2010 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ * Genady Beryozkin, [email protected] - https://bugs.eclipse.org/bugs/show_bug.cgi?id=11668
+ * Benjamin Muskalla <[email protected]> - https://bugs.eclipse.org/bugs/show_bug.cgi?id=41573
+ * Tom Eicher (Avaloq Evolution AG) - block selection mode
+ *******************************************************************************/
+package org.eclipse.ui.texteditor;
+
+//import org.eclipse.jface.text.information.IInformationProvider;
+
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.actions.ActionFactory;
+
+
+/**
+ * Defines the names of those actions which are pre-registered with the
+ * <code>AbstractTextEditor</code>. <code>RULER_DOUBLE_CLICK</code> defines
+ * the action which is registered as being executed when the editor's ruler has
+ * been double clicked. This interface extends the set of names available from
+ * <code>IWorkbenchActionConstants</code>. It also defines the names of the
+ * menu groups in a text editor's context menu.
+ * <p>
+ * This interface must not be implemented by clients.
+ * </p>
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public interface ITextEditorActionConstants extends IWorkbenchActionConstants {
+
+ /**
+ * Context menu group for undo/redo related actions.
+ * Value: <code>"group.undo"</code>
+ */
+ String GROUP_UNDO= "group.undo"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for copy/paste related actions.
+ * Value: <code>"group.copy"</code>
+ */
+ String GROUP_COPY= "group.copy"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for text manipulation actions.
+ * Value: <code>"group.edit"</code>
+ */
+ String GROUP_EDIT= "group.edit"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for print related actions.
+ * Value: <code>"group.print"</code>
+ */
+ String GROUP_PRINT= "group.print"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for find/replace related actions.
+ * Value: <code>"group.find"</code>
+ */
+ String GROUP_FIND= "group.find"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for save related actions.
+ * Value: <code>"group.save"</code>
+ */
+ String GROUP_SAVE= "group.save"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for actions which do not fit in one of the other categories.
+ * Value: <code>"group.rest"</code>
+ */
+ String GROUP_REST= "group.rest"; //$NON-NLS-1$
+
+ /**
+ * Menu group for open actions.
+ * Value <code>"group.open"</code>
+ * @since 3.1
+ */
+ String GROUP_OPEN= "group.open"; //$NON-NLS-1$
+
+ /**
+ * Menu group for code generation and content assist actions.
+ * Value <code>"group.generate"</code>).
+ * @since 3.1
+ */
+ String GROUP_GENERATE= "group.generate"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for shifting text blocks to the right.
+ * Value: <code>"ShiftRight"</code>
+ */
+ String SHIFT_RIGHT= "ShiftRight"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for shifting text blocks to the right, triggered by the TAB key.
+ * Value: <code>"ShiftRightTab"</code>
+ * @since 3.0
+ */
+ String SHIFT_RIGHT_TAB= "ShiftRightTab"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for shifting text blocks to the left.
+ * Value: <code>"ShiftLeft"</code>
+ */
+ String SHIFT_LEFT= "ShiftLeft"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to delete the current line.
+ * Value: <code>"DeleteLine"</code>
+ * @since 2.0
+ */
+ String DELETE_LINE= "DeleteLine"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to join the current lines.
+ * Value: <code>"JoinLine"</code>
+ * @since 3.3
+ */
+ String JOIN_LINES= "JoinLines"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to cut the current line.
+ * Value: <code>"CutLine"</code>
+ * @since 2.1
+ */
+ String CUT_LINE= "CutLine"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to delete line to beginning.
+ * Value: <code>"DeleteLineToBeginning"</code>
+ * @since 2.0
+ */
+ String DELETE_LINE_TO_BEGINNING= "DeleteLineToBeginning"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to cut line to beginning.
+ * Value: <code>"CutLineToBeginning"</code>
+ * @since 2.1
+ */
+ String CUT_LINE_TO_BEGINNING= "CutLineToBeginning"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to delete line to end.
+ * Value: <code>"DeleteLineToEnd"</code>
+ * @since 2.0
+ */
+ String DELETE_LINE_TO_END= "DeleteLineToEnd"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to cut line to end.
+ * Value: <code>"CutLineToEnd"</code>
+ * @since 2.1
+ */
+ String CUT_LINE_TO_END= "CutLineToEnd"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to set the mark.
+ * Value: <code>"SetMark"</code>
+ * @since 2.0
+ */
+ String SET_MARK= "SetMark"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to set the mark.
+ * Value: <code>"ClearMark"</code>
+ * @since 2.0
+ */
+ String CLEAR_MARK= "ClearMark"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to swap the mark with the cursor position.
+ * Value: <code>"SwapMark"</code>
+ * @since 2.0
+ */
+ String SWAP_MARK= "SwapMark"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to jump to a certain text line.
+ * Value: <code>"GotoLine"</code>
+ */
+ String GOTO_LINE= "GotoLine"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to insert a new line below the current position.
+ * Value: <code>"SmartEnter"</code>
+ * @since 3.0
+ */
+ String SMART_ENTER= "SmartEnter"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to insert a new line above the current position.
+ * Value: <code>"SmartEnterInverse"</code>
+ * @since 3.0
+ */
+ String SMART_ENTER_INVERSE= "SmartEnterInverse"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to move lines upwards
+ * Value: <code>"MoveLineUp"</code>
+ * @since 3.0
+ */
+ String MOVE_LINE_UP= "MoveLineUp"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to move lines downwards
+ * Value: <code>"MoveLineDown"</code>
+ * @since 3.0
+ */
+ String MOVE_LINE_DOWN= "MoveLineDown"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to copy lines upwards
+ * Value: <code>"CopyLineUp"</code>
+ * @since 3.0
+ */
+ String COPY_LINE_UP= "CopyLineUp"; //$NON-NLS-1$;
+
+ /**
+ * Name of the action to copy lines downwards
+ * Value: <code>"CopyLineDown"</code>
+ * @since 3.0
+ */
+ String COPY_LINE_DOWN= "CopyLineDown"; //$NON-NLS-1$;
+
+ /**
+ * Name of the action to turn a selection to upper case
+ * Value: <code>"UpperCase"</code>
+ * @since 3.0
+ */
+ String UPPER_CASE= "UpperCase"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to turn a selection to lower case
+ * Value: <code>"LowerCase"</code>
+ * @since 3.0
+ */
+ String LOWER_CASE= "LowerCase"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to find next.
+ * Value: <code>"FindNext"</code>
+ * @since 2.0
+ */
+ String FIND_NEXT= "FindNext"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to find previous.
+ * Value: <code>"FindPrevious"</code>
+ * @since 2.0
+ */
+ String FIND_PREVIOUS= "FindPrevious"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to incremental find.
+ * Value: <code>"FindIncremental"</code>
+ * @since 2.0
+ */
+ String FIND_INCREMENTAL= "FindIncremental"; //$NON-NLS-1$
+ /**
+ * Name of the action to incremental find reverse.
+ * Value: <code>"FindIncrementalReverse"</code>
+ * @since 2.1
+ */
+ String FIND_INCREMENTAL_REVERSE= "FindIncrementalReverse"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to convert line delimiters to Windows.
+ * Value: <code>"ConvertLineDelimitersToWindows"</code>
+ * @since 2.0
+ * @deprecated since 3.1. No longer supported as editor actions.
+ */
+ String CONVERT_LINE_DELIMITERS_TO_WINDOWS= "ConvertLineDelimitersToWindows"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to convert line delimiters to UNIX.
+ * Value: <code>"ConvertLineDelimitersToUNIX"</code>
+ * @since 2.0
+ * @deprecated since 3.1. No longer supported as editor actions.
+ */
+ String CONVERT_LINE_DELIMITERS_TO_UNIX= "ConvertLineDelimitersToUNIX"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to convert line delimiters to MAC.
+ * Value: <code>"ConvertLineDelimitersToMAC"</code>
+ * @since 2.0
+ * @deprecated since 3.1. No longer supported as editor actions.
+ */
+ String CONVERT_LINE_DELIMITERS_TO_MAC= "ConvertLineDelimitersToMAC"; //$NON-NLS-1$
+
+ /**
+ * Name of the change encoding action.
+ * Value: <code>"ChangeEncoding"</code>
+ * @since 3.1
+ */
+ String CHANGE_ENCODING= "ChangeEncoding"; //$NON-NLS-1$
+
+ /**
+ * Name of the ruler action performed when double clicking the editor's vertical ruler.
+ * Value: <code>"RulerDoubleClick"</code>
+ */
+ String RULER_DOUBLE_CLICK= "RulerDoubleClick"; //$NON-NLS-1$
+
+ /**
+ * Name of the ruler action performed when clicking the editor's vertical ruler.
+ * Value: <code>"RulerClick"</code>
+ * @since 2.0
+ */
+ String RULER_CLICK= "RulerClick"; //$NON-NLS-1$
+
+ /**
+ * Name of the ruler action to manage tasks.
+ * Value: <code>"ManageTasks"</code>
+ */
+ String RULER_MANAGE_TASKS= "ManageTasks"; //$NON-NLS-1$
+
+ /**
+ * Name of the ruler action to manage bookmarks.
+ * Value: <code>"ManageBookmarks"</code>
+ */
+ String RULER_MANAGE_BOOKMARKS= "ManageBookmarks"; //$NON-NLS-1$
+
+
+ /**
+ * Status line category "input position".
+ * Value: <code>"InputPosition"</code>
+ * @since 2.0
+ */
+ String STATUS_CATEGORY_INPUT_POSITION= "InputPosition"; //$NON-NLS-1$
+
+ /**
+ * Status line category "input mode".
+ * Value: <code>"InputMode"</code>
+ * @since 2.0
+ */
+ String STATUS_CATEGORY_INPUT_MODE= "InputMode"; //$NON-NLS-1$
+
+ /**
+ * Status line category "element state".
+ * Value: <code>"ElementState"</code>
+ * @since 2.0
+ */
+ String STATUS_CATEGORY_ELEMENT_STATE= "ElementState"; //$NON-NLS-1$
+
+ /**
+ * Status line category "findField".
+ * Value: <code>"findField"</code>
+ * @since 3.0
+ */
+ String STATUS_CATEGORY_FIND_FIELD= "findField"; //$NON-NLS-1$
+
+ /**
+ * Name of standard Copy global action in the Edit menu.
+ * Value <code>"copy"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#COPY
+ */
+ String COPY= ActionFactory.COPY.getId();
+
+ /**
+ * Name of standard Cut global action in the Edit menu.
+ * Value <code>"cut"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#CUT
+ */
+ String CUT= ActionFactory.CUT.getId();
+
+ /**
+ * Name of standard Delete global action in the Edit menu.
+ * Value <code>"delete"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#DELETE
+ */
+ String DELETE= ActionFactory.DELETE.getId();
+
+ /**
+ * Name of standard Find global action in the Edit menu.
+ * Value <code>"find"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#FIND
+ */
+ String FIND= ActionFactory.FIND.getId();
+
+ /**
+ * Name of standard Paste global action in the Edit menu.
+ * Value <code>"paste"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#PASTE
+ */
+ String PASTE= ActionFactory.PASTE.getId();
+
+ /**
+ * Name of standard Print global action in the File menu.
+ * Value <code>"print"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#PRINT
+ */
+ String PRINT= ActionFactory.PRINT.getId();
+
+ /**
+ * Name of standard Properties global action in the File menu.
+ * Value <code>"properties"</code>
+ * @since 3.1
+ * @see org.eclipse.ui.actions.ActionFactory#PROPERTIES
+ */
+ String PROPERTIES= ActionFactory.PROPERTIES.getId();
+
+ /**
+ * Name of standard Redo global action in the Edit menu.
+ * Value <code>"redo"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#REDO
+ */
+ String REDO= ActionFactory.REDO.getId();
+
+ /**
+ * Name of standard Undo global action in the Edit menu.
+ * Value <code>"undo"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#UNDO
+ */
+ String UNDO= ActionFactory.UNDO.getId();
+
+ /**
+ * Name of standard Save global action in the File menu.
+ * Value <code>"save"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#SAVE
+ */
+ String SAVE= ActionFactory.SAVE.getId();
+
+ /**
+ * Name of standard Select All global action in the Edit menu.
+ * Value <code>"selectAll"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#SELECT_ALL
+ */
+ String SELECT_ALL= ActionFactory.SELECT_ALL.getId();
+
+ /**
+ * Name of standard Revert global action in the File menu.
+ * Value <code>"revert"</code>
+ * @since 3.0
+ * @see org.eclipse.ui.actions.ActionFactory#REVERT
+ */
+ String REVERT= ActionFactory.REVERT.getId();
+
+ /**
+ * Name of standard Next global action in the Navigate menu.
+ * Value <code>"next"</code>
+ * @since 3.2
+ * @see org.eclipse.ui.actions.ActionFactory#NEXT
+ */
+ String NEXT= ActionFactory.NEXT.getId();
+
+ /**
+ * Name of standard Previous global action in the Navigate menu.
+ * Value <code>"previous"</code>
+ * @since 3.2
+ * @see org.eclipse.ui.actions.ActionFactory#PREVIOUS
+ */
+ String PREVIOUS= ActionFactory.PREVIOUS.getId();
+
+ /**
+ * Name of standard Refresh global action in the File menu.
+ * Value <code>"refresh"</code>
+ * @since 3.4
+ * @see org.eclipse.ui.actions.ActionFactory#REFRESH
+ */
+ String REFRESH= ActionFactory.REFRESH.getId();
+
+ /**
+ * Name of the action for re-establishing the state after the
+ * most recent save operation.
+ * Value: <code>"ITextEditorActionConstants.REVERT"</code>
+ */
+ String REVERT_TO_SAVED= REVERT;
+
+ /**
+ * Name of the action for toggling the smart insert mode.
+ * Value: <code>"ToggleInsertMode"</code>
+ * @since 3.0
+ */
+ String TOGGLE_INSERT_MODE= "TOGGLE_INSERT_MODE"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for preference related actions.
+ * Value: <code>"settings"</code>
+ * @since 3.1
+ */
+ String GROUP_SETTINGS= "settings"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for ruler column related actions.
+ * Value: <code>"rulers"</code>
+ * @since 3.1
+ */
+ String GROUP_RULERS= "rulers"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for quick diff revert related actions.
+ * Value: <code>"restore"</code>
+ * @since 3.1
+ */
+ String GROUP_RESTORE= "restore"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for actions that display additional information. Value:
+ * <code>"group.information"</code>.
+ * @since 3.2
+ */
+ String GROUP_INFORMATION= "group.information"; //$NON-NLS-1$
+
+ /**
+ * Context menu group for typing aid actions such as content assist. Value:
+ * <code>"group.assist"</code>.
+ * @since 3.2
+ */
+ String GROUP_ASSIST= "group.assist"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for showing the preferences from the editor context
+ * menu. Value: <code>"Preferences.ContextAction"</code>
+ * @since 3.1
+ */
+ String CONTEXT_PREFERENCES= "Preferences.ContextAction"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for showing the preferences from the editor ruler
+ * context menu. Value: <code>"Preferences.RulerAction"</code>
+ * @since 3.1
+ */
+ String RULER_PREFERENCES= "Preferences.RulerAction"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for toggling line number display.
+ * Value: <code>"Linenumbers.Toggle"</code>
+ * @since 3.1
+ */
+ String LINENUMBERS_TOGGLE= "Linenumbers.Toggle"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for reverting deleted lines at the current selection.
+ * Value: <code>"QuickDiff.RevertDeletion"</code>
+ * @since 3.1
+ */
+ String QUICKDIFF_REVERTDELETION= "QuickDiff.RevertDeletion"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for reverting the line at the current selection.
+ * Value: <code>"QuickDiff.RevertLine"</code>
+ * @since 3.1
+ */
+ String QUICKDIFF_REVERTLINE= "QuickDiff.RevertLine"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for reverting the selection or the block at the
+ * current selection. Value: <code>"QuickDiff.Revert"</code>
+ * @since 3.1
+ */
+ String QUICKDIFF_REVERT= "QuickDiff.Revert"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for reverting the block at the current selection.
+ * Value: <code>"QuickDiff.RevertBlock"</code>
+ * @since 3.1
+ */
+ String QUICKDIFF_REVERTBLOCK= "QuickDiff.RevertBlock"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for reverting the current selection.
+ * Value: <code>"QuickDiff.RevertBlock"</code>
+ * @since 3.1
+ */
+ String QUICKDIFF_REVERTSELECTION= "QuickDiff.RevertSelection"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for toggling quick diff display.
+ * Value: <code>"QuickDiff.Toggle"</code>
+ * @since 3.1
+ */
+ String QUICKDIFF_TOGGLE= "QuickDiff.Toggle"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for emacs style word completion.
+ * Value: <code>"HIPPIE_COMPLETION"</code>
+ * @since 3.1
+ */
+ String HIPPIE_COMPLETION= "HIPPIE_COMPLETION"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for hiding the revision info
+ * Value: <code>"Revision.HideInfo"</code>
+ * @since 3.2
+ */
+ String REVISION_HIDE_INFO= "Revision.HideInfo"; //$NON-NLS-1$
+
+ /**
+ * Name of the content assist action.
+ * Value: <code>"ContentAssistProposal"</code>
+ *
+ * @since 3.5
+ */
+ String CONTENT_ASSIST= "ContentAssistProposal"; //$NON-NLS-1$
+
+ /**
+ * Name of the content assist context information action.
+ * Value: <code>"ContentAssistContextInformation"</code>
+ *
+ * @since 3.5
+ */
+ String CONTENT_ASSIST_CONTEXT_INFORMATION= "ContentAssistContextInformation"; //$NON-NLS-1$
+
+ /**
+ * Name of the quick assist action
+ * Value: <code>"QuickAssist"</code>
+ * @since 3.2
+ */
+ String QUICK_ASSIST= "QuickAssist"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for cycling through the revision rendering modes.
+ * Value: <code>"Revision.Rendering.Cycle"</code>
+ * @since 3.3
+ */
+ String REVISION_RENDERING_CYCLE= "Revision.Rendering.Cycle"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for toggling the display of the revision author.
+ * Value: <code>"Revision.ShowAuthor.Toggle"</code>
+ * @since 3.3
+ */
+ String REVISION_SHOW_AUTHOR_TOGGLE= "Revision.ShowAuthor.Toggle"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for toggling the display of the revision id.
+ * Value: <code>"Revision.ShowId.Toggle"</code>
+ * @since 3.3
+ */
+ String REVISION_SHOW_ID_TOGGLE= "Revision.ShowId.Toggle"; //$NON-NLS-1$
+ /**
+ * Name of the action for emacs recenter.
+ * Value: <code>"RECENTER"</code>
+ * @since 3.3
+ */
+ String RECENTER= "Recenter"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for toggling the display of whitespace characters.
+ * Value: <code>"ShowWhitespaceCharacters"</code>
+ * @since 3.3
+ */
+ String SHOW_WHITESPACE_CHARACTERS= "ShowWhitespaceCharacters"; //$NON-NLS-1$
+
+ /**
+ * Name of the action displaying information for the
+ * current caret location in a sticky hover.
+ * Value: <code>"ShowInformation"</code>
+ * @see IInformationProvider
+ * @since 3.3
+ */
+ String SHOW_INFORMATION= "ShowInformation"; //$NON-NLS-1$
+
+ /**
+ * Name of the action for toggling block selection mode. Value:
+ * <code>"BlockSelectionMode"</code>
+ * @since 3.5
+ */
+ String BLOCK_SELECTION_MODE= "BlockSelectionMode"; //$NON-NLS-1$
+
+ /**
+ * Name of the action displaying a sticky ruler hover for the current caret location.
+ * Value: <code>"ShowChangeRulerInformation"</code>
+ * @since 3.6
+ */
+ public static final String SHOW_CHANGE_RULER_INFORMATION= "ShowChangeRulerInformation"; //$NON-NLS-1$
+
+ /**
+ * Name of the action displaying a sticky ruler annotation hover for the current caret location.
+ * Value: <code>"ShowRulerAnnotationInformation"</code>
+ * @since 3.6
+ */
+ public static final String SHOW_RULER_ANNOTATION_INFORMATION= "ShowRulerAnnotationInformation"; //$NON-NLS-1$
+
+ /**
+ * Name of the action to open the hyperlink at the caret location or to display a chooser
+ * if more than one hyperlink is available.
+ * Value: <code>"OpenHyperlink"</code>
+ * @since 3.7
+ */
+ public static String OPEN_HYPERLINK= "OpenHyperlink"; //$NON-NLS-1$
+}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipselabs/tapiji/translator/rap/supplemental/Activator.java b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipselabs/tapiji/translator/rap/supplemental/Activator.java
new file mode 100644
index 00000000..be2b0e3f
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap.supplemental/src/org/eclipselabs/tapiji/translator/rap/supplemental/Activator.java
@@ -0,0 +1,30 @@
+package org.eclipselabs.tapiji.translator.rap.supplemental;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ private static BundleContext context;
+
+ static BundleContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext bundleContext) throws Exception {
+ Activator.context = bundleContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext bundleContext) throws Exception {
+ Activator.context = null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF
index 855f826c..d207a626 100644
--- a/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF
@@ -1,11 +1,9 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: TranslatorRAP
+Bundle-Name: RAP fragment for TapiJI Translator
Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap;singleton:=true
-Bundle-Version: 1.0.0.qualifier
+Bundle-Version: 0.0.2.qualifier
+Fragment-Host: org.eclipselabs.tapiji.translator;bundle-version="0.0.2"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Require-Bundle: org.eclipse.rap.ui;bundle-version="1.5.0",
- org.eclipse.rap.ui.views;bundle-version="1.5.0",
- org.eclipse.rap.rwt.supplemental.filedialog;bundle-version="1.5.0",
- org.junit;bundle-version="3.8.2",
- org.eclipselabs.tapiji.translator.rap.rbe;bundle-version="0.0.2"
+Require-Bundle: org.eclipse.rap.ui
+Export-Package: org.eclipselabs.tapiji.translator.views.widgets.provider;uses:="org.eclipse.ui,org.eclipse.jface.viewers"
diff --git a/org.eclipselabs.tapiji.translator.rap/build.properties b/org.eclipselabs.tapiji.translator.rap/build.properties
index e9863e28..e3023e14 100644
--- a/org.eclipselabs.tapiji.translator.rap/build.properties
+++ b/org.eclipselabs.tapiji.translator.rap/build.properties
@@ -2,4 +2,4 @@ source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
- plugin.xml
+ fragment.xml
diff --git a/org.eclipselabs.tapiji.translator.rap/fragment.xml b/org.eclipselabs.tapiji.translator.rap/fragment.xml
new file mode 100644
index 00000000..5f413ff2
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap/fragment.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<fragment>
+ <extension
+ point="org.eclipse.rap.ui.entrypoint">
+ <entrypoint
+ class="org.eclipselabs.tapiji.translator.rap.TranslatorEntryPoint"
+ id="org.eclipselabs.tapiji.translator.rap.entrypoint"
+ parameter="translator">
+ </entrypoint>
+ </extension>
+
+</fragment>
diff --git a/org.eclipselabs.tapiji.translator.rap/plugin.xml b/org.eclipselabs.tapiji.translator.rap/plugin.xml
deleted file mode 100644
index 26f4838b..00000000
--- a/org.eclipselabs.tapiji.translator.rap/plugin.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.rap.ui.entrypoint">
- <entrypoint
- class="org.eclipselabs.tapiji.translator.rap.TranslatorEntryPoint"
- id="org.eclipselabs.tapiji.translator.rap.entrypoint"
- parameter="translator">
- </entrypoint>
- </extension>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- class="org.eclipselabs.tapiji.translator.rap.Perspective"
- id="org.eclipselabs.tapiji.translator.rap.perspective"
- name="Perspective">
- </perspective>
- </extension>
- <extension
- point="org.eclipse.ui.views">
- <category
- id="org.eclipselabs.tapiji.translator.rap"
- name="Internationalization">
- </category>
- <view
- category="org.eclipselabs.tapiji.translator.rap"
- class="org.eclipselabs.tapiji.translator.rap.views.GlossaryView"
- icon="icons/sample.gif"
- id="org.eclipselabs.tapiji.translator.rap.views.GlossaryView"
- name="Glossary"
- restorable="true">
- </view>
- </extension>
-
-</plugin>
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Activator.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Activator.java
deleted file mode 100644
index 5418856f..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Activator.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Application.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Application.java
deleted file mode 100644
index bbb40d29..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Application.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.equinox.app.IApplication;
-import org.eclipse.equinox.app.IApplicationContext;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class controls all aspects of the application's execution
- */
-public class Application implements IApplication {
-
- /* (non-Javadoc)
- * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
- */
- public Object start(IApplicationContext context) {
- Display display = PlatformUI.createDisplay();
- try {
- int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
- if (returnCode == PlatformUI.RETURN_RESTART) {
- return IApplication.EXIT_RESTART;
- }
- return IApplication.EXIT_OK;
- } finally {
- display.dispose();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.equinox.app.IApplication#stop()
- */
- public void stop() {
- if (!PlatformUI.isWorkbenchRunning())
- return;
- final IWorkbench workbench = PlatformUI.getWorkbench();
- final Display display = workbench.getDisplay();
- display.syncExec(new Runnable() {
- public void run() {
- if (!display.isDisposed())
- workbench.close();
- }
- });
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationActionBarAdvisor.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationActionBarAdvisor.java
deleted file mode 100644
index 6b924d25..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationActionBarAdvisor.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.ICoolBarManager;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarContributionItem;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ContributionItemFactory;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-
-/**
- * An action bar advisor is responsible for creating, adding, and disposing of
- * the actions added to a workbench window. Each window will be populated with
- * new actions.
- */
-public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
-
- public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
- super(configurer);
- }
-
- @Override
- protected void fillCoolBar(ICoolBarManager coolBar) {
- super.fillCoolBar(coolBar);
-
- coolBar.add(new GroupMarker("group.file"));
- {
- // File Group
- IToolBarManager fileToolBar = new ToolBarManager(coolBar.getStyle());
-
- fileToolBar.add(new Separator(IWorkbenchActionConstants.NEW_GROUP));
- fileToolBar.add(new GroupMarker(IWorkbenchActionConstants.OPEN_EXT));
-
- fileToolBar.add(new GroupMarker(IWorkbenchActionConstants.SAVE_GROUP));
- fileToolBar.add(getAction(ActionFactory.SAVE.getId()));
-
- // Add to the cool bar manager
- coolBar.add(new ToolBarContributionItem(fileToolBar,IWorkbenchActionConstants.TOOLBAR_FILE));
- }
-
- coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR));
- }
-
- @Override
- protected void fillMenuBar(IMenuManager menuBar) {
- super.fillMenuBar(menuBar);
-
- menuBar.add(fileMenu());
- menuBar.add(new GroupMarker (IWorkbenchActionConstants.MB_ADDITIONS));
- menuBar.add(helpMenu());
- }
-
- private MenuManager helpMenu () {
- MenuManager helpMenu = new MenuManager ("&Help", IWorkbenchActionConstants.M_HELP);
-
- //TODO: 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));
- //TODO: 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.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationWorkbenchAdvisor.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationWorkbenchAdvisor.java
deleted file mode 100644
index 1cac4e6b..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationWorkbenchAdvisor.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.ui.application.IWorkbenchConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchAdvisor;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
-
- private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective";
-
- public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer) {
- return new ApplicationWorkbenchWindowAdvisor(configurer);
- }
-
- public String getInitialWindowPerspectiveId() {
- return PERSPECTIVE_ID;
- }
-
- @Override
- public void initialize(IWorkbenchConfigurer configurer) {
- super.initialize(configurer);
- configurer.setSaveAndRestore(true);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationWorkbenchWindowAdvisor.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationWorkbenchWindowAdvisor.java
deleted file mode 100644
index 4375da4f..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/ApplicationWorkbenchWindowAdvisor.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ShellAdapter;
-import org.eclipse.swt.events.ShellEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Tray;
-import org.eclipse.swt.widgets.TrayItem;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.eclipselabs.tapiji.translator.rap.utils.FileUtils;
-
-
-public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
-
- /** Workbench state **/
- private IWorkbenchWindow window;
-
- /** System tray item / icon **/
- private TrayItem trayItem;
- private Image trayImage;
-
- /** Command ids **/
- private final static String COMMAND_ABOUT_ID = "org.eclipse.ui.help.aboutAction";
- private final static String COMMAND_EXIT_ID = "org.eclipse.ui.file.exit";
-
- public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
- super(configurer);
- }
-
- public ActionBarAdvisor createActionBarAdvisor(
- IActionBarConfigurer configurer) {
- return new ApplicationActionBarAdvisor(configurer);
- }
-
- public void preWindowOpen() {
- IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
- configurer.setShowFastViewBars(true);
- configurer.setShowCoolBar(true);
- configurer.setShowStatusLine(true);
- configurer.setInitialSize(new Point (1024, 768));
-
- /** Init workspace and container project */
- /*TODO: try {
- FileUtils.getProject();
- } catch (CoreException e) {
- }*/
- }
-
- @Override
- public void postWindowOpen() {
- super.postWindowOpen();
- window = getWindowConfigurer().getWindow();
-
- /** Add the application into the system tray icon section **/
- trayItem = initTrayItem (window);
-
- // If tray items are not supported by the operating system
- if (trayItem != null) {
-
- // minimize / maximize action
- window.getShell().addShellListener(new ShellAdapter() {
- public void shellIconified (ShellEvent e) {
- window.getShell().setMinimized(true);
- window.getShell().setVisible(false);
- }
- });
-
- trayItem.addListener(SWT.DefaultSelection, new Listener() {
- public void handleEvent (Event event) {
- Shell shell = window.getShell();
- if (!shell.isVisible() || window.getShell().getMinimized()) {
- window.getShell().setMinimized(false);
- shell.setVisible(true);
- }
- }
- });
-
- // Add actions menu
- hookActionsMenu ();
- }
- }
-
- private void hookActionsMenu () {
- trayItem.addListener (SWT.MenuDetect, new Listener () {
- @Override
- public void handleEvent(Event event) {
- Menu menu = new Menu (window.getShell(), SWT.POP_UP);
-
- MenuItem about = new MenuItem (menu, SWT.None);
- about.setText("&�ber");
- about.addListener(SWT.Selection, new Listener () {
-
- @Override
- public void handleEvent(Event event) {
- try {
- IHandlerService handlerService = (IHandlerService) window.getService(IHandlerService.class);
- handlerService.executeCommand(COMMAND_ABOUT_ID, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- });
-
- MenuItem sep = new MenuItem (menu, SWT.SEPARATOR);
-
- // Add exit action
- MenuItem exit = new MenuItem (menu, SWT.NONE);
- exit.setText("Exit");
- exit.addListener (SWT.Selection, new Listener() {
- @Override
- public void handleEvent(Event event) {
- // Perform a call to the exit command
- IHandlerService handlerService = (IHandlerService) window.getService(IHandlerService.class);
- try {
- handlerService.executeCommand (COMMAND_EXIT_ID, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
-
- menu.setVisible(true);
- }
- });
- }
-
- private TrayItem initTrayItem (IWorkbenchWindow window) {
- final Tray osTray = window.getShell().getDisplay().getSystemTray();
- TrayItem item = new TrayItem (osTray, SWT.None);
-
- trayImage = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "/icons/TapiJI_32.png").createImage();
- item.setImage(trayImage);
- item.setToolTipText("TapiJI - Translator");
-
- return item;
- }
-
- @Override
- public void dispose() {
- try {
- super.dispose();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- try {
- if (trayImage != null)
- trayImage.dispose();
- if (trayItem != null)
- trayItem.dispose();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void postWindowClose() {
- super.postWindowClose();
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Perspective.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Perspective.java
deleted file mode 100644
index aa58ce29..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/Perspective.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-import org.eclipselabs.tapiji.translator.rap.views.GlossaryView;
-
-
-public class Perspective implements IPerspectiveFactory {
-
- public void createInitialLayout(IPageLayout layout) {
- layout.setEditorAreaVisible(true);
- layout.setFixed(true);
-
- initEditorArea (layout);
- initViewsArea (layout);
- }
-
- private void initViewsArea(IPageLayout layout) {
- layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM, .6f, IPageLayout.ID_EDITOR_AREA);
- }
-
- private void initEditorArea(IPageLayout layout) {
-
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorEntryPoint.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorEntryPoint.java
index 20aebca0..ac139289 100644
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorEntryPoint.java
+++ b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorEntryPoint.java
@@ -4,13 +4,14 @@
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.WorkbenchAdvisor;
+import org.eclipselabs.tapiji.translator.ApplicationWorkbenchAdvisor;
public class TranslatorEntryPoint implements IEntryPoint {
@Override
public int createUI() {
Display display = PlatformUI.createDisplay();
- WorkbenchAdvisor advisor = new TranslatorWorkbenchAdvisor();
+ WorkbenchAdvisor advisor = new ApplicationWorkbenchAdvisor();
return PlatformUI.createAndRunWorkbench(display, advisor);
}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorWorkbenchAdvisor.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorWorkbenchAdvisor.java
deleted file mode 100644
index 926c4a02..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/TranslatorWorkbenchAdvisor.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap;
-
-import org.eclipse.ui.application.WorkbenchAdvisor;
-
-public class TranslatorWorkbenchAdvisor extends WorkbenchAdvisor {
-
- private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.rap.perspective";
-
- @Override
- public String getInitialWindowPerspectiveId() {
- return PERSPECTIVE_ID;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/FileOpenAction.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/FileOpenAction.java
deleted file mode 100644
index 2b41e0fc..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/FileOpenAction.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-//TODO: import org.eclipse.ui.part.FileEditorInput;
-import org.eclipselabs.tapiji.translator.rap.utils.FileUtils;
-
-
-public class FileOpenAction extends Action implements IWorkbenchWindowActionDelegate {
-
- /** Editor ids **/
- public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor";
-
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "Open Resource-Bundle", SWT.OPEN, new String[] {"*.properties"} );
- if (!FileUtils.isResourceBundle(fileName)) {
- MessageDialog.openError(window.getShell(),
- "Cannot open Resource-Bundle", "The choosen file does not represent a Resource-Bundle!");
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- /*TODO: try {
- page.openEditor(new FileEditorInput(FileUtils.getResourceBundleRef(fileName)),
- RESOURCE_BUNDLE_EDITOR);
-
- } catch (CoreException e) {
- e.printStackTrace();
- }*/
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/NewGlossaryAction.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/NewGlossaryAction.java
deleted file mode 100644
index 3d0ff2dc..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/NewGlossaryAction.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.actions;
-
-import java.io.File;
-import java.text.MessageFormat;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipselabs.tapiji.translator.rap.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.rap.utils.FileUtils;
-
-
-public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window */
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "New Glossary", SWT.SAVE, new String[] {"*.xml"} );
-
- if (!fileName.endsWith(".xml")) {
- if (fileName.endsWith("."))
- fileName += "xml";
- else
- fileName += ".xml";
- }
-
- if (new File (fileName).exists()) {
- String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?";
- MessageFormat mf = new MessageFormat(recallPattern);
-
- if (!MessageDialog.openQuestion(window.getShell(),
- "File already exists!", mf.format(new String[] {fileName})))
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- GlossaryManager.newGlossary (new File (fileName));
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- }
-
- @Override
- public void dispose() {
- this.window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/OpenGlossaryAction.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/OpenGlossaryAction.java
deleted file mode 100644
index 522b30bb..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/actions/OpenGlossaryAction.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.actions;
-
-import java.io.File;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipselabs.tapiji.translator.rap.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.rap.utils.FileUtils;
-
-
-public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window */
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "Open Glossary", SWT.OPEN, new String[] {"*.xml"} );
- if (!FileUtils.isGlossary(fileName)) {
- MessageDialog.openError(window.getShell(),
- "Cannot open Glossary", "The choosen file does not represent a Glossary!");
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- if (fileName != null) {
- GlossaryManager.loadGlossary(new File (fileName));
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- }
-
- @Override
- public void dispose() {
- this.window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/GlossaryManager.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/GlossaryManager.java
deleted file mode 100644
index 72b5df28..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/GlossaryManager.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.core;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-
-
-public class GlossaryManager {
-
- private Glossary glossary;
- private File file;
- private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener> ();
-
- public GlossaryManager (File file, boolean overwrite) throws Exception {
- this.file = file;
-
- if (file.exists() && !overwrite) {
- // load the existing glossary
- glossary = new Glossary();
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Unmarshaller unmarshaller = context.createUnmarshaller();
- glossary = (Glossary) unmarshaller.unmarshal(file);
- } else {
- // Create a new glossary
- glossary = new Glossary ();
- saveGlossary();
- }
- }
-
- public void saveGlossary () throws Exception {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16");
-
- OutputStream fout = new FileOutputStream (file.getAbsolutePath());
- OutputStream bout = new BufferedOutputStream (fout);
- marshaller.marshal(glossary, new OutputStreamWriter (bout, "UTF-16"));
- }
-
- public void setGlossary (Glossary glossary) {
- this.glossary = glossary;
- }
-
- public Glossary getGlossary () {
- return glossary;
- }
-
- public static void loadGlossary (File file) {
- /* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
- for (ILoadGlossaryListener listener : loadGlossaryListeners) {
- listener.glossaryLoaded(event);
- }
- }
-
- public static void registerLoadGlossaryListener (ILoadGlossaryListener listener) {
- loadGlossaryListeners.add(listener);
- }
-
- public static void unregisterLoadGlossaryListener (ILoadGlossaryListener listener) {
- loadGlossaryListeners.remove(listener);
- }
-
- public static void newGlossary(File file) {
- /* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
- event.setNewGlossary(true);
- for (ILoadGlossaryListener listener : loadGlossaryListeners) {
- listener.glossaryLoaded(event);
- }
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/ILoadGlossaryListener.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/ILoadGlossaryListener.java
deleted file mode 100644
index 10aa6771..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/ILoadGlossaryListener.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.core;
-
-public interface ILoadGlossaryListener {
-
- void glossaryLoaded (LoadGlossaryEvent event);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/LoadGlossaryEvent.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/LoadGlossaryEvent.java
deleted file mode 100644
index ad5b1565..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/core/LoadGlossaryEvent.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.core;
-
-import java.io.File;
-
-public class LoadGlossaryEvent {
-
- private boolean newGlossary = false;
- private File glossaryFile;
-
- public LoadGlossaryEvent (File glossaryFile) {
- this.glossaryFile = glossaryFile;
- }
-
- public File getGlossaryFile() {
- return glossaryFile;
- }
-
- public void setNewGlossary(boolean newGlossary) {
- this.newGlossary = newGlossary;
- }
-
- public boolean isNewGlossary() {
- return newGlossary;
- }
-
- public void setGlossaryFile(File glossaryFile) {
- this.glossaryFile = glossaryFile;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Glossary.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Glossary.java
deleted file mode 100644
index c913e611..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Glossary.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class Glossary implements Serializable {
-
- private static final long serialVersionUID = 2070750758712154134L;
-
- public Info info;
-
- @XmlElementWrapper (name="terms")
- @XmlElement (name = "term")
- public List<Term> terms;
-
- public Glossary() {
- terms = new ArrayList <Term> ();
- info = new Info();
- }
-
- public Term[] getAllTerms () {
- return terms.toArray(new Term [terms.size()]);
- }
-
- public int getIndexOfLocale(String referenceLocale) {
- int i = 0;
-
- for (String locale : info.translations) {
- if (locale.equalsIgnoreCase(referenceLocale))
- return i;
- i++;
- }
-
- return 0;
- }
-
- public void removeTerm(Term elem) {
- for (Term term : terms) {
- if (term == elem) {
- terms.remove(term);
- break;
- }
-
- if (term.removeTerm (elem))
- break;
- }
- }
-
- public void addTerm(Term parentTerm, Term newTerm) {
- if (parentTerm == null) {
- this.terms.add(newTerm);
- return;
- }
-
- for (Term term : terms) {
- if (term == parentTerm) {
- term.subTerms.add(newTerm);
- break;
- }
-
- if (term.addTerm (parentTerm, newTerm))
- break;
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Info.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Info.java
deleted file mode 100644
index 2725b5e7..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Info.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-public class Info implements Serializable {
-
- private static final long serialVersionUID = 8607746669906026928L;
-
- @XmlElementWrapper (name = "locales")
- @XmlElement (name = "locale")
- public List<String> translations;
-
- public Info () {
- this.translations = new ArrayList<String>();
-
- // Add the default Locale
- this.translations.add("Default");
- }
-
- public String[] getTranslations () {
- return translations.toArray(new String [translations.size()]);
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Term.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Term.java
deleted file mode 100644
index d05fdb86..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Term.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlTransient;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-public class Term implements Serializable {
-
- private static final long serialVersionUID = 7004998590181568026L;
-
- @XmlElementWrapper (name = "translations")
- @XmlElement (name = "translation")
- public List<Translation> translations;
-
- @XmlElementWrapper (name = "terms")
- @XmlElement (name = "term")
- public List<Term> subTerms;
-
- public Term parentTerm;
-
- @XmlTransient
- private Object info;
-
- public Term () {
- translations = new ArrayList<Translation> ();
- subTerms = new ArrayList<Term> ();
- parentTerm = null;
- info = null;
- }
-
- public void setInfo(Object info) {
- this.info = info;
- }
-
- public Object getInfo() {
- return info;
- }
-
- public Term[] getAllSubTerms () {
- return subTerms.toArray(new Term[subTerms.size()]);
- }
-
- public Term getParentTerm() {
- return parentTerm;
- }
-
- public boolean hasChildTerms () {
- return subTerms != null && subTerms.size() > 0;
- }
-
- public Translation[] getAllTranslations() {
- return translations.toArray(new Translation [translations.size()]);
- }
-
- public Translation getTranslation (String language) {
- for (Translation translation : translations) {
- if (translation.id.equalsIgnoreCase(language))
- return translation;
- }
-
- Translation newTranslation = new Translation ();
- newTranslation.id = language;
- translations.add(newTranslation);
-
- return newTranslation;
- }
-
- public boolean removeTerm(Term elem) {
- boolean hasFound = false;
- for (Term subTerm : subTerms) {
- if (subTerm == elem) {
- subTerms.remove(elem);
- hasFound = true;
- break;
- } else {
- hasFound = subTerm.removeTerm(elem);
- if (hasFound)
- break;
- }
- }
- return hasFound;
- }
-
- public boolean addTerm(Term parentTerm, Term newTerm) {
- boolean hasFound = false;
- for (Term subTerm : subTerms) {
- if (subTerm == parentTerm) {
- subTerms.add(newTerm);
- hasFound = true;
- break;
- } else {
- hasFound = subTerm.addTerm(parentTerm, newTerm);
- if (hasFound)
- break;
- }
- }
- return hasFound;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Translation.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Translation.java
deleted file mode 100644
index 32291e0a..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/model/Translation.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.model;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-@XmlType (name = "Translation")
-public class Translation implements Serializable {
-
- private static final long serialVersionUID = 2033276999496196690L;
-
- public String id;
-
- public String value;
-
- public Translation () {
- id = "";
- value = "";
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/tests/JaxBTest.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/tests/JaxBTest.java
deleted file mode 100644
index ed0cf314..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/tests/JaxBTest.java
+++ /dev/null
@@ -1,126 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.tests;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.util.ArrayList;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-import org.eclipselabs.tapiji.translator.rap.model.Info;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-
-import junit.framework.TestCase;;
-
-
-public class JaxBTest extends TestCase {
-
-
- 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();
- assertFalse(true);
- }
- }
-
- 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();
- assertFalse(true);
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/utils/FileUtils.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/utils/FileUtils.java
deleted file mode 100644
index 0fc0d3fe..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/utils/FileUtils.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.utils;
-
-import java.io.File;
-
-/*TODO: import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;*/
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-
-public class FileUtils {
-
- /** Token to replace in a regular expression with a bundle name. */
- private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME";
- /** Token to replace in a regular expression with a file extension. */
- private static final String TOKEN_FILE_EXTENSION =
- "FILEEXTENSION";
- /** Regex to match a properties file. */
- private static final String PROPERTIES_FILE_REGEX =
- "^(" + TOKEN_BUNDLE_NAME + ")"
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + TOKEN_FILE_EXTENSION + ")$";
-
- /** The singleton instance of Workspace */
- //TODO: private static IWorkspace workspace;
-
- /** Wrapper project for external file resources */
- //TODO: 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");
- }
-
- /*TODO: public static IWorkspace getWorkspace () {
- if (workspace == null) {
- workspace = ResourcesPlugin.getWorkspace();
- }
-
- return workspace;
- }*/
-
- /*TODO: 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;
- }*/
-
- /*TODO: public static void prePareEditorInputs () {
- IWorkspace workspace = getWorkspace();
- }*/
-
- /*TODO: public static IFile getResourceBundleRef (String location) throws CoreException {
- IPath path = new Path (location);
-
- /** Create all files of the Resource-Bundle within the project space and link them to the original file */
- /*String regex = getPropertiesFileRegEx(path);
- String projPathName = toProjectRelativePathName(path);
- IFile file = getProject().getFile(projPathName);
- file.createLink(path, IResource.REPLACE, null);
-
- File parentDir = new File (path.toFile().getParent());
- String[] files = parentDir.list();
-
- for (String fn : files) {
- File fo = new File (parentDir, fn);
- if (!fo.isFile())
- continue;
-
- IPath newFilePath = new Path(fo.getAbsolutePath());
- if (fo.getName().matches(regex) && !path.toFile().getName().equals(newFilePath.toFile().getName())) {
- IFile newFile = project.getFile(toProjectRelativePathName(newFilePath));
- newFile.createLink(newFilePath, IResource.REPLACE, null);
- }
- }
-
- return file;
- }*/
-
- protected static String toProjectRelativePathName (IPath path) {
- String projectRelativeName = "";
-
- projectRelativeName = path.toString().replaceAll(":", "");
- projectRelativeName = projectRelativeName.replaceAll("/", ".");
-
- return projectRelativeName;
- }
-
- protected static String getPropertiesFileRegEx(IPath file) {
- String bundleName = getBundleName(file);
- return PROPERTIES_FILE_REGEX.replaceFirst(
- TOKEN_BUNDLE_NAME, bundleName).replaceFirst(
- TOKEN_FILE_EXTENSION, file.getFileExtension());
- }
-
- public static String getBundleName(IPath file) {
- String name = file.toFile().getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + file.getFileExtension() + ")$";
- return name.replaceFirst(regex, "$1");
- }
-
- public static String queryFileName(Shell shell, String title, int dialogOptions, String[] endings) {
- FileDialog dialog= new FileDialog(shell, dialogOptions);
- dialog.setText( title );
- dialog.setFilterExtensions(endings);
- String path= dialog.open();
-
-
- if (path != null && path.length() > 0)
- return path;
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/utils/FontUtils.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/utils/FontUtils.java
deleted file mode 100644
index 8f2d57b2..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/utils/FontUtils.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.utils;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.rap.Activator;
-
-
-public class FontUtils {
-
- /**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
-
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/GlossaryView.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/GlossaryView.java
deleted file mode 100644
index c263f241..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/GlossaryView.java
+++ /dev/null
@@ -1,667 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views;
-
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Scale;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.dialogs.ListSelectionDialog;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipselabs.tapiji.translator.rap.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.rap.core.ILoadGlossaryListener;
-import org.eclipselabs.tapiji.translator.rap.core.LoadGlossaryEvent;
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-import org.eclipselabs.tapiji.translator.rap.views.dialog.LocaleContentProvider;
-import org.eclipselabs.tapiji.translator.rap.views.dialog.LocaleLabelProvider;
-import org.eclipselabs.tapiji.translator.rap.views.menus.GlossaryEntryMenuContribution;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.GlossaryWidget;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.model.GlossaryViewState;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.provider.GlossaryLabelProvider;
-
-
-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.rap.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 () {
- /** 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);
- }
-
- 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());
-
- }
- 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;
- }
-
- 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());
- }
-
- // 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();
- }
- 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();
- }
- };
- 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());
- }
-
- 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());
- }
-
- manager.add(enableFuzzyMatching);
- manager.add(editable);
-
- if (this.glossary != null && this.glossary.getGlossary() != null) {
- manager.add(new Separator());
- manager.add(newTranslation);
- manager.add(deleteTranslation);
- createMenuAdditions (manager);
- }
- }
-
- /*** 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);
- }
-
- createMenuAdditions (manager);
- }
-
- 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());
- }
-
- showMenu.add(showAll);
- showMenu.add(showSelectiveContent);
-
- manager.add(showMenu);
- }
-
- 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);
- }
- }
-
- 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);
- }
- }
-
- for (Action a : displayActions) {
- displayMenu.add(a);
- }
-
- 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!");
- }
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/dialog/LocaleContentProvider.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/dialog/LocaleContentProvider.java
deleted file mode 100644
index f304ecef..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/dialog/LocaleContentProvider.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.dialog;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-public class LocaleContentProvider implements IStructuredContentProvider {
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
-
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof List) {
- List<Locale> locales = (List<Locale>) inputElement;
- return locales.toArray(new Locale[locales.size()]);
- }
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/dialog/LocaleLabelProvider.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/dialog/LocaleLabelProvider.java
deleted file mode 100644
index 1114f351..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/dialog/LocaleLabelProvider.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.dialog;
-
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Image;
-
-public class LocaleLabelProvider implements ILabelProvider {
-
- @Override
- public void addListener(ILabelProviderListener listener) {
-
- }
-
- @Override
- public void dispose() {
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
-
- }
-
- @Override
- public Image getImage(Object element) {
- // TODO add image output for Locale entries
- return null;
- }
-
- @Override
- public String getText(Object element) {
- if (element != null && element instanceof Locale)
- return ((Locale)element).getDisplayName();
-
- return null;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/menus/GlossaryEntryMenuContribution.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/menus/GlossaryEntryMenuContribution.java
deleted file mode 100644
index fa3ca457..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/menus/GlossaryEntryMenuContribution.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.menus;
-
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.GlossaryWidget;
-
-
-public class GlossaryEntryMenuContribution extends ContributionItem implements
- ISelectionChangedListener {
-
- private GlossaryWidget parentView;
- private boolean legalSelection = false;
-
- // Menu-Items
- private MenuItem addItem;
- private MenuItem removeItem;
-
- public GlossaryEntryMenuContribution () {
- }
-
- public GlossaryEntryMenuContribution (GlossaryWidget view, boolean legalSelection) {
- this.legalSelection = legalSelection;
- this.parentView = view;
- parentView.addSelectionChangedListener(this);
- }
-
- @Override
- public void fill(Menu menu, int index) {
-
- // MenuItem for adding a new entry
- addItem = new MenuItem(menu, SWT.NONE, index);
- addItem.setText("Add ...");
- addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
- addItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.addNewItem();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
-
- if ((parentView == null && legalSelection) || parentView != null) {
- // MenuItem for deleting the currently selected entry
- removeItem = new MenuItem(menu, SWT.NONE, index + 1);
- removeItem.setText("Remove");
- removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
- .createImage());
- removeItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.deleteSelectedItems();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
- enableMenuItems();
- }
- }
-
- protected void enableMenuItems() {
- try {
- removeItem.setEnabled(legalSelection);
- } catch (Exception e) {
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- legalSelection = !event.getSelection().isEmpty();
-// enableMenuItems ();
- }
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/GlossaryWidget.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/GlossaryWidget.java
deleted file mode 100644
index aea2398e..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/GlossaryWidget.java
+++ /dev/null
@@ -1,630 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets;
-
-import java.awt.ComponentOrientation;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-/* TODO: import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;*/
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipselabs.tapiji.translator.rap.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.dnd.GlossaryDragSource;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.dnd.GlossaryDropTarget;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.dnd.TermTransfer;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.filter.ExactMatcher;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.filter.FuzzyMatcher;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.filter.SelectiveMatcher;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.provider.GlossaryContentProvider;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.provider.GlossaryLabelProvider;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.sorter.GlossaryEntrySorter;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.sorter.SortInfo;
-
-
-public class GlossaryWidget extends Composite /*TODO: implements IResourceChangeListener*/ {
-
- private final int TERM_COLUMN_WEIGHT = 1;
- private final int DESCRIPTION_COLUMN_WEIGHT = 1;
-
- private boolean editable;
-
- private IWorkbenchPartSite site;
- private TreeColumnLayout basicLayout;
- private TreeViewer treeViewer;
- private TreeColumn termColumn;
- private boolean grouped = true;
- private boolean fuzzyMatchingEnabled = false;
- private boolean selectiveViewEnabled = false;
- private float matchingPrecision = .75f;
- private String referenceLocale;
- private List<String> displayedTranslations;
- private String[] translationsToDisplay;
-
- private SortInfo sortInfo;
- private Glossary glossary;
- private GlossaryManager manager;
-
- private GlossaryContentProvider contentProvider;
- private GlossaryLabelProvider labelProvider;
-
- /*** MATCHER ***/
- ExactMatcher matcher;
-
- /*** SORTER ***/
- GlossaryEntrySorter sorter;
-
- /*** ACTIONS ***/
- private Action doubleClickAction;
-
- public GlossaryWidget(IWorkbenchPartSite site,
- Composite parent, int style, GlossaryManager manager, String refLang, List<String> dls) {
- super(parent, style);
- this.site = site;
-
- if (manager != null) {
- this.manager = manager;
- this.glossary = manager.getGlossary();
-
- if (refLang != null)
- this.referenceLocale = refLang;
- else
- this.referenceLocale = glossary.info.getTranslations()[0];
-
- if (dls != null)
- this.translationsToDisplay = dls.toArray(new String[dls.size()]);
- else
- this.translationsToDisplay = glossary.info.getTranslations();
- }
-
- constructWidget();
-
- if (this.glossary!= null) {
- initTreeViewer();
- initMatchers();
- initSorters();
- }
-
- hookDragAndDrop();
- registerListeners();
- }
-
- protected void registerListeners() {
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyPressed (KeyEvent event) {
- if (event.character == SWT.DEL &&
- event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
-
- // Listen resource changes
- //TODO: 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;//TODO: 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);//TODO: SWT.RIGHT_TO_LEFT/*getOrientation(l)*/);
-
- termColumn.setText(l.getDisplayName());
- TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn);
- termCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- if (element instanceof Term) {
- Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(referenceLocale);
-
- if (translation != null) {
- translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
- manager.setGlossary(gl);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- treeViewer.refresh();
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, 0);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
- termColumn.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(termColumn, new ColumnWeightData(
- TERM_COLUMN_WEIGHT));
-
-
- /** Translations */
- String[] allLocales = this.translationsToDisplay;
-
- int iCol = 1;
- for (String locale : allLocales) {
- final int ifCall = iCol;
- final String sfLocale = locale;
- if (locale.equalsIgnoreCase(this.referenceLocale))
- continue;
-
- // trac the rendered translation
- this.displayedTranslations.add(locale);
-
- String [] locDef = locale.split("_");
- l = locDef.length < 3 ? (locDef.length < 2 ? new Locale (locDef[0]) : new Locale(locDef[0], locDef[1])) : new Locale (locDef[0], locDef[1], locDef[2]);
-
- // Add editing support to this table column
- TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE);
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, descriptionColumn);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- if (element instanceof Term) {
- Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(sfLocale);
-
- if (translation != null) {
- translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
- manager.setGlossary(gl);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- treeViewer.refresh();
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, ifCall);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
-
- descriptionColumn.setText(l.getDisplayName());
- descriptionColumn.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(ifCall);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(ifCall);
- }
- });
- basicLayout.setColumnData(descriptionColumn, new ColumnWeightData(
- DESCRIPTION_COLUMN_WEIGHT));
- iCol ++;
- }
-
- }
-
- protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sorter.setSortInfo(sortInfo);
- setTreeStructure(idx == 0);
- treeViewer.refresh();
- }
-
- @Override
- public boolean setFocus() {
- return treeViewer.getControl().setFocus();
- }
-
- /*** DRAG AND DROP ***/
- protected void hookDragAndDrop() {
- GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager);
- GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager);
-
- // Initialize drag source for copy event
- DragSource dragSource = new DragSource(treeViewer.getControl(),
- DND.DROP_MOVE);
- dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() });
- dragSource.addDragListener(source);
-
- // Initialize drop target for copy event
- DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
- DND.DROP_MOVE);
- dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() });
- dropTarget.addDropListener(target);
- }
-
- /*** ACTIONS ***/
-
- private void makeActions() {
- doubleClickAction = new Action() {
-
- @Override
- public void run() {
- // implement the cell edit event
- }
-
- };
- }
-
- private void hookDoubleClickAction() {
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
- }
-
- /*** SELECTION LISTENER ***/
-
-
- private void refreshViewer() {
- treeViewer.refresh();
- }
-
- public StructuredViewer getViewer() {
- return this.treeViewer;
- }
-
- public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- if (matcher.getPattern().trim().length() > 0)
- grouped = false;
- else
- grouped = true;
- labelProvider.setSearchEnabled(!grouped);
- this.setTreeStructure(grouped && sorter != null && sorter.getSortInfo().getColIdx() == 0);
- treeViewer.refresh();
- }
-
- public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- setTreeStructure(sortInfo.getColIdx() == 0);
- treeViewer.refresh();
- }
- }
-
- public String getSearchString() {
- return matcher.getPattern();
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public void deleteSelectedItems() {
- List<String> ids = new ArrayList<String>();
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
- ISelection selection = site.getSelectionProvider().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof Term) {
- this.glossary.removeTerm ((Term)elem);
- this.manager.setGlossary(this.glossary);
- try {
- this.manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- this.refreshViewer();
- }
-
- public void addNewItem() {
- //TODO: event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- Term parentTerm = null;
-
- ISelection selection = site.getSelectionProvider().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof Term) {
- parentTerm = ((Term) elem);
- break;
- }
- }
- }
-
- InputDialog dialog = new InputDialog (this.getShell(), "Neuer Begriff",
- "Please, define the new term:", "", null);
-
- if (dialog.open() == InputDialog.OK) {
- if (dialog.getValue() != null && dialog.getValue().trim().length() > 0) {
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
- // Construct a new term
- Term newTerm = new Term();
- Translation defaultTranslation = new Translation ();
- defaultTranslation.id = referenceLocale;
- defaultTranslation.value = dialog.getValue();
- newTerm.translations.add(defaultTranslation);
-
- this.glossary.addTerm (parentTerm, newTerm);
-
- this.manager.setGlossary(this.glossary);
- try {
- this.manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- this.refreshViewer();
- }
-
- public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public Control getControl() {
- return treeViewer.getControl();
- }
-
- public Glossary getGlossary () {
- return this.glossary;
- }
-
- public void addSelectionChangedListener(
- ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- }
-
- public String getReferenceLanguage() {
- return referenceLocale;
- }
-
- public void setReferenceLanguage (String lang) {
- this.referenceLocale = lang;
- }
-
- public void bindContentToSelection(boolean enable) {
- this.selectiveViewEnabled = enable;
- initMatchers();
- }
-
- public boolean isSelectiveViewEnabled() {
- return selectiveViewEnabled;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- //TODO: ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- }
-
- /*TODO: @Override
- public void resourceChanged(IResourceChangeEvent event) {
- initMatchers();
- this.refreshViewer();
- }*/
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/GlossaryDragSource.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/GlossaryDragSource.java
deleted file mode 100644
index 134cf66e..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/GlossaryDragSource.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.dnd;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipselabs.tapiji.translator.rap.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.provider.GlossaryContentProvider;
-
-
-public class GlossaryDragSource implements DragSourceListener {
-
- private final TreeViewer source;
- private final GlossaryManager manager;
- private List<Term> selectionList;
-
- public GlossaryDragSource (TreeViewer sourceView, GlossaryManager manager) {
- source = sourceView;
- this.manager = manager;
- this.selectionList = new ArrayList<Term>();
- }
-
- @Override
- public void dragFinished(DragSourceEvent event) {
- GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source.getContentProvider());
- Glossary glossary = contentProvider.getGlossary();
- for (Term selectionObject : selectionList)
- glossary.removeTerm(selectionObject);
- manager.setGlossary(glossary);
- this.source.refresh();
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void dragSetData(DragSourceEvent event) {
- selectionList = new ArrayList<Term> ();
- for (Object selectionObject : ((IStructuredSelection)source.getSelection()).toList())
- selectionList.add((Term) selectionObject);
-
- event.data = selectionList.toArray(new Term[selectionList.size()]);
- }
-
- @Override
- public void dragStart(DragSourceEvent event) {
- event.doit = !source.getSelection().isEmpty();
- }
-
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/GlossaryDropTarget.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/GlossaryDropTarget.java
deleted file mode 100644
index 7de9ea1a..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/GlossaryDropTarget.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.dnd;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipselabs.tapiji.translator.rap.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.provider.GlossaryContentProvider;
-
-
-public class GlossaryDropTarget extends DropTargetAdapter {
- private final TreeViewer target;
- private final GlossaryManager manager;
-
- public GlossaryDropTarget (TreeViewer viewer, GlossaryManager manager) {
- super();
- this.target = viewer;
- this.manager = manager;
- }
-
- public void dragEnter (DropTargetEvent event) {
- if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) {
- if ((event.operations & DND.DROP_MOVE) != 0)
- event.detail = DND.DROP_MOVE;
- else
- event.detail = DND.DROP_NONE;
- }
- }
-
- public void drop (DropTargetEvent event) {
- if (TermTransfer.getInstance().isSupportedType (event.currentDataType)) {
- Term parentTerm = null;
-
- event.detail = DND.DROP_MOVE;
- event.feedback = DND.FEEDBACK_INSERT_AFTER;
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof Term) {
- parentTerm = ((Term) ((TreeItem) event.item).getData());
- }
-
- Term[] moveTerm = (Term[]) event.data;
- Glossary glossary = ((GlossaryContentProvider) target.getContentProvider()).getGlossary();
-
- /* Remove the move term from its initial position
- for (Term selectionObject : moveTerm)
- glossary.removeTerm(selectionObject);*/
-
- /* Insert the move term on its target position */
- if (parentTerm == null) {
- for (Term t : moveTerm)
- glossary.terms.add(t);
- } else {
- for (Term t : moveTerm)
- parentTerm.subTerms.add(t);
- }
-
- manager.setGlossary(glossary);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- target.refresh();
- } else
- event.detail = DND.DROP_NONE;
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/TermTransfer.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/TermTransfer.java
deleted file mode 100644
index 4e1fdc2e..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/dnd/TermTransfer.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.dnd;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-
-
-public class TermTransfer extends ByteArrayTransfer {
-
- private static final String TERM = "term";
-
- private static final int TYPEID = registerType(TERM);
-
- private static TermTransfer transfer = new TermTransfer();
-
- public static TermTransfer getInstance() {
- return transfer;
- }
-
- public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
- DND.error(DND.ERROR_INVALID_DATA);
- }
- Term[] terms = (Term[]) object;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream oOut = new ObjectOutputStream(out);
- for (int i = 0, length = terms.length; i < length; i++) {
- oOut.writeObject(terms[i]);
- }
- byte[] buffer = out.toByteArray();
- oOut.close();
-
- super.javaToNative(buffer, transferData);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
-
- byte[] buffer;
- try {
- buffer = (byte[]) super.nativeToJava(transferData);
- } catch (Exception e) {
- e.printStackTrace();
- buffer = null;
- }
- if (buffer == null)
- return null;
-
- List<Term> terms = new ArrayList<Term>();
- try {
- ByteArrayInputStream in = new ByteArrayInputStream(buffer);
- ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
- Term newTerm = (Term) readIn.readObject();
- terms.add(newTerm);
- //}
- readIn.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- return null;
- }
- return terms.toArray(new Term[terms.size()]);
- }
-
- return null;
- }
-
- protected String[] getTypeNames() {
- return new String[] { TERM };
- }
-
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
-
- boolean checkType(Object object) {
- if (object == null || !(object instanceof Term[])
- || ((Term[]) object).length == 0) {
- return false;
- }
- Term[] myTypes = (Term[]) object;
- for (int i = 0; i < myTypes.length; i++) {
- if (myTypes[i] == null) {
- return false;
- }
- }
- return true;
- }
-
- protected boolean validate(Object object) {
- return checkType(object);
- }
-}
\ No newline at end of file
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/ExactMatcher.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/ExactMatcher.java
deleted file mode 100644
index e5675edb..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/ExactMatcher.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.filter;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-
-
-public class ExactMatcher extends ViewerFilter {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public String getPattern () {
- return pattern;
- }
-
- public void setPattern (String p) {
- boolean filtering = matcher != null;
- if (p != null && p.trim().length() > 0) {
- pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
- if (!filtering)
- viewer.addFilter(this);
- else
- viewer.refresh();
- } else {
- pattern = "";
- matcher = null;
- if (filtering) {
- viewer.removeFilter(this);
- }
- }
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- Term term = (Term) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = false;
-
- // Iterate translations
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
- String locale = translation.id;
- if (matcher.match(value)) {
- filterInfo.addFoundInTranslation(locale);
- filterInfo.addSimilarity(locale, 1d);
- int start = -1;
- while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- //TODO: filterInfo.addFoundInTranslationRange(locale, start, pattern.length());
- }
- selected = true;
- }
- }
-
- term.setInfo(filterInfo);
- return selected;
- }
-
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/FilterInfo.java
deleted file mode 100644
index 2c97c4e9..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/FilterInfo.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.filter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/*TODO: import org.eclipse.jface.text.Region;*/
-
-public class FilterInfo {
-
- private List<String> foundInTranslation = new ArrayList<String> ();
- /*TODO: private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>();*/
- private Map<String, Double> localeSimilarity = new HashMap<String, Double>();
-
- public FilterInfo() {
-
- }
-
- public void addSimilarity (String l, Double similarity) {
- localeSimilarity.put (l, similarity);
- }
-
- public Double getSimilarityLevel (String l) {
- return localeSimilarity.get(l);
- }
-
- public void addFoundInTranslation (String loc) {
- foundInTranslation.add(loc);
- }
-
- public void removeFoundInTranslation (String loc) {
- foundInTranslation.remove(loc);
- }
-
- public void clearFoundInTranslation () {
- foundInTranslation.clear();
- }
-
- public boolean hasFoundInTranslation (String l) {
- return foundInTranslation.contains(l);
- }
-
- /*TODO: public List<Region> getFoundInTranslationRanges (String locale) {
- List<Region> reg = occurrences.get(locale);
- return (reg == null ? new ArrayList<Region>() : reg);
- }
-
- TODO: 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.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/FuzzyMatcher.java
deleted file mode 100644
index ba75037f..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/FuzzyMatcher.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.filter;
-
-//TODO: import org.eclipse.babel.rap.editor.api.AnalyzerFactory;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-import org.eclipselabs.tapiji.translator.rap.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-
-public class FuzzyMatcher extends ExactMatcher {
-
- protected ILevenshteinDistanceAnalyzer lvda;
- protected float minimumSimilarity = 0.75f;
-
- public FuzzyMatcher(StructuredViewer viewer) {
- super(viewer);
- //TODO: lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
- }
-
- public double getMinimumSimilarity () {
- return minimumSimilarity;
- }
-
- public void setMinimumSimilarity (float similarity) {
- this.minimumSimilarity = similarity;
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- boolean exactMatch = super.select(viewer, parentElement, element);
- boolean match = exactMatch;
-
- Term term = (Term) element;
-
- FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
- String locale = translation.id;
- if (filterInfo.hasFoundInTranslation(locale))
- continue;
- double dist = lvda.analyse(value, getPattern());
- if (dist >= minimumSimilarity) {
- filterInfo.addFoundInTranslation(locale);
- filterInfo.addSimilarity(locale, dist);
- match = true;
- //TODO: filterInfo.addFoundInTranslationRange(locale, 0, value.length());
- }
- }
-
- term.setInfo(filterInfo);
- return match;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/SelectiveMatcher.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/SelectiveMatcher.java
deleted file mode 100644
index f80fc918..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/SelectiveMatcher.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.filter;
-
-//TODO: import org.eclipse.babel.rap.editor.api.EditorUtil;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-import org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle.IMessage;
-
-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) {
- //TODO: this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
- }
-
- this.page = page;
- page.getWorkbenchWindow().getSelectionService().addSelectionListener(this);
-
- viewer.addFilter(this);
- viewer.refresh();
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (selectedItem == null)
- return false;
-
- Term term = (Term) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = false;
-
- // Iterate translations
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
-
- if (value.trim().length() == 0)
- continue;
-
- String locale = translation.id;
-
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
- String ev = entry.getValue();
- String[] subValues = ev.split("[\\s\\p{Punct}]+");
- for (String v : subValues) {
- if (v.trim().equalsIgnoreCase(value.trim()))
- return true;
- }
- }
- }
-
- return false;
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- try {
- if (selection.isEmpty())
- return;
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- IStructuredSelection sel = (IStructuredSelection) selection;
- selectedItem = (IKeyTreeNode) sel.iterator().next();
- viewer.refresh();
- } catch (Exception e) { }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- event.getSelection();
- }
-
- public void dispose () {
- page.getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/StringMatcher.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/StringMatcher.java
deleted file mode 100644
index fe9a4917..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/filter/StringMatcher.java
+++ /dev/null
@@ -1,441 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.filter;
-
-import java.util.Vector;
-
-/**
- * A string pattern matcher, suppporting "*" and "?" wildcards.
- */
-public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
- throw new IllegalArgumentException();
- }
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
- if (end < 0 || start >= end) {
- return null;
- }
- if (fLength == 0) {
- return new Position(start, start);
- }
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
- return null;
- }
- return new Position(x, x + fLength);
- }
-
- int segCount = fSegments.length;
- if (segCount == 0) {
- return new Position(start, end);
- }
-
- int curPos = start;
- int matchStart = -1;
- int i;
- for (i = 0; i < segCount && curPos < end; ++i) {
- String current = fSegments[i];
- int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0) {
- return null;
- }
- if (i == 0) {
- matchStart = nextMatch;
- }
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
- return null;
- }
- return new Position(matchStart, curPos);
- }
-
- /**
- * match the given <code>text</code> with the pattern
- * @return true if matched otherwise false
- * @param text a String object
- */
- public boolean match(String text) {
- if(text == null) {
- return false;
- }
- return match(text, 0, text.length());
- }
-
- /**
- * Given the starting (inclusive) and the ending (exclusive) positions in the
- * <code>text</code>, determine if the given substring matches with aPattern
- * @return true if the specified portion of the text matches the pattern
- * @param text a String object that contains the substring to match
- * @param start marks the starting position (inclusive) of the substring
- * @param end marks the ending index (exclusive) of the substring
- */
- public boolean match(String text, int start, int end) {
- if (null == text) {
- throw new IllegalArgumentException();
- }
-
- if (start > end) {
- return false;
- }
-
- if (fIgnoreWildCards) {
- return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
- }
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
- return true;
- }
- if (start == end) {
- return fLength == 0;
- }
- if (fLength == 0) {
- return start == end;
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
-
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
- return false;
- }
- int i = 0;
- String current = fSegments[i];
- int segLength = current.length();
-
- /* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos = tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar)
- && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current = fSegments[i];
- int currentMatch;
- int k = current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch = textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- } else {
- currentMatch = regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- }
- tCurPos = currentMatch + current.length();
- i++;
- }
-
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen = current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount;
- }
-
- /**
- * This method parses the given pattern into segments seperated by wildcard '*' characters.
- * Since wildcards are not being used in this case, the pattern consists of a single segment.
- */
- private void parseNoWildCards() {
- fSegments = new String[1];
- fSegments[0] = fPattern;
- fBound = fLength;
- }
-
- /**
- * Parses the given pattern into segments seperated by wildcard '*' characters.
- * @param p, a String object that is a simple regular expression with '*' and/or '?'
- */
- private void parseWildCards() {
- if (fPattern.startsWith("*")) { //$NON-NLS-1$
- fHasLeadingStar = true;
- }
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * @param text a simple regular expression that may only contain '?'(s)
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a simple regular expression that may contains '?'
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int regExpPosIn(String text, int start, int end, String p) {
- int plen = p.length();
-
- int max = end - plen;
- for (int i = start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- *
- * @return boolean
- * @param text a String to match
- * @param start int that indicates the starting index of match, inclusive
- * @param end</code> int that indicates the ending index of match, exclusive
- * @param p String, String, a simple regular expression that may contain '?'
- * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
- */
- protected boolean regExpRegionMatches(String text, int tStart, String p,
- int pStart, int plen) {
- while (plen-- > 0) {
- char tchar = text.charAt(tStart++);
- char pchar = p.charAt(pStart++);
-
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar) {
- continue;
- }
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character
- .toUpperCase(pchar)) {
- continue;
- }
- // comparing after converting to upper case doesn't handle all cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character
- .toLowerCase(pchar)) {
- continue;
- }
- }
- return false;
- }
- return true;
- }
-
- /**
- * @param text the string to match
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a pattern string that has no wildcard
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int textPosIn(String text, int start, int end, String p) {
-
- int plen = p.length();
- int max = end - plen;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(p, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
- return i;
- }
- }
-
- return -1;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/model/GlossaryViewState.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/model/GlossaryViewState.java
deleted file mode 100644
index fa195be5..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/model/GlossaryViewState.java
+++ /dev/null
@@ -1,212 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.model;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.sorter.SortInfo;
-
-
-public class GlossaryViewState {
-
- private static final String TAG_GLOSSARY_FILE = "glossary_file";
- private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
- private static final String TAG_SELECTIVE_VIEW = "selective_content";
- private static final String TAG_DISPLAYED_LOCALES = "displayed_locales";
- private static final String TAG_LOCALE = "locale";
- private static final String TAG_REFERENCE_LANG = "reference_language";
- private static final String TAG_MATCHING_PRECISION= "matching_precision";
- private static final String TAG_ENABLED = "enabled";
- private static final String TAG_VALUE = "value";
- private static final String TAG_SEARCH_STRING = "search_string";
- private static final String TAG_EDITABLE = "editable";
-
- private SortInfo sortings;
- private boolean fuzzyMatchingEnabled;
- private boolean selectiveViewEnabled;
- private float matchingPrecision = .75f;
- private String searchString;
- private boolean editable;
- private String glossaryFile;
- private String referenceLanguage;
- private List<String> displayLanguages;
-
- public void saveState (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (sortings != null) {
- sortings.saveState(memento);
- }
-
- IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
- memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
-
- IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW);
- memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled);
-
- IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
- memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
-
- IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
- memSStr.putString(TAG_VALUE, searchString);
-
- IMemento memEditable = memento.createChild(TAG_EDITABLE);
- memEditable.putBoolean(TAG_ENABLED, editable);
-
- IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG);
- memRefLang.putString(TAG_VALUE, referenceLanguage);
-
- IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE);
- memGlossaryFile.putString(TAG_VALUE, glossaryFile);
-
- IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES);
- if (displayLanguages != null) {
- for (String lang : displayLanguages) {
- IMemento memLoc = memDispLoc.createChild(TAG_LOCALE);
- memLoc.putString(TAG_VALUE, lang);
- }
- }
- } catch (Exception e) {
-
- }
- }
-
- public void init (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (sortings == null)
- sortings = new SortInfo();
- sortings.init(memento);
-
- IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
- if (mFuzzyMatching != null)
- fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
-
- IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW);
- if (mSelectiveView != null)
- selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED);
-
- IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
- if (mMP != null)
- matchingPrecision = mMP.getFloat(TAG_VALUE);
-
- IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
- if (mSStr != null)
- searchString = mSStr.getString(TAG_VALUE);
-
- IMemento mEditable = memento.getChild(TAG_EDITABLE);
- if (mEditable != null)
- editable = mEditable.getBoolean(TAG_ENABLED);
-
- IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG);
- if (mRefLang != null)
- referenceLanguage = mRefLang.getString(TAG_VALUE);
-
- IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE);
- if (mGlossaryFile != null)
- glossaryFile = mGlossaryFile.getString(TAG_VALUE);
-
- IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES);
- if (memDispLoc != null) {
- displayLanguages = new ArrayList<String>();
- for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) {
- displayLanguages.add(locale.getString(TAG_VALUE));
- }
- }
- } catch (Exception e) {
-
- }
- }
-
- public GlossaryViewState(List<Locale> visibleLocales,
- SortInfo sortings, boolean fuzzyMatchingEnabled,
- String selectedBundleId) {
- super();
- this.sortings = sortings;
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public SortInfo getSortings() {
- return sortings;
- }
-
- public void setSortings(SortInfo sortings) {
- this.sortings = sortings;
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public void setSearchString(String searchString) {
- this.searchString = searchString;
- }
-
- public String getSearchString() {
- return searchString;
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public void setMatchingPrecision (float value) {
- this.matchingPrecision = value;
- }
-
- public String getReferenceLanguage() {
- return this.referenceLanguage;
- }
-
- public void setReferenceLanguage (String refLang) {
- this.referenceLanguage = refLang;
- }
-
- public List<String> getDisplayLanguages() {
- return displayLanguages;
- }
-
- public void setDisplayLanguages(List<String> displayLanguages) {
- this.displayLanguages = displayLanguages;
- }
-
- public void setDisplayLangArr (String[] displayLanguages) {
- this.displayLanguages = new ArrayList<String>();
- for (String dl : displayLanguages) {
- this.displayLanguages.add(dl);
- }
- }
-
- public void setGlossaryFile(String absolutePath) {
- this.glossaryFile = absolutePath;
- }
-
- public String getGlossaryFile() {
- return glossaryFile;
- }
-
- public void setSelectiveViewEnabled(boolean selectiveViewEnabled) {
- this.selectiveViewEnabled = selectiveViewEnabled;
- }
-
- public boolean isSelectiveViewEnabled() {
- return selectiveViewEnabled;
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/provider/GlossaryContentProvider.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/provider/GlossaryContentProvider.java
deleted file mode 100644
index 57b1dc1a..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/provider/GlossaryContentProvider.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.rap.model.Glossary;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-
-
-public class GlossaryContentProvider implements ITreeContentProvider {
-
- private Glossary glossary;
- private boolean grouped = false;
-
- public GlossaryContentProvider (Glossary glossary) {
- this.glossary = glossary;
- }
-
- public Glossary getGlossary () {
- return glossary;
- }
-
- public void setGrouped (boolean grouped) {
- this.grouped = grouped;
- }
-
- @Override
- public void dispose() {
- this.glossary = null;
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput instanceof Glossary)
- this.glossary = (Glossary) newInput;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (!grouped)
- return getAllElements(glossary.terms).toArray(new Term[glossary.terms.size()]);
-
- if (glossary != null)
- return glossary.getAllTerms();
-
- return null;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (!grouped)
- return null;
-
- if (parentElement instanceof Term) {
- Term t = (Term) parentElement;
- return t.getAllSubTerms ();
- }
- return null;
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof Term) {
- Term t = (Term) element;
- return t.getParentTerm();
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (!grouped)
- return false;
-
- if (element instanceof Term) {
- Term t = (Term) element;
- return t.hasChildTerms();
- }
- return false;
- }
-
- public List<Term> getAllElements (List<Term> terms) {
- List<Term> allTerms = new ArrayList<Term>();
-
- if (terms != null) {
- for (Term term : terms) {
- allTerms.add(term);
- allTerms.addAll(getAllElements(term.subTerms));
- }
- }
-
- return allTerms;
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/provider/GlossaryLabelProvider.java
deleted file mode 100644
index 7caaa3bc..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/provider/GlossaryLabelProvider.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-//TODO: import org.eclipse.babel.editor.api.EditorUtil;
-//TODO: import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-//TODO: import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-//TODO: import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-import org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rap.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.rap.utils.FontUtils;
-import org.eclipselabs.tapiji.translator.rap.views.widgets.filter.FilterInfo;
-
-public class GlossaryLabelProvider /*TODO: extends StyledCellLabelProvider*/ implements
- ISelectionListener, ISelectionChangedListener {
-
- private boolean searchEnabled = false;
- private int referenceColumn = 0;
- private List<String> translations;
- private IKeyTreeNode selectedItem;
-
- /*** COLORS ***/
- private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
- private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
- private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
- private Color info_crossref = FontUtils.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- private Color info_crossref_foreground = FontUtils.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- private Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE);
-
- /*** FONTS ***/
- private Font bold = FontUtils.createFont(SWT.BOLD);
- private Font bold_italic = FontUtils.createFont(SWT.ITALIC);
-
- public void setSearchEnabled(boolean b) {
- this.searchEnabled = b;
- }
-
- public GlossaryLabelProvider(int referenceColumn, List<String> translations, IWorkbenchPage page) {
- this.referenceColumn = referenceColumn;
- this.translations = translations;
- if (page.getActiveEditor() != null) {
- //TODO: selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
- }
- }
-
- public String getColumnText(Object element, int columnIndex) {
- try {
- Term term = (Term) element;
- if (term != null) {
- Translation transl = term.getTranslation(this.translations.get(columnIndex));
- return transl != null ? transl.value : "";
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "";
- }
-
- public boolean isSearchEnabled () {
- return this.searchEnabled;
- }
-
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
- boolean matching = false;
-
- if (element instanceof Term) {
- Term term = (Term) element;
-
- if (term.getInfo() == null)
- return false;
-
- FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- matching = filterInfo.hasFoundInTranslation(translations.get(columnIndex));
- }
-
- return matching;
- }
-
- /*TODO: @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
- cell.setText(this.getColumnText(element, columnIndex));
-
- if (isCrossRefRegion(cell.getText())) {
- cell.setFont (bold);
- cell.setBackground(info_crossref);
- cell.setForeground(info_crossref_foreground);
- } else {
- cell.setFont(this.getColumnFont(element, columnIndex));
- cell.setBackground(transparent);
- }
-
- if (isSearchEnabled()) {
- if (isMatchingToPattern(element, columnIndex) ) {
- List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((Term)element).getInfo();
-
- for (Region reg : filterInfo.getFoundInTranslationRanges(translations.get(columnIndex < referenceColumn ? columnIndex + 1 : columnIndex))) {
- styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
- }
-
- cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
- } else {
- cell.setForeground(gray);
- }
- }
- }*/
-
- private boolean isCrossRefRegion(String cellText) {
- if (selectedItem != null) {
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
- String value = entry.getValue();
- String[] subValues = value.split("[\\s\\p{Punct}]+");
- for (String v : subValues) {
- if (v.trim().equalsIgnoreCase(cellText.trim()))
- return true;
- }
- }
- }
-
- return false;
- }
-
- private Font getColumnFont(Object element, int columnIndex) {
- if (columnIndex == 0) {
- return bold_italic;
- }
- return null;
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- try {
- if (selection.isEmpty())
- return;
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- IStructuredSelection sel = (IStructuredSelection) selection;
- selectedItem = (IKeyTreeNode) sel.iterator().next();
- //TODO: this.getViewer().refresh();
- } catch (Exception e) {
- // silent catch
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- event.getSelection();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/sorter/GlossaryEntrySorter.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/sorter/GlossaryEntrySorter.java
deleted file mode 100644
index 272cf483..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/sorter/GlossaryEntrySorter.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.sorter;
-
-import java.util.List;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipselabs.tapiji.translator.rap.model.Term;
-import org.eclipselabs.tapiji.translator.rap.model.Translation;
-
-
-public class GlossaryEntrySorter extends ViewerSorter {
-
- private StructuredViewer viewer;
- private SortInfo sortInfo;
- private int referenceCol;
- private List<String> translations;
-
- public GlossaryEntrySorter (StructuredViewer viewer,
- SortInfo sortInfo,
- int referenceCol,
- List<String> translations) {
- this.viewer = viewer;
- this.referenceCol = referenceCol;
- this.translations = translations;
-
- if (sortInfo != null)
- this.sortInfo = sortInfo;
- else
- this.sortInfo = new SortInfo();
- }
-
- public StructuredViewer getViewer() {
- return viewer;
- }
-
- public void setViewer(StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public SortInfo getSortInfo() {
- return sortInfo;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- this.sortInfo = sortInfo;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- try {
- if (!(e1 instanceof Term && e2 instanceof Term))
- return super.compare(viewer, e1, e2);
- Term comp1 = (Term) e1;
- Term comp2 = (Term) e2;
-
- int result = 0;
-
- if (sortInfo == null)
- return 0;
-
- if (sortInfo.getColIdx() == 0) {
- Translation transComp1 = comp1.getTranslation(translations.get(referenceCol));
- Translation transComp2 = comp2.getTranslation(translations.get(referenceCol));
- if (transComp1 != null && transComp2 != null)
- result = transComp1.value.compareTo(transComp2.value);
- } else {
- int col = sortInfo.getColIdx() < referenceCol ? sortInfo.getColIdx() + 1 : sortInfo.getColIdx();
- Translation transComp1 = comp1.getTranslation(translations.get(col));
- Translation transComp2 = comp2.getTranslation(translations.get(col));
-
- if (transComp1 == null)
- transComp1 = new Translation();
- if (transComp2 == null)
- transComp2 = new Translation();
- result = transComp1.value.compareTo(transComp2.value);
- }
-
- return result * (sortInfo.isDESC() ? -1 : 1);
- } catch (Exception e) {
- return 0;
- }
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/sorter/SortInfo.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/sorter/SortInfo.java
deleted file mode 100644
index 547b29c3..00000000
--- a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/rap/views/widgets/sorter/SortInfo.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package org.eclipselabs.tapiji.translator.rap.views.widgets.sorter;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-
-public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
- private int colIdx;
- private boolean DESC;
- private List<Locale> visibleLocales;
-
- public void setDESC(boolean dESC) {
- DESC = dESC;
- }
-
- public boolean isDESC() {
- return DESC;
- }
-
- public void setColIdx(int colIdx) {
- this.colIdx = colIdx;
- }
-
- public int getColIdx() {
- return colIdx;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void saveState (IMemento memento) {
- IMemento mCI = memento.createChild(TAG_SORT_INFO);
- mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
- mCI.putBoolean(TAG_ORDER, DESC);
- }
-
- public void init (IMemento memento) {
- IMemento mCI = memento.getChild(TAG_SORT_INFO);
- if (mCI == null)
- return;
- colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
- DESC = mCI.getBoolean(TAG_ORDER);
- }
-}
diff --git a/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
new file mode 100644
index 00000000..fffd80d9
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rap/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
@@ -0,0 +1,53 @@
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
+
+import java.util.List;
+
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.ui.IWorkbenchPage;
+
+public class GlossaryLabelProvider extends AbstractGlossaryLabelProvider {
+
+ private static final long serialVersionUID = -4483186763283604766L;
+
+ public GlossaryLabelProvider(int referenceColumn,
+ List<String> translations, IWorkbenchPage page) {
+ super(referenceColumn, translations, page);
+ }
+
+ @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)) {
+ // TODO [RAP] workaround
+ /* 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);
+ }
+ }
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rbe/.project b/org.eclipselabs.tapiji.translator.rbe/.project
deleted file mode 100644
index c504135a..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipselabs.tapiji.translator.rbe</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF
deleted file mode 100644
index 84347f3a..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,10 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: ResourceBundleEditorAPI
-Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rbe
-Bundle-Version: 0.0.2.qualifier
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Export-Package: org.eclipselabs.tapiji.translator.rbe.babel.bundle,
- org.eclipselabs.tapiji.translator.rbe.model.analyze,
- org.eclipselabs.tapiji.translator.rbe.ui.wizards
-Require-Bundle: org.eclipse.jface;bundle-version="3.6.2"
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
deleted file mode 100644
index e028b18c..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-
-
-public interface IAbstractKeyTreeModel {
-
- IKeyTreeNode[] getChildren(IKeyTreeNode node);
-
- IKeyTreeNode getChild(String key);
-
- IKeyTreeNode[] getRootNodes();
-
- IKeyTreeNode getRootNode();
-
- IKeyTreeNode getParent(IKeyTreeNode node);
-
- void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
deleted file mode 100644
index b236a632..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-import org.eclipse.jface.viewers.TreeViewer;
-
-
-public interface IKeyTreeContributor {
-
- void contribute(final TreeViewer treeViewer);
-
- IKeyTreeNode getKeyTreeNode(String key);
-
- IKeyTreeNode[] getRootKeyItems();
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
deleted file mode 100644
index bca34004..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-
-
-public interface IKeyTreeNode {
-
- /**
- * Returns the key of the corresponding Resource-Bundle entry.
- * @return The key of the Resource-Bundle entry
- */
- String getMessageKey();
-
- /**
- * Returns the set of Resource-Bundle entries of the next deeper
- * hierarchy level that share the represented entry as their common
- * parent.
- * @return The direct child Resource-Bundle entries
- */
- IKeyTreeNode[] getChildren();
-
- /**
- * The represented Resource-Bundle entry's id without the prefix defined
- * by the entry's parent.
- * @return The Resource-Bundle entry's display name.
- */
- String getName();
-
- /**
- * Returns the set of Resource-Bundle entries from all deeper hierarchy
- * levels that share the represented entry as their common parent.
- * @return All child Resource-Bundle entries
- */
-// Collection<? extends IKeyTreeItem> getNestedChildren();
-
- /**
- * Returns whether this Resource-Bundle entry is visible under the
- * given filter expression.
- * @param filter The filter expression
- * @return True if the filter expression matches the represented Resource-Bundle entry
- */
-// boolean applyFilter(String filter);
-
- /**
- * The Resource-Bundle entries parent.
- * @return The parent Resource-Bundle entry
- */
- IKeyTreeNode getParent();
-
- /**
- * The Resource-Bundles key representation.
- * @return The Resource-Bundle reference, if known
- */
- IMessagesBundleGroup getMessagesBundleGroup();
-
-
- boolean isUsedAsKey();
-
- void setParent(IKeyTreeNode parentNode);
-
- void addChild(IKeyTreeNode childNode);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
deleted file mode 100644
index f520ab74..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-
-/**
- * Objects implementing this interface can act as a visitor to a
- * <code>IKeyTreeModel</code>.
- * @author Pascal Essiembre ([email protected])
- */
-public interface IKeyTreeVisitor {
- /**
- * Visits a key tree node.
- * @param item key tree node to visit
- */
- void visitKeyTreeNode(IKeyTreeNode node);
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessage.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessage.java
deleted file mode 100644
index 4b07d841..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessage.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Locale;
-
-
-
-public interface IMessage {
-
- String getKey();
-
- String getValue();
-
- Locale getLocale();
-
- String getComment();
-
- boolean isActive();
-
- String toString();
-
- void setActive(boolean active);
-
- void setComment(String comment);
-
- void setComment(String comment, boolean silent);
-
- void setText(String test);
-
- void setText(String test, boolean silent);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
deleted file mode 100644
index 6c1ebbdc..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-
-
-
-
-public interface IMessagesBundle {
-
- void dispose();
-
- void renameMessageKey(String sourceKey, String targetKey);
-
- void removeMessage(String messageKey);
-
- void duplicateMessage(String sourceKey, String targetKey);
-
- Locale getLocale();
-
- String[] getKeys();
-
- String getValue(String key);
-
- Collection<IMessage> getMessages();
-
- IMessage getMessage(String key);
-
- void addMessage(IMessage message);
-
- void removeMessages(String[] messageKeys);
-
- void setComment(String comment);
-
- String getComment();
-
- IMessagesResource getResource();
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
deleted file mode 100644
index dae97627..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-
-
-public interface IMessagesBundleGroup {
-
- Collection<IMessagesBundle> getMessagesBundles();
-
- boolean containsKey(String key);
-
- IMessage[] getMessages(String key);
-
- IMessage getMessage(String key, Locale locale);
-
- IMessagesBundle getMessagesBundle(Locale locale);
-
- void removeMessages(String messageKey);
-
- boolean isKey(String key);
-
- void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
-
- String[] getMessageKeys();
-
- void addMessages(String key);
-
- int getMessagesBundleCount();
-
- String getName();
-
- String getResourceBundleId();
-
- boolean hasPropertiesFileGroupStrategy();
-
- public boolean isMessageKey(String key);
-
- public String getProjectName();
-
- public void removeMessagesBundle(IMessagesBundle messagesBundle);
-
- public void dispose();
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesResource.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
deleted file mode 100644
index b9f2d54f..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Locale;
-
-/**
- * Class abstracting the underlying native storage mechanism for persisting
- * internationalised text messages.
- * @author Pascal Essiembre
- */
-public interface IMessagesResource {
-
- /**
- * Gets the resource locale.
- * @return locale
- */
- Locale getLocale();
- /**
- * Gets the underlying object abstracted by this resource (e.g. a File).
- * @return source object
- */
- Object getSource();
- /**
- * Serializes a {@link MessagesBundle} instance to its native format.
- * @param messagesBundle the MessagesBundle to serialize
- */
- void serialize(IMessagesBundle messagesBundle);
- /**
- * Deserializes a {@link MessagesBundle} instance from its native format.
- * @param messagesBundle the MessagesBundle to deserialize
- */
- void deserialize(IMessagesBundle messagesBundle);
- /**
- * Adds a messages resource listener. Implementors are required to notify
- * listeners of changes within the native implementation.
- * @param listener the listener
- */
- void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * Removes a messages resource listener.
- * @param listener the listener
- */
- void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * @return The resource location label. or null if unknown.
- */
- String getResourceLocationLabel();
-
- /**
- * Called when the group it belongs to is disposed.
- */
- void dispose();
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
deleted file mode 100644
index 68c49799..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-/**
- * Listener being notified when a {@link IMessagesResource} content changes.
- * @author Pascal Essiembre
- */
-public interface IMessagesResourceChangeListener {
-
- /**
- * Method called when the messages resource has changed.
- * @param resource the resource that changed
- */
- void resourceChanged(IMessagesResource resource);
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
deleted file mode 100644
index 3d02895a..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-
-
-public interface IValuedKeyTreeNode extends IKeyTreeNode{
-
- public void initValues (Map<Locale, String> values);
-
- public void addValue (Locale locale, String value);
-
- public String getValue (Locale locale);
-
- public Collection<String> getValues ();
-
- public void setInfo(Object info);
-
- public Object getInfo();
-
- public Collection<Locale> getLocales ();
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/TreeType.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/TreeType.java
deleted file mode 100644
index f88b831b..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/babel/bundle/TreeType.java
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- *
- */
-package org.eclipselabs.tapiji.translator.rbe.babel.bundle;
-
-
-/**
- * @author ala
- *
- */
-public enum TreeType {
- Tree,
- Flat
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
deleted file mode 100644
index f4a7c1fc..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.model.analyze;
-
-public interface ILevenshteinDistanceAnalyzer {
-
- double analyse(Object value, Object pattern);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java b/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java
deleted file mode 100644
index afb12509..00000000
--- a/org.eclipselabs.tapiji.translator.rbe/src/org/eclipselabs/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.eclipselabs.tapiji.translator.rbe.ui.wizards;
-
-public interface IResourceBundleWizard {
-
- void setBundleId(String rbName);
-
- void setDefaultPath(String pathName);
-
-}
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/.classpath b/org.eclipselabs.tapiji.translator.rcp.compat/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/.project b/org.eclipselabs.tapiji.translator.rcp.compat/.project
new file mode 100644
index 00000000..04f10b31
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipselabs.tapiji.translator.rcp.compat</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.translator.rcp.compat/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..c537b630
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/.settings/org.eclipse.pde.core.prefs b/org.eclipselabs.tapiji.translator.rcp.compat/.settings/org.eclipse.pde.core.prefs
new file mode 100644
index 00000000..f29e940a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/.settings/org.eclipse.pde.core.prefs
@@ -0,0 +1,3 @@
+eclipse.preferences.version=1
+pluginProject.extensions=false
+resolve.requirebundle=false
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rcp.compat/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..646f8ccf
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/META-INF/MANIFEST.MF
@@ -0,0 +1,11 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RCP Compatibiltiy for TapiJI Translator
+Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rcp.compat
+Bundle-Version: 0.0.2.qualifier
+Bundle-Activator: org.eclipselabs.tapiji.translator.compat.Activator
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Import-Package: org.osgi.framework;version="1.6.0"
+Require-Bundle: org.eclipse.ui
+Export-Package: org.eclipselabs.tapiji.translator.compat
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/build.properties b/org.eclipselabs.tapiji.translator.rcp.compat/build.properties
new file mode 100644
index 00000000..34d2e4d2
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/build.properties
@@ -0,0 +1,4 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/src/org/eclipselabs/tapiji/translator/compat/Activator.java b/org.eclipselabs.tapiji.translator.rcp.compat/src/org/eclipselabs/tapiji/translator/compat/Activator.java
new file mode 100644
index 00000000..ba84e8dc
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/src/org/eclipselabs/tapiji/translator/compat/Activator.java
@@ -0,0 +1,30 @@
+package org.eclipselabs.tapiji.translator.compat;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ private static BundleContext context;
+
+ static BundleContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext bundleContext) throws Exception {
+ Activator.context = bundleContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext bundleContext) throws Exception {
+ Activator.context = null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rcp.compat/src/org/eclipselabs/tapiji/translator/compat/MySWT.java b/org.eclipselabs.tapiji.translator.rcp.compat/src/org/eclipselabs/tapiji/translator/compat/MySWT.java
new file mode 100644
index 00000000..c32fecf7
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp.compat/src/org/eclipselabs/tapiji/translator/compat/MySWT.java
@@ -0,0 +1,7 @@
+package org.eclipselabs.tapiji.translator.compat;
+
+import org.eclipse.swt.SWT;
+
+public class MySWT extends SWT {
+
+}
diff --git a/org.eclipselabs.tapiji.translator.rcp/.classpath b/org.eclipselabs.tapiji.translator.rcp/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipselabs.tapiji.translator.rcp/.project b/org.eclipselabs.tapiji.translator.rcp/.project
new file mode 100644
index 00000000..46f44aaf
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipselabs.tapiji.translator.rcp</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipselabs.tapiji.translator.rcp/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.translator.rcp/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..c537b630
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipselabs.tapiji.translator.rcp/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rcp/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..3c20b396
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/META-INF/MANIFEST.MF
@@ -0,0 +1,7 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: RCP fragment for TapiJI Translator
+Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rcp;singleton:=true
+Bundle-Version: 0.0.2.qualifier
+Fragment-Host: org.eclipselabs.tapiji.translator;bundle-version="0.0.2"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.eclipselabs.tapiji.translator.rcp/build.properties b/org.eclipselabs.tapiji.translator.rcp/build.properties
new file mode 100644
index 00000000..e3023e14
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/build.properties
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ fragment.xml
diff --git a/org.eclipselabs.tapiji.translator.rcp/fragment.xml b/org.eclipselabs.tapiji.translator.rcp/fragment.xml
new file mode 100644
index 00000000..3bf1d8ea
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/fragment.xml
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<fragment>
+
+ <extension
+ id="product"
+ point="org.eclipse.core.runtime.products">
+ <product
+ application="org.eclipselabs.tapiji.application"
+ name="TapiJI Translator">
+ <property
+ name="windowImages"
+ value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
+ </property>
+ <property
+ name="appName"
+ value="TapiJI Translator">
+ </property>
+ <property
+ name="aboutImage"
+ value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
+ </property>
+ <property
+ name="aboutText"
+ value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
+ </property>
+ <property
+ name="preferenceCustomization"
+ value="plugin_customization.ini">
+ </property>
+ </product>
+ </extension>
+ <extension
+ id="app"
+ point="org.eclipse.core.runtime.products">
+ <product
+ application="org.eclipselabs.tapiji.translator.application"
+ name="TapiJI Translator">
+ <property
+ name="windowImages"
+ value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png">
+ </property>
+ <property
+ name="aboutText"
+ value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
+ </property>
+ <property
+ name="aboutImage"
+ value="icons/TapiJI_128.png">
+ </property>
+ <property
+ name="appName"
+ value="TapiJI Translator">
+ </property>
+ </product>
+ </extension>
+ <extension
+ id="application"
+ point="org.eclipse.core.runtime.applications">
+ <application>
+ <run
+ class="org.eclipselabs.tapiji.translator.rcp.compat.Application">
+ </run>
+ </application>
+ </extension>
+</fragment>
diff --git a/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.product b/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.product
new file mode 100644
index 00000000..afea13f1
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.product
@@ -0,0 +1,330 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?pde version="3.5"?>
+
+<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.0.1" useFeatures="false" includeLaunchers="true">
+
+ <aboutInfo>
+ <image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/>
+ <text>
+ TapiJI - Translator
+Version 1.0.0
+by Stefan Strobl & Martin Reiterer
+ </text>
+ </aboutInfo>
+
+ <configIni use="default">
+ </configIni>
+
+ <launcherArgs>
+ <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"/>
+
+
+ <launcher>
+ <solaris/>
+ <win useIco="false">
+ <bmp/>
+ </win>
+ </launcher>
+
+
+ <vm>
+ </vm>
+
+ <license>
+ <url>http://www.eclipse.org/legal/epl-v10.html</url>
+ <text>
+ Eclipse Public License - v 1.0
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS
+ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
+DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE
+OF THIS AGREEMENT.
+1. DEFINITIONS
+"Contribution" means:
+a) in the case of the initial Contributor, the initial code and
+documentation distributed under this Agreement, and
+b) in the case of each subsequent Contributor:
+i) changes to the Program, and
+ii) additions to the Program;
+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.
+"Contributor" means any person or entity that distributes the
+Program.
+"Licensed Patents" 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.
+"Program" means the Contributions distributed in accordance with
+this Agreement.
+"Recipient" means anyone who receives the Program under this
+Agreement, including all Contributors.
+2. GRANT OF RIGHTS
+a) Subject to the terms of this Agreement, each Contributor hereby
+grants Recipient a non-exclusive, worldwide, royalty-free copyright
+license to reproduce, prepare derivative works of, publicly display,
+publicly perform, distribute and sublicense the Contribution
+of such Contributor, if any, and such derivative works, in source
+code and object code form.
+b) Subject to the terms of this Agreement, each Contributor hereby
+grants Recipient a non-exclusive, worldwide, royalty-free patent
+license under Licensed Patents to make, use, sell, offer to sell,
+import and otherwise transfer the Contribution of such Contributor,
+if any, in source code and object code form. This patent license
+shall apply to the combination of the Contribution and the Program
+if, at the time the Contribution is added by the Contributor,
+such addition of the Contribution causes such combination to
+be covered by the Licensed Patents. The patent license shall
+not apply to any other combinations which include the Contribution.
+No hardware per se is licensed hereunder.
+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.
+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.
+3. REQUIREMENTS
+A Contributor may choose to distribute the Program in object
+code form under its own license agreement, provided that:
+a) it complies with the terms and conditions of this Agreement;
+and
+b) its license agreement:
+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;
+ii) effectively excludes on behalf of all Contributors all liability
+for damages, including direct, indirect, special, incidental
+and consequential damages, such as lost profits;
+iii) states that any provisions which differ from this Agreement
+are offered by that Contributor alone and not by any other party;
+and
+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.
+When the Program is made available in source code form:
+a) it must be made available under this Agreement; and
+b) a copy of this Agreement must be included with each copy of
+the Program.
+Contributors may not remove or alter any copyright notices contained
+within the Program.
+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.
+4. COMMERCIAL DISTRIBUTION
+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
+("Commercial Contributor") hereby agrees to defend and indemnify
+every other Contributor ("Indemnified Contributor") against any
+losses, damages and costs (collectively "Losses") 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.
+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.
+5. NO WARRANTY
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM
+IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
+ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
+OR FITNESS FOR A PARTICULAR PURPOSE. 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.
+6. DISCLAIMER OF LIABILITY
+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.
+7. GENERAL
+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.
+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.
+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.
+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.
+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.
+ </text>
+ </license>
+
+ <plugins>
+ <plugin id="com.ibm.icu"/>
+ <plugin id="javax.transaction" fragment="true"/>
+ <plugin id="org.eclipse.ant.core"/>
+ <plugin id="org.eclipse.babel.core"/>
+ <plugin id="org.eclipse.babel.editor"/>
+ <plugin id="org.eclipse.babel.editor.nls" fragment="true"/>
+ <plugin id="org.eclipse.compare"/>
+ <plugin id="org.eclipse.compare.core"/>
+ <plugin id="org.eclipse.core.commands"/>
+ <plugin id="org.eclipse.core.contenttype"/>
+ <plugin id="org.eclipse.core.databinding"/>
+ <plugin id="org.eclipse.core.databinding.observable"/>
+ <plugin id="org.eclipse.core.databinding.property"/>
+ <plugin id="org.eclipse.core.expressions"/>
+ <plugin id="org.eclipse.core.filebuffers"/>
+ <plugin id="org.eclipse.core.filesystem"/>
+ <plugin id="org.eclipse.core.filesystem.linux.x86_64" fragment="true"/>
+ <plugin id="org.eclipse.core.jobs"/>
+ <plugin id="org.eclipse.core.resources"/>
+ <plugin id="org.eclipse.core.runtime"/>
+ <plugin id="org.eclipse.core.runtime.compatibility.registry" fragment="true"/>
+ <plugin id="org.eclipse.core.variables"/>
+ <plugin id="org.eclipse.debug.core"/>
+ <plugin id="org.eclipse.ecf"/>
+ <plugin id="org.eclipse.ecf.filetransfer"/>
+ <plugin id="org.eclipse.ecf.identity"/>
+ <plugin id="org.eclipse.ecf.provider.filetransfer"/>
+ <plugin id="org.eclipse.ecf.provider.filetransfer.ssl" fragment="true"/>
+ <plugin id="org.eclipse.ecf.ssl" fragment="true"/>
+ <plugin id="org.eclipse.equinox.app"/>
+ <plugin id="org.eclipse.equinox.common"/>
+ <plugin id="org.eclipse.equinox.frameworkadmin"/>
+ <plugin id="org.eclipse.equinox.frameworkadmin.equinox"/>
+ <plugin id="org.eclipse.equinox.p2.artifact.repository"/>
+ <plugin id="org.eclipse.equinox.p2.core"/>
+ <plugin id="org.eclipse.equinox.p2.director"/>
+ <plugin id="org.eclipse.equinox.p2.director.app"/>
+ <plugin id="org.eclipse.equinox.p2.engine"/>
+ <plugin id="org.eclipse.equinox.p2.garbagecollector"/>
+ <plugin id="org.eclipse.equinox.p2.jarprocessor"/>
+ <plugin id="org.eclipse.equinox.p2.metadata"/>
+ <plugin id="org.eclipse.equinox.p2.metadata.repository"/>
+ <plugin id="org.eclipse.equinox.p2.publisher"/>
+ <plugin id="org.eclipse.equinox.p2.publisher.eclipse"/>
+ <plugin id="org.eclipse.equinox.p2.repository"/>
+ <plugin id="org.eclipse.equinox.p2.touchpoint.eclipse"/>
+ <plugin id="org.eclipse.equinox.preferences"/>
+ <plugin id="org.eclipse.equinox.registry"/>
+ <plugin id="org.eclipse.equinox.security"/>
+ <plugin id="org.eclipse.equinox.simpleconfigurator"/>
+ <plugin id="org.eclipse.equinox.simpleconfigurator.manipulator"/>
+ <plugin id="org.eclipse.help"/>
+ <plugin id="org.eclipse.jdt.compiler.apt" fragment="true"/>
+ <plugin id="org.eclipse.jdt.compiler.tool" fragment="true"/>
+ <plugin id="org.eclipse.jdt.core"/>
+ <plugin id="org.eclipse.jdt.debug"/>
+ <plugin id="org.eclipse.jdt.launching"/>
+ <plugin id="org.eclipse.jface"/>
+ <plugin id="org.eclipse.jface.databinding"/>
+ <plugin id="org.eclipse.jface.text"/>
+ <plugin id="org.eclipse.ltk.core.refactoring"/>
+ <plugin id="org.eclipse.ltk.ui.refactoring"/>
+ <plugin id="org.eclipse.osgi"/>
+ <plugin id="org.eclipse.osgi.services"/>
+ <plugin id="org.eclipse.pde.build"/>
+ <plugin id="org.eclipse.pde.core"/>
+ <plugin id="org.eclipse.swt"/>
+ <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true"/>
+ <plugin id="org.eclipse.team.core"/>
+ <plugin id="org.eclipse.team.ui"/>
+ <plugin id="org.eclipse.text"/>
+ <plugin id="org.eclipse.ui"/>
+ <plugin id="org.eclipse.ui.editors"/>
+ <plugin id="org.eclipse.ui.forms"/>
+ <plugin id="org.eclipse.ui.ide"/>
+ <plugin id="org.eclipse.ui.navigator"/>
+ <plugin id="org.eclipse.ui.views"/>
+ <plugin id="org.eclipse.ui.workbench"/>
+ <plugin id="org.eclipse.ui.workbench.texteditor"/>
+ <plugin id="org.eclipse.update.configurator"/>
+ <plugin id="org.eclipselabs.tapiji.translator"/>
+ <plugin id="org.eclipselabs.tapiji.translator.rap.compat" fragment="true"/>
+ <plugin id="org.eclipselabs.tapiji.translator.rbe" fragment=""/>
+ <plugin id="org.eclipselabs.tapiji.translator.rcp.compat" fragment="true"/>
+ <plugin id="org.hamcrest.core"/>
+ <plugin id="org.junit"/>
+ <plugin id="org.sat4j.core"/>
+ <plugin id="org.sat4j.pb"/>
+ </plugins>
+
+
+</product>
diff --git a/org.eclipselabs.tapiji.translator.rcp/splash.bmp b/org.eclipselabs.tapiji.translator.rcp/splash.bmp
new file mode 100644
index 00000000..9283331e
Binary files /dev/null and b/org.eclipselabs.tapiji.translator.rcp/splash.bmp differ
diff --git a/org.eclipselabs.tapiji.translator.rcp/src/org/eclipselabs/tapiji/translator/rcp/compat/Application.java b/org.eclipselabs.tapiji.translator.rcp/src/org/eclipselabs/tapiji/translator/rcp/compat/Application.java
new file mode 100644
index 00000000..e101e020
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/src/org/eclipselabs/tapiji/translator/rcp/compat/Application.java
@@ -0,0 +1,62 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.rcp.compat;
+
+import org.eclipse.equinox.app.IApplication;
+import org.eclipse.equinox.app.IApplicationContext;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+import org.eclipselabs.tapiji.translator.ApplicationWorkbenchAdvisor;
+
+/**
+ * This class controls all aspects of the application's execution
+ */
+public class Application implements IApplication {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
+ * IApplicationContext)
+ */
+ public Object start(IApplicationContext context) {
+ Display display = PlatformUI.createDisplay();
+ try {
+ int returnCode = PlatformUI.createAndRunWorkbench(display,
+ new ApplicationWorkbenchAdvisor());
+ if (returnCode == PlatformUI.RETURN_RESTART) {
+ return IApplication.EXIT_RESTART;
+ }
+ return IApplication.EXIT_OK;
+ } finally {
+ display.dispose();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.equinox.app.IApplication#stop()
+ */
+ public void stop() {
+ if (!PlatformUI.isWorkbenchRunning())
+ return;
+ final IWorkbench workbench = PlatformUI.getWorkbench();
+ final Display display = workbench.getDisplay();
+ display.syncExec(new Runnable() {
+ public void run() {
+ if (!display.isDisposed())
+ workbench.close();
+ }
+ });
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator.rcp/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator.rcp/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
new file mode 100644
index 00000000..3a12cad4
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator.rcp/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
@@ -0,0 +1,59 @@
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.AbstractGlossaryLabelProvider;
+
+public class GlossaryLabelProvider extends AbstractGlossaryLabelProvider {
+
+ private static final long serialVersionUID = 1060409544305337717L;
+
+ public GlossaryLabelProvider(int referenceColumn,
+ List<String> translations, IWorkbenchPage page) {
+ super(referenceColumn, translations, page);
+ }
+
+ @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);
+ }
+ }
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF
index 1d4163d8..a90032d3 100644
--- a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF
@@ -4,14 +4,19 @@ Bundle-Name: TapiJI Translator
Bundle-SymbolicName: org.eclipselabs.tapiji.translator;singleton:=true
Bundle-Version: 0.0.2.qualifier
Bundle-Activator: org.eclipselabs.tapiji.translator.Activator
-Require-Bundle: org.eclipse.ui,
+Require-Bundle: org.eclipse.ui;resolution:=optional,
org.eclipse.core.runtime,
org.eclipse.core.filesystem;bundle-version="1.3.0",
- org.eclipse.jface.text;bundle-version="3.6.0",
org.eclipse.core.resources;bundle-version="3.6.0",
- org.eclipse.ui.ide;bundle-version="3.6.0",
+ org.eclipse.ui.ide;bundle-version="3.6.0";resolution:=optional,
org.junit,
- org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.2"
+ org.eclipse.babel.core;bundle-version="0.8.0",
+ org.eclipse.jface.text;bundle-version="3.6.1";resolution:=optional,
+ org.eclipse.rap.ui;bundle-version="1.5.0";resolution:=optional,
+ org.eclipse.rap.rwt.supplemental.filedialog;bundle-version="1.5.0";resolution:=optional,
+ org.eclipselabs.tapiji.translator.rap.supplemental;bundle-version="0.0.2";resolution:=optional,
+ org.eclipselabs.tapiji.translator.rcp.compat;bundle-version="0.0.2";resolution:=optional,
+ org.eclipselabs.tapiji.translator.rap.compat;bundle-version="0.0.2";resolution:=optional
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-Vendor: Vienna University of Technology
diff --git a/org.eclipselabs.tapiji.translator/org.eclipselabs.tapiji.translator.product b/org.eclipselabs.tapiji.translator/org.eclipselabs.tapiji.translator.product
index 49e3c0f0..9bdf79b5 100644
--- a/org.eclipselabs.tapiji.translator/org.eclipselabs.tapiji.translator.product
+++ b/org.eclipselabs.tapiji.translator/org.eclipselabs.tapiji.translator.product
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?pde version="3.5"?>
-
-<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.0.1" useFeatures="false" includeLaunchers="true">
-
- <aboutInfo>
- <image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/>
- <text>
+<?xml version="1.0" encoding="UTF-8"?>
+<?pde version="3.5"?>
+
+<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.0.1" useFeatures="false" includeLaunchers="true">
+
+ <aboutInfo>
+ <image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/>
+ <text>
TapiJI - Translator
Version 1.0.0
-by Stefan Strobl & Martin Reiterer
- </text>
- </aboutInfo>
-
- <configIni use="default">
- </configIni>
-
- <launcherArgs>
- <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"/>
-
- <license>
- <url>http://www.eclipse.org/legal/epl-v10.html</url>
- <text>
+by Stefan Strobl & Martin Reiterer
+ </text>
+ </aboutInfo>
+
+ <configIni use="default">
+ </configIni>
+
+ <launcherArgs>
+ <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"/>
+
+ <license>
+ <url>http://www.eclipse.org/legal/epl-v10.html</url>
+ <text>
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS
ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
@@ -219,72 +219,103 @@ 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.
- </text>
- </license>
-
- <plugins>
- <plugin id="com.essiembre.eclipse.i18n.resourcebundle"/>
- <plugin id="com.ibm.icu"/>
- <plugin id="org.eclipse.compare.core"/>
- <plugin id="org.eclipse.core.commands"/>
- <plugin id="org.eclipse.core.contenttype"/>
- <plugin id="org.eclipse.core.databinding"/>
- <plugin id="org.eclipse.core.databinding.observable"/>
- <plugin id="org.eclipse.core.databinding.property"/>
- <plugin id="org.eclipse.core.expressions"/>
- <plugin id="org.eclipse.core.filebuffers"/>
- <plugin id="org.eclipse.core.filesystem"/>
- <plugin id="org.eclipse.core.filesystem.win32.x86" fragment="true"/>
- <plugin id="org.eclipse.core.filesystem.win32.x86_64" fragment="true"/>
- <plugin id="org.eclipse.core.jobs"/>
- <plugin id="org.eclipse.core.resources"/>
- <plugin id="org.eclipse.core.resources.win32.x86" fragment="true"/>
- <plugin id="org.eclipse.core.runtime"/>
- <plugin id="org.eclipse.core.runtime.compatibility.registry" fragment="true"/>
- <plugin id="org.eclipse.ecf"/>
- <plugin id="org.eclipse.ecf.filetransfer"/>
- <plugin id="org.eclipse.ecf.identity"/>
- <plugin id="org.eclipse.ecf.provider.filetransfer"/>
- <plugin id="org.eclipse.ecf.provider.filetransfer.ssl" fragment="true"/>
- <plugin id="org.eclipse.ecf.ssl" fragment="true"/>
- <plugin id="org.eclipse.equinox.app"/>
- <plugin id="org.eclipse.equinox.common"/>
- <plugin id="org.eclipse.equinox.p2.core"/>
- <plugin id="org.eclipse.equinox.p2.engine"/>
- <plugin id="org.eclipse.equinox.p2.metadata"/>
- <plugin id="org.eclipse.equinox.p2.metadata.repository"/>
- <plugin id="org.eclipse.equinox.p2.repository"/>
- <plugin id="org.eclipse.equinox.preferences"/>
- <plugin id="org.eclipse.equinox.registry"/>
- <plugin id="org.eclipse.equinox.security"/>
- <plugin id="org.eclipse.equinox.security.win32.x86" fragment="true"/>
- <plugin id="org.eclipse.equinox.security.win32.x86_64" fragment="true"/>
- <plugin id="org.eclipse.help"/>
- <plugin id="org.eclipse.jdt.compiler.apt" fragment="true"/>
- <plugin id="org.eclipse.jdt.compiler.tool" fragment="true"/>
- <plugin id="org.eclipse.jdt.core"/>
- <plugin id="org.eclipse.jface"/>
- <plugin id="org.eclipse.jface.databinding"/>
- <plugin id="org.eclipse.jface.text"/>
- <plugin id="org.eclipse.osgi"/>
- <plugin id="org.eclipse.osgi.services"/>
- <plugin id="org.eclipse.swt"/>
- <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.text"/>
- <plugin id="org.eclipse.ui"/>
- <plugin id="org.eclipse.ui.editors"/>
- <plugin id="org.eclipse.ui.ide"/>
- <plugin id="org.eclipse.ui.views"/>
- <plugin id="org.eclipse.ui.win32" fragment="true"/>
- <plugin id="org.eclipse.ui.workbench"/>
- <plugin id="org.eclipse.ui.workbench.texteditor"/>
- <plugin id="org.eclipselabs.tapiji.translator"/>
- <plugin id="org.eclipselabs.tapiji.translator.rbe"/>
- <plugin id="org.hamcrest.core"/>
- <plugin id="org.junit"/>
- </plugins>
-
-
-</product>
+litigation.
+ </text>
+ </license>
+
+ <plugins>
+ <plugin id="com.ibm.icu"/>
+ <plugin id="javax.transaction" fragment="true"/>
+ <plugin id="org.eclipse.ant.core"/>
+ <plugin id="org.eclipse.babel.core"/>
+ <plugin id="org.eclipse.babel.core.rcp" fragment="true"/>
+ <plugin id="org.eclipse.babel.editor"/>
+ <plugin id="org.eclipse.babel.editor.nls" fragment="true"/>
+ <plugin id="org.eclipse.babel.editor.rcp" fragment="true"/>
+ <plugin id="org.eclipse.babel.editor.rcp.compat"/>
+ <plugin id="org.eclipse.compare"/>
+ <plugin id="org.eclipse.compare.core"/>
+ <plugin id="org.eclipse.core.commands"/>
+ <plugin id="org.eclipse.core.contenttype"/>
+ <plugin id="org.eclipse.core.databinding"/>
+ <plugin id="org.eclipse.core.databinding.observable"/>
+ <plugin id="org.eclipse.core.databinding.property"/>
+ <plugin id="org.eclipse.core.expressions"/>
+ <plugin id="org.eclipse.core.filebuffers"/>
+ <plugin id="org.eclipse.core.filesystem"/>
+ <plugin id="org.eclipse.core.filesystem.linux.x86_64" fragment="true"/>
+ <plugin id="org.eclipse.core.jobs"/>
+ <plugin id="org.eclipse.core.resources"/>
+ <plugin id="org.eclipse.core.runtime"/>
+ <plugin id="org.eclipse.core.runtime.compatibility.registry" fragment="true"/>
+ <plugin id="org.eclipse.core.variables"/>
+ <plugin id="org.eclipse.debug.core"/>
+ <plugin id="org.eclipse.ecf"/>
+ <plugin id="org.eclipse.ecf.filetransfer"/>
+ <plugin id="org.eclipse.ecf.identity"/>
+ <plugin id="org.eclipse.ecf.provider.filetransfer"/>
+ <plugin id="org.eclipse.ecf.provider.filetransfer.ssl" fragment="true"/>
+ <plugin id="org.eclipse.ecf.ssl" fragment="true"/>
+ <plugin id="org.eclipse.equinox.app"/>
+ <plugin id="org.eclipse.equinox.common"/>
+ <plugin id="org.eclipse.equinox.frameworkadmin"/>
+ <plugin id="org.eclipse.equinox.frameworkadmin.equinox"/>
+ <plugin id="org.eclipse.equinox.p2.artifact.repository"/>
+ <plugin id="org.eclipse.equinox.p2.core"/>
+ <plugin id="org.eclipse.equinox.p2.director"/>
+ <plugin id="org.eclipse.equinox.p2.director.app"/>
+ <plugin id="org.eclipse.equinox.p2.engine"/>
+ <plugin id="org.eclipse.equinox.p2.garbagecollector"/>
+ <plugin id="org.eclipse.equinox.p2.jarprocessor"/>
+ <plugin id="org.eclipse.equinox.p2.metadata"/>
+ <plugin id="org.eclipse.equinox.p2.metadata.repository"/>
+ <plugin id="org.eclipse.equinox.p2.publisher"/>
+ <plugin id="org.eclipse.equinox.p2.publisher.eclipse"/>
+ <plugin id="org.eclipse.equinox.p2.repository"/>
+ <plugin id="org.eclipse.equinox.p2.touchpoint.eclipse"/>
+ <plugin id="org.eclipse.equinox.preferences"/>
+ <plugin id="org.eclipse.equinox.registry"/>
+ <plugin id="org.eclipse.equinox.security"/>
+ <plugin id="org.eclipse.equinox.simpleconfigurator"/>
+ <plugin id="org.eclipse.equinox.simpleconfigurator.manipulator"/>
+ <plugin id="org.eclipse.help"/>
+ <plugin id="org.eclipse.jdt.compiler.apt" fragment="true"/>
+ <plugin id="org.eclipse.jdt.compiler.tool" fragment="true"/>
+ <plugin id="org.eclipse.jdt.core"/>
+ <plugin id="org.eclipse.jdt.debug"/>
+ <plugin id="org.eclipse.jdt.launching"/>
+ <plugin id="org.eclipse.jface"/>
+ <plugin id="org.eclipse.jface.databinding"/>
+ <plugin id="org.eclipse.jface.text"/>
+ <plugin id="org.eclipse.ltk.core.refactoring"/>
+ <plugin id="org.eclipse.ltk.ui.refactoring"/>
+ <plugin id="org.eclipse.osgi"/>
+ <plugin id="org.eclipse.osgi.services"/>
+ <plugin id="org.eclipse.pde.build"/>
+ <plugin id="org.eclipse.pde.core"/>
+ <plugin id="org.eclipse.swt"/>
+ <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true"/>
+ <plugin id="org.eclipse.team.core"/>
+ <plugin id="org.eclipse.team.ui"/>
+ <plugin id="org.eclipse.text"/>
+ <plugin id="org.eclipse.ui"/>
+ <plugin id="org.eclipse.ui.editors"/>
+ <plugin id="org.eclipse.ui.forms"/>
+ <plugin id="org.eclipse.ui.ide"/>
+ <plugin id="org.eclipse.ui.navigator"/>
+ <plugin id="org.eclipse.ui.views"/>
+ <plugin id="org.eclipse.ui.workbench"/>
+ <plugin id="org.eclipse.ui.workbench.texteditor"/>
+ <plugin id="org.eclipse.update.configurator"/>
+ <plugin id="org.eclipselabs.tapiji.translator"/>
+ <plugin id="org.eclipselabs.tapiji.translator.rbe" fragment=""/>
+ <plugin id="org.eclipselabs.tapiji.translator.rcp" fragment="true"/>
+ <plugin id="org.eclipselabs.tapiji.translator.rcp.compat"/>
+ <plugin id="org.hamcrest.core"/>
+ <plugin id="org.junit"/>
+ <plugin id="org.sat4j.core"/>
+ <plugin id="org.sat4j.pb"/>
+ </plugins>
+
+
+</product>
diff --git a/org.eclipselabs.tapiji.translator/plugin.xml b/org.eclipselabs.tapiji.translator/plugin.xml
index 4ca5318b..a886e314 100644
--- a/org.eclipselabs.tapiji.translator/plugin.xml
+++ b/org.eclipselabs.tapiji.translator/plugin.xml
@@ -1,16 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
-
- <extension
- id="application"
- point="org.eclipse.core.runtime.applications">
- <application>
- <run
- class="org.eclipselabs.tapiji.translator.Application">
- </run>
- </application>
+ <extension
+ point="org.eclipse.ui.bindings">
+ <key
+ commandId="org.eclipselabs.tapiji.translator.fileOpen"
+ contextId="org.eclipse.ui.contexts.window"
+ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
+ sequence="M1+O">
+ </key>
+ <key
+ commandId="org.eclipse.ui.help.aboutAction"
+ contextId="org.eclipse.ui.contexts.window"
+ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
+ sequence="M1+A">
+ </key>
</extension>
+
<extension
point="org.eclipse.ui.perspectives">
<perspective
@@ -25,34 +31,7 @@
targetID="*">
</perspectiveExtension>
</extension>
- <extension
- id="product"
- point="org.eclipse.core.runtime.products">
- <product
- application="org.eclipselabs.tapiji.application"
- name="TapiJI Translator">
- <property
- name="windowImages"
- value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
- </property>
- <property
- name="appName"
- value="TapiJI Translator">
- </property>
- <property
- name="aboutImage"
- value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
- </property>
- <property
- name="aboutText"
- value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
- </property>
- <property
- name="preferenceCustomization"
- value="plugin_customization.ini">
- </property>
- </product>
- </extension>
+
<extension
point="org.eclipse.ui.commands">
<command
@@ -70,21 +49,7 @@
name="New Glossary ...">
</command>
</extension>
- <extension
- point="org.eclipse.ui.bindings">
- <key
- commandId="org.eclipselabs.tapiji.translator.fileOpen"
- contextId="org.eclipse.ui.contexts.window"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="M1+O">
- </key>
- <key
- commandId="org.eclipse.ui.help.aboutAction"
- contextId="org.eclipse.ui.contexts.window"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="M1+A">
- </key>
- </extension>
+
<extension
point="org.eclipse.ui.actionSets">
<actionSet
@@ -166,5 +131,6 @@
value="TapiJI Translator">
</property>
</product>
- </extension>
+ </extension>
+
</plugin>
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
index 6689bdfe..fe5188e1 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
@@ -1,61 +1,78 @@
-package org.eclipselabs.tapiji.translator;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given plug-in
+ * relative path
+ *
+ * @param path
+ * the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java
deleted file mode 100644
index bd06d884..00000000
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package org.eclipselabs.tapiji.translator;
-
-import org.eclipse.equinox.app.IApplication;
-import org.eclipse.equinox.app.IApplicationContext;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class controls all aspects of the application's execution
- */
-public class Application implements IApplication {
-
- /* (non-Javadoc)
- * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
- */
- public Object start(IApplicationContext context) {
- Display display = PlatformUI.createDisplay();
- try {
- int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
- if (returnCode == PlatformUI.RETURN_RESTART) {
- return IApplication.EXIT_RESTART;
- }
- return IApplication.EXIT_OK;
- } finally {
- display.dispose();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.equinox.app.IApplication#stop()
- */
- public void stop() {
- if (!PlatformUI.isWorkbenchRunning())
- return;
- final IWorkbench workbench = PlatformUI.getWorkbench();
- final Display display = workbench.getDisplay();
- display.syncExec(new Runnable() {
- public void run() {
- if (!display.isDisposed())
- workbench.close();
- }
- });
- }
-}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
index bd96f8c5..1f7dbeff 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.jface.action.GroupMarker;
@@ -26,47 +36,51 @@ 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"));
- {
+
+ 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(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 ToolBarContributionItem(fileToolBar,
+ IWorkbenchActionConstants.TOOLBAR_FILE));
}
-
+
coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR));
}
-
+
@Override
protected void fillMenuBar(IMenuManager menuBar) {
super.fillMenuBar(menuBar);
-
+
menuBar.add(fileMenu());
- menuBar.add(new GroupMarker (IWorkbenchActionConstants.MB_ADDITIONS));
+ menuBar.add(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()));
-
+ private MenuManager helpMenu() {
+ MenuManager helpMenu = new MenuManager("&Help",
+ IWorkbenchActionConstants.M_HELP);
+
+ // TODO [RAP] 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));
@@ -79,30 +93,32 @@ private MenuManager fileMenu() {
menu.add(getAction(ActionFactory.SAVE.getId()));
menu.add(getAction(ActionFactory.SAVE_ALL.getId()));
- menu.add(ContributionItemFactory.REOPEN_EDITORS.create(getActionBarConfigurer().getWindowConfigurer().getWindow()));
+ 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));
+ //TODO [RAP] 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 666e751b..5a897172 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.ui.application.IWorkbenchConfigurer;
@@ -10,14 +20,14 @@ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective";
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer) {
+ IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}
public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}
-
+
@Override
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
index 40b88788..9e5a77fc 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.core.runtime.CoreException;
@@ -22,26 +32,26 @@
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
/** Workbench state **/
private IWorkbenchWindow window;
-
+
/** System tray item / icon **/
private TrayItem trayItem;
private Image trayImage;
-
+
/** Command ids **/
- private final static String COMMAND_ABOUT_ID = "org.eclipse.ui.help.aboutAction";
- private final static String COMMAND_EXIT_ID = "org.eclipse.ui.file.exit";
-
- public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
+ 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) {
+ IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
@@ -50,36 +60,36 @@ public void preWindowOpen() {
configurer.setShowFastViewBars(true);
configurer.setShowCoolBar(true);
configurer.setShowStatusLine(true);
- configurer.setInitialSize(new Point (1024, 768));
-
+ configurer.setInitialSize(new Point(1024, 768));
+
/** Init workspace and container project */
try {
FileUtils.getProject();
} catch (CoreException e) {
}
}
-
+
@Override
public void postWindowOpen() {
super.postWindowOpen();
window = getWindowConfigurer().getWindow();
-
+
/** Add the application into the system tray icon section **/
- trayItem = initTrayItem (window);
-
+ 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) {
+ public void shellIconified(ShellEvent e) {
window.getShell().setMinimized(true);
window.getShell().setVisible(false);
}
});
-
+
trayItem.addListener(SWT.DefaultSelection, new Listener() {
- public void handleEvent (Event event) {
+ public void handleEvent(Event event) {
Shell shell = window.getShell();
if (!shell.isVisible() || window.getShell().getMinimized()) {
window.getShell().setMinimized(false);
@@ -87,68 +97,79 @@ public void handleEvent (Event event) {
}
}
});
-
+
// Add actions menu
- hookActionsMenu ();
+ hookActionsMenu();
}
}
-
- private void hookActionsMenu () {
- trayItem.addListener (SWT.MenuDetect, new Listener () {
+
+ 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 () {
+ 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);
+ 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);
-
+
+ MenuItem sep = new MenuItem(menu, SWT.SEPARATOR);
+
// Add exit action
- MenuItem exit = new MenuItem (menu, SWT.NONE);
+ MenuItem exit = new MenuItem(menu, SWT.NONE);
exit.setText("Exit");
- exit.addListener (SWT.Selection, new Listener() {
+ 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);
+ IHandlerService handlerService = (IHandlerService) window
+ .getService(IHandlerService.class);
try {
- handlerService.executeCommand (COMMAND_EXIT_ID, null);
+ handlerService
+ .executeCommand(COMMAND_EXIT_ID, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
-
+
menu.setVisible(true);
}
});
}
-
- private TrayItem initTrayItem (IWorkbenchWindow window) {
+
+ 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();
+ // no support for system tray (RAP)
+ if (osTray == null) {
+ return null;
+ }
+
+ 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 {
@@ -156,7 +177,7 @@ public void dispose() {
} catch (Exception e) {
e.printStackTrace();
}
-
+
try {
if (trayImage != null)
trayImage.dispose();
@@ -166,7 +187,7 @@ public void dispose() {
e.printStackTrace();
}
}
-
+
@Override
public void postWindowClose() {
super.postWindowClose();
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java
index d1fcd27a..910e91fe 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,26 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipselabs.tapiji.translator.views.GlossaryView;
-
public class Perspective implements IPerspectiveFactory {
-
+
public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(true);
layout.setFixed(true);
-
- initEditorArea (layout);
- initViewsArea (layout);
+
+ initEditorArea(layout);
+ initViewsArea(layout);
}
private void initViewsArea(IPageLayout layout) {
- layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM, .6f, IPageLayout.ID_EDITOR_AREA);
+ layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM,
+ .6f, IPageLayout.ID_EDITOR_AREA);
}
private void initEditorArea(IPageLayout layout) {
-
+
}
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
index 4bb6865c..3bfaa322 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,60 +1,75 @@
-package org.eclipselabs.tapiji.translator.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
-
-public class FileOpenAction extends Action implements IWorkbenchWindowActionDelegate {
-
- /** Editor ids **/
- public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor";
-
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "Open Resource-Bundle", SWT.OPEN, new String[] {"*.properties"} );
- if (!FileUtils.isResourceBundle(fileName)) {
- MessageDialog.openError(window.getShell(),
- "Cannot open Resource-Bundle", "The choosen file does not represent a Resource-Bundle!");
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- try {
- page.openEditor(new FileEditorInput(FileUtils.getResourceBundleRef(fileName)),
- RESOURCE_BUNDLE_EDITOR);
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.actions;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+public class FileOpenAction extends Action implements
+ IWorkbenchWindowActionDelegate {
+
+ /** Editor ids **/
+ public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
+
+ private IWorkbenchWindow window;
+
+ @Override
+ public void run(IAction action) {
+ String fileName = FileUtils.queryFileName(window.getShell(),
+ "Open Resource-Bundle", SWT.OPEN,
+ new String[] { "*.properties" });
+ if (!FileUtils.isResourceBundle(fileName)) {
+ MessageDialog.openError(window.getShell(),
+ "Cannot open Resource-Bundle",
+ "The choosen file does not represent a Resource-Bundle!");
+ return;
+ }
+
+ if (fileName != null) {
+ IWorkbenchPage page = window.getActivePage();
+ try {
+ page.openEditor(
+ new FileEditorInput(FileUtils
+ .getResourceBundleRef(fileName)),
+ RESOURCE_BUNDLE_EDITOR);
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ window = null;
+ }
+
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
index 967c0814..ad78187d 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
@@ -1,63 +1,74 @@
-package org.eclipselabs.tapiji.translator.actions;
-
-import java.io.File;
-import java.text.MessageFormat;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
-
-public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window */
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "New Glossary", SWT.SAVE, new String[] {"*.xml"} );
-
- if (!fileName.endsWith(".xml")) {
- if (fileName.endsWith("."))
- fileName += "xml";
- else
- fileName += ".xml";
- }
-
- if (new File (fileName).exists()) {
- String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?";
- MessageFormat mf = new MessageFormat(recallPattern);
-
- if (!MessageDialog.openQuestion(window.getShell(),
- "File already exists!", mf.format(new String[] {fileName})))
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- GlossaryManager.newGlossary (new File (fileName));
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- }
-
- @Override
- public void dispose() {
- this.window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.actions;
+
+import java.io.File;
+import java.text.MessageFormat;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
+
+ /** The workbench window */
+ private IWorkbenchWindow window;
+
+ @Override
+ public void run(IAction action) {
+ String fileName = FileUtils.queryFileName(window.getShell(),
+ "New Glossary", SWT.SAVE, new String[] { "*.xml" });
+
+ if (!fileName.endsWith(".xml")) {
+ if (fileName.endsWith("."))
+ fileName += "xml";
+ else
+ fileName += ".xml";
+ }
+
+ if (new File(fileName).exists()) {
+ String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?";
+ MessageFormat mf = new MessageFormat(recallPattern);
+
+ if (!MessageDialog.openQuestion(window.getShell(),
+ "File already exists!",
+ mf.format(new String[] { fileName })))
+ return;
+ }
+
+ if (fileName != null) {
+ IWorkbenchPage page = window.getActivePage();
+ GlossaryManager.newGlossary(new File(fileName));
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+
+ }
+
+ @Override
+ public void dispose() {
+ this.window = null;
+ }
+
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
index b2556c2c..2ba8eb2d 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
@@ -1,53 +1,63 @@
-package org.eclipselabs.tapiji.translator.actions;
-
-import java.io.File;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
-
-public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window */
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "Open Glossary", SWT.OPEN, new String[] {"*.xml"} );
- if (!FileUtils.isGlossary(fileName)) {
- MessageDialog.openError(window.getShell(),
- "Cannot open Glossary", "The choosen file does not represent a Glossary!");
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- if (fileName != null) {
- GlossaryManager.loadGlossary(new File (fileName));
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- }
-
- @Override
- public void dispose() {
- this.window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.actions;
+
+import java.io.File;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
+
+ /** The workbench window */
+ private IWorkbenchWindow window;
+
+ @Override
+ public void run(IAction action) {
+ String fileName = FileUtils.queryFileName(window.getShell(),
+ "Open Glossary", SWT.OPEN, new String[] { "*.xml" });
+ if (!FileUtils.isGlossary(fileName)) {
+ MessageDialog.openError(window.getShell(), "Cannot open Glossary",
+ "The choosen file does not represent a Glossary!");
+ return;
+ }
+
+ if (fileName != null) {
+ IWorkbenchPage page = window.getActivePage();
+ if (fileName != null) {
+ GlossaryManager.loadGlossary(new File(fileName));
+ }
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+
+ }
+
+ @Override
+ public void dispose() {
+ this.window = null;
+ }
+
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
index 5ce5a885..e59ed45d 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
@@ -1,82 +1,93 @@
-package org.eclipselabs.tapiji.translator.core;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-
-import org.eclipselabs.tapiji.translator.model.Glossary;
-
-
-public class GlossaryManager {
-
- private Glossary glossary;
- private File file;
- private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener> ();
-
- public GlossaryManager (File file, boolean overwrite) throws Exception {
- this.file = file;
-
- if (file.exists() && !overwrite) {
- // load the existing glossary
- glossary = new Glossary();
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Unmarshaller unmarshaller = context.createUnmarshaller();
- glossary = (Glossary) unmarshaller.unmarshal(file);
- } else {
- // Create a new glossary
- glossary = new Glossary ();
- saveGlossary();
- }
- }
-
- public void saveGlossary () throws Exception {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16");
-
- OutputStream fout = new FileOutputStream (file.getAbsolutePath());
- OutputStream bout = new BufferedOutputStream (fout);
- marshaller.marshal(glossary, new OutputStreamWriter (bout, "UTF-16"));
- }
-
- public void setGlossary (Glossary glossary) {
- this.glossary = glossary;
- }
-
- public Glossary getGlossary () {
- return glossary;
- }
-
- public static void loadGlossary (File file) {
- /* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
- for (ILoadGlossaryListener listener : loadGlossaryListeners) {
- listener.glossaryLoaded(event);
- }
- }
-
- public static void registerLoadGlossaryListener (ILoadGlossaryListener listener) {
- loadGlossaryListeners.add(listener);
- }
-
- public static void unregisterLoadGlossaryListener (ILoadGlossaryListener listener) {
- loadGlossaryListeners.remove(listener);
- }
-
- public static void newGlossary(File file) {
- /* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
- event.setNewGlossary(true);
- for (ILoadGlossaryListener listener : loadGlossaryListeners) {
- listener.glossaryLoaded(event);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.core;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import org.eclipselabs.tapiji.translator.model.Glossary;
+
+public class GlossaryManager {
+
+ private Glossary glossary;
+ private File file;
+ private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener>();
+
+ public GlossaryManager(File file, boolean overwrite) throws Exception {
+ this.file = file;
+
+ if (file.exists() && !overwrite) {
+ // load the existing glossary
+ glossary = new Glossary();
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ glossary = (Glossary) unmarshaller.unmarshal(file);
+ } else {
+ // Create a new glossary
+ glossary = new Glossary();
+ saveGlossary();
+ }
+ }
+
+ public void saveGlossary() throws Exception {
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16");
+
+ OutputStream fout = new FileOutputStream(file.getAbsolutePath());
+ OutputStream bout = new BufferedOutputStream(fout);
+ marshaller.marshal(glossary, new OutputStreamWriter(bout, "UTF-16"));
+ }
+
+ public void setGlossary(Glossary glossary) {
+ this.glossary = glossary;
+ }
+
+ public Glossary getGlossary() {
+ return glossary;
+ }
+
+ public static void loadGlossary(File file) {
+ /* Inform the listeners */
+ LoadGlossaryEvent event = new LoadGlossaryEvent(file);
+ for (ILoadGlossaryListener listener : loadGlossaryListeners) {
+ listener.glossaryLoaded(event);
+ }
+ }
+
+ public static void registerLoadGlossaryListener(
+ ILoadGlossaryListener listener) {
+ loadGlossaryListeners.add(listener);
+ }
+
+ public static void unregisterLoadGlossaryListener(
+ ILoadGlossaryListener listener) {
+ loadGlossaryListeners.remove(listener);
+ }
+
+ public static void newGlossary(File file) {
+ /* Inform the listeners */
+ LoadGlossaryEvent event = new LoadGlossaryEvent(file);
+ event.setNewGlossary(true);
+ for (ILoadGlossaryListener listener : loadGlossaryListeners) {
+ listener.glossaryLoaded(event);
+ }
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
index 3d3a263f..e460f2d1 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
@@ -1,7 +1,17 @@
-package org.eclipselabs.tapiji.translator.core;
-
-public interface ILoadGlossaryListener {
-
- void glossaryLoaded (LoadGlossaryEvent event);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.core;
+
+public interface ILoadGlossaryListener {
+
+ void glossaryLoaded(LoadGlossaryEvent event);
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
index 54bc3891..65cbd414 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
@@ -1,30 +1,40 @@
-package org.eclipselabs.tapiji.translator.core;
-
-import java.io.File;
-
-public class LoadGlossaryEvent {
-
- private boolean newGlossary = false;
- private File glossaryFile;
-
- public LoadGlossaryEvent (File glossaryFile) {
- this.glossaryFile = glossaryFile;
- }
-
- public File getGlossaryFile() {
- return glossaryFile;
- }
-
- public void setNewGlossary(boolean newGlossary) {
- this.newGlossary = newGlossary;
- }
-
- public boolean isNewGlossary() {
- return newGlossary;
- }
-
- public void setGlossaryFile(File glossaryFile) {
- this.glossaryFile = glossaryFile;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.core;
+
+import java.io.File;
+
+public class LoadGlossaryEvent {
+
+ private boolean newGlossary = false;
+ private File glossaryFile;
+
+ public LoadGlossaryEvent(File glossaryFile) {
+ this.glossaryFile = glossaryFile;
+ }
+
+ public File getGlossaryFile() {
+ return glossaryFile;
+ }
+
+ public void setNewGlossary(boolean newGlossary) {
+ this.newGlossary = newGlossary;
+ }
+
+ public boolean isNewGlossary() {
+ return newGlossary;
+ }
+
+ public void setGlossaryFile(File glossaryFile) {
+ this.glossaryFile = glossaryFile;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
index 61607d56..d03b760e 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
@@ -1,75 +1,85 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class Glossary implements Serializable {
-
- private static final long serialVersionUID = 2070750758712154134L;
-
- public Info info;
-
- @XmlElementWrapper (name="terms")
- @XmlElement (name = "term")
- public List<Term> terms;
-
- public Glossary() {
- terms = new ArrayList <Term> ();
- info = new Info();
- }
-
- public Term[] getAllTerms () {
- return terms.toArray(new Term [terms.size()]);
- }
-
- public int getIndexOfLocale(String referenceLocale) {
- int i = 0;
-
- for (String locale : info.translations) {
- if (locale.equalsIgnoreCase(referenceLocale))
- return i;
- i++;
- }
-
- return 0;
- }
-
- public void removeTerm(Term elem) {
- for (Term term : terms) {
- if (term == elem) {
- terms.remove(term);
- break;
- }
-
- if (term.removeTerm (elem))
- break;
- }
- }
-
- public void addTerm(Term parentTerm, Term newTerm) {
- if (parentTerm == null) {
- this.terms.add(newTerm);
- return;
- }
-
- for (Term term : terms) {
- if (term == parentTerm) {
- term.subTerms.add(newTerm);
- break;
- }
-
- if (term.addTerm (parentTerm, newTerm))
- break;
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.FIELD)
+public class Glossary implements Serializable {
+
+ private static final long serialVersionUID = 2070750758712154134L;
+
+ public Info info;
+
+ @XmlElementWrapper(name = "terms")
+ @XmlElement(name = "term")
+ public List<Term> terms;
+
+ public Glossary() {
+ terms = new ArrayList<Term>();
+ info = new Info();
+ }
+
+ public Term[] getAllTerms() {
+ return terms.toArray(new Term[terms.size()]);
+ }
+
+ public int getIndexOfLocale(String referenceLocale) {
+ int i = 0;
+
+ for (String locale : info.translations) {
+ if (locale.equalsIgnoreCase(referenceLocale))
+ return i;
+ i++;
+ }
+
+ return 0;
+ }
+
+ public void removeTerm(Term elem) {
+ for (Term term : terms) {
+ if (term == elem) {
+ terms.remove(term);
+ break;
+ }
+
+ if (term.removeTerm(elem))
+ break;
+ }
+ }
+
+ public void addTerm(Term parentTerm, Term newTerm) {
+ if (parentTerm == null) {
+ this.terms.add(newTerm);
+ return;
+ }
+
+ for (Term term : terms) {
+ if (term == parentTerm) {
+ term.subTerms.add(newTerm);
+ break;
+ }
+
+ if (term.addTerm(parentTerm, newTerm))
+ break;
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java
index f7abdc18..24376dc0 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java
@@ -1,32 +1,42 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-public class Info implements Serializable {
-
- private static final long serialVersionUID = 8607746669906026928L;
-
- @XmlElementWrapper (name = "locales")
- @XmlElement (name = "locale")
- public List<String> translations;
-
- public Info () {
- this.translations = new ArrayList<String>();
-
- // Add the default Locale
- this.translations.add("Default");
- }
-
- public String[] getTranslations () {
- return translations.toArray(new String [translations.size()]);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+
+@XmlAccessorType(XmlAccessType.FIELD)
+public class Info implements Serializable {
+
+ private static final long serialVersionUID = 8607746669906026928L;
+
+ @XmlElementWrapper(name = "locales")
+ @XmlElement(name = "locale")
+ public List<String> translations;
+
+ public Info() {
+ this.translations = new ArrayList<String>();
+
+ // Add the default Locale
+ this.translations.add("Default");
+ }
+
+ public String[] getTranslations() {
+ return translations.toArray(new String[translations.size()]);
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java
index 26bef6e2..afa6f3d3 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java
@@ -1,106 +1,116 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlTransient;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-public class Term implements Serializable {
-
- private static final long serialVersionUID = 7004998590181568026L;
-
- @XmlElementWrapper (name = "translations")
- @XmlElement (name = "translation")
- public List<Translation> translations;
-
- @XmlElementWrapper (name = "terms")
- @XmlElement (name = "term")
- public List<Term> subTerms;
-
- public Term parentTerm;
-
- @XmlTransient
- private Object info;
-
- public Term () {
- translations = new ArrayList<Translation> ();
- subTerms = new ArrayList<Term> ();
- parentTerm = null;
- info = null;
- }
-
- public void setInfo(Object info) {
- this.info = info;
- }
-
- public Object getInfo() {
- return info;
- }
-
- public Term[] getAllSubTerms () {
- return subTerms.toArray(new Term[subTerms.size()]);
- }
-
- public Term getParentTerm() {
- return parentTerm;
- }
-
- public boolean hasChildTerms () {
- return subTerms != null && subTerms.size() > 0;
- }
-
- public Translation[] getAllTranslations() {
- return translations.toArray(new Translation [translations.size()]);
- }
-
- public Translation getTranslation (String language) {
- for (Translation translation : translations) {
- if (translation.id.equalsIgnoreCase(language))
- return translation;
- }
-
- Translation newTranslation = new Translation ();
- newTranslation.id = language;
- translations.add(newTranslation);
-
- return newTranslation;
- }
-
- public boolean removeTerm(Term elem) {
- boolean hasFound = false;
- for (Term subTerm : subTerms) {
- if (subTerm == elem) {
- subTerms.remove(elem);
- hasFound = true;
- break;
- } else {
- hasFound = subTerm.removeTerm(elem);
- if (hasFound)
- break;
- }
- }
- return hasFound;
- }
-
- public boolean addTerm(Term parentTerm, Term newTerm) {
- boolean hasFound = false;
- for (Term subTerm : subTerms) {
- if (subTerm == parentTerm) {
- subTerms.add(newTerm);
- hasFound = true;
- break;
- } else {
- hasFound = subTerm.addTerm(parentTerm, newTerm);
- if (hasFound)
- break;
- }
- }
- return hasFound;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlTransient;
+
+@XmlAccessorType(XmlAccessType.FIELD)
+public class Term implements Serializable {
+
+ private static final long serialVersionUID = 7004998590181568026L;
+
+ @XmlElementWrapper(name = "translations")
+ @XmlElement(name = "translation")
+ public List<Translation> translations;
+
+ @XmlElementWrapper(name = "terms")
+ @XmlElement(name = "term")
+ public List<Term> subTerms;
+
+ public Term parentTerm;
+
+ @XmlTransient
+ private Object info;
+
+ public Term() {
+ translations = new ArrayList<Translation>();
+ subTerms = new ArrayList<Term>();
+ parentTerm = null;
+ info = null;
+ }
+
+ public void setInfo(Object info) {
+ this.info = info;
+ }
+
+ public Object getInfo() {
+ return info;
+ }
+
+ public Term[] getAllSubTerms() {
+ return subTerms.toArray(new Term[subTerms.size()]);
+ }
+
+ public Term getParentTerm() {
+ return parentTerm;
+ }
+
+ public boolean hasChildTerms() {
+ return subTerms != null && subTerms.size() > 0;
+ }
+
+ public Translation[] getAllTranslations() {
+ return translations.toArray(new Translation[translations.size()]);
+ }
+
+ public Translation getTranslation(String language) {
+ for (Translation translation : translations) {
+ if (translation.id.equalsIgnoreCase(language))
+ return translation;
+ }
+
+ Translation newTranslation = new Translation();
+ newTranslation.id = language;
+ translations.add(newTranslation);
+
+ return newTranslation;
+ }
+
+ public boolean removeTerm(Term elem) {
+ boolean hasFound = false;
+ for (Term subTerm : subTerms) {
+ if (subTerm == elem) {
+ subTerms.remove(elem);
+ hasFound = true;
+ break;
+ } else {
+ hasFound = subTerm.removeTerm(elem);
+ if (hasFound)
+ break;
+ }
+ }
+ return hasFound;
+ }
+
+ public boolean addTerm(Term parentTerm, Term newTerm) {
+ boolean hasFound = false;
+ for (Term subTerm : subTerms) {
+ if (subTerm == parentTerm) {
+ subTerms.add(newTerm);
+ hasFound = true;
+ break;
+ } else {
+ hasFound = subTerm.addTerm(parentTerm, newTerm);
+ if (hasFound)
+ break;
+ }
+ }
+ return hasFound;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java
index 624b5066..b62184ea 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java
@@ -1,24 +1,34 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-@XmlType (name = "Translation")
-public class Translation implements Serializable {
-
- private static final long serialVersionUID = 2033276999496196690L;
-
- public String id;
-
- public String value;
-
- public Translation () {
- id = "";
- value = "";
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "Translation")
+public class Translation implements Serializable {
+
+ private static final long serialVersionUID = 2033276999496196690L;
+
+ public String id;
+
+ public String value;
+
+ public Translation() {
+ id = "";
+ value = "";
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
index 57872066..ac86bb59 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
@@ -1,127 +1,136 @@
-package org.eclipselabs.tapiji.translator.tests;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.util.ArrayList;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Info;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.junit.Assert;
-import org.junit.Test;
-
-
-public class JaxBTest {
-
- @Test
- public void testModel () {
- Glossary glossary = new Glossary ();
- Info info = new Info ();
- info.translations = new ArrayList<String>();
- info.translations.add("default");
- info.translations.add("de");
- info.translations.add("en");
- glossary.info = info;
- glossary.terms = new ArrayList<Term>();
-
- // Hello World
- Term term = new Term();
-
- Translation tranl1 = new Translation ();
- tranl1.id = "default";
- tranl1.value = "Hallo Welt";
-
- Translation tranl2 = new Translation ();
- tranl2.id = "de";
- tranl2.value = "Hallo Welt";
-
- Translation tranl3 = new Translation ();
- tranl3.id = "en";
- tranl3.value = "Hello World!";
-
- term.translations = new ArrayList <Translation>();
- term.translations.add(tranl1);
- term.translations.add(tranl2);
- term.translations.add(tranl3);
- term.parentTerm = null;
-
- glossary.terms.add(term);
-
- // Hello World 2
- Term term2 = new Term();
-
- Translation tranl12 = new Translation ();
- tranl12.id = "default";
- tranl12.value = "Hallo Welt2";
-
- Translation tranl22 = new Translation ();
- tranl22.id = "de";
- tranl22.value = "Hallo Welt2";
-
- Translation tranl32 = new Translation ();
- tranl32.id = "en";
- tranl32.value = "Hello World2!";
-
- term2.translations = new ArrayList <Translation>();
- term2.translations.add(tranl12);
- term2.translations.add(tranl22);
- term2.translations.add(tranl32);
- //term2.parentTerm = term;
-
- term.subTerms = new ArrayList<Term>();
- term.subTerms.add(term2);
-
- // Hello World 3
- Term term3 = new Term();
-
- Translation tranl13 = new Translation ();
- tranl13.id = "default";
- tranl13.value = "Hallo Welt3";
-
- Translation tranl23 = new Translation ();
- tranl23.id = "de";
- tranl23.value = "Hallo Welt3";
-
- Translation tranl33 = new Translation ();
- tranl33.id = "en";
- tranl33.value = "Hello World3!";
-
- term3.translations = new ArrayList <Translation>();
- term3.translations.add(tranl13);
- term3.translations.add(tranl23);
- term3.translations.add(tranl33);
- term3.parentTerm = null;
-
- glossary.terms.add(term3);
-
- // Serialize model
- try {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.marshal(glossary, new FileWriter ("C:\\test.xml"));
- } catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
- }
- }
-
- @Test
- public void testReadModel () {
- Glossary glossary = new Glossary();
-
- try {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Unmarshaller unmarshaller = context.createUnmarshaller();
- glossary = (Glossary) unmarshaller.unmarshal(new File ("C:\\test.xml"));
- } catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.tests;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.util.ArrayList;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Info;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class JaxBTest extends TestCase {
+
+ 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);
+ }
+ }
+
+ public void testReadModel() {
+ Glossary glossary = new Glossary();
+
+ try {
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ glossary = (Glossary) unmarshaller.unmarshal(new File(
+ "C:\\test.xml"));
+ } catch (Exception e) {
+ e.printStackTrace();
+ Assert.assertFalse(true);
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
index c4dc3957..5738a3a3 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
@@ -1,133 +1,149 @@
-package org.eclipselabs.tapiji.translator.utils;
-
-import java.io.File;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-
-public class FileUtils {
-
- /** Token to replace in a regular expression with a bundle name. */
- private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME";
- /** Token to replace in a regular expression with a file extension. */
- private static final String TOKEN_FILE_EXTENSION =
- "FILEEXTENSION";
- /** Regex to match a properties file. */
- private static final String PROPERTIES_FILE_REGEX =
- "^(" + TOKEN_BUNDLE_NAME + ")"
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + TOKEN_FILE_EXTENSION + ")$";
-
- /** The singleton instance of Workspace */
- private static IWorkspace workspace;
-
- /** Wrapper project for external file resources */
- private static IProject project;
-
- public static boolean isResourceBundle (String fileName) {
- return fileName.toLowerCase().endsWith(".properties");
- }
-
- public static boolean isGlossary (String fileName) {
- return fileName.toLowerCase().endsWith(".xml");
- }
-
- public static IWorkspace getWorkspace () {
- if (workspace == null) {
- workspace = ResourcesPlugin.getWorkspace();
- }
-
- return workspace;
- }
-
- public static IProject getProject () throws CoreException {
- if (project == null) {
- project = getWorkspace().getRoot().getProject("ExternalResourceBundles");
- }
-
- if (!project.exists())
- project.create(null);
- if (!project.isOpen())
- project.open(null);
-
- return project;
- }
-
- public static void prePareEditorInputs () {
- IWorkspace workspace = getWorkspace();
- }
-
- public static IFile getResourceBundleRef (String location) throws CoreException {
- IPath path = new Path (location);
-
- /** Create all files of the Resource-Bundle within the project space and link them to the original file */
- String regex = getPropertiesFileRegEx(path);
- String projPathName = toProjectRelativePathName(path);
- IFile file = getProject().getFile(projPathName);
- file.createLink(path, IResource.REPLACE, null);
-
- File parentDir = new File (path.toFile().getParent());
- String[] files = parentDir.list();
-
- for (String fn : files) {
- File fo = new File (parentDir, fn);
- if (!fo.isFile())
- continue;
-
- IPath newFilePath = new Path(fo.getAbsolutePath());
- if (fo.getName().matches(regex) && !path.toFile().getName().equals(newFilePath.toFile().getName())) {
- IFile newFile = project.getFile(toProjectRelativePathName(newFilePath));
- newFile.createLink(newFilePath, IResource.REPLACE, null);
- }
- }
-
- return file;
- }
-
- protected static String toProjectRelativePathName (IPath path) {
- String projectRelativeName = "";
-
- projectRelativeName = path.toString().replaceAll(":", "");
- projectRelativeName = projectRelativeName.replaceAll("/", ".");
-
- return projectRelativeName;
- }
-
- protected static String getPropertiesFileRegEx(IPath file) {
- String bundleName = getBundleName(file);
- return PROPERTIES_FILE_REGEX.replaceFirst(
- TOKEN_BUNDLE_NAME, bundleName).replaceFirst(
- TOKEN_FILE_EXTENSION, file.getFileExtension());
- }
-
- public static String getBundleName(IPath file) {
- String name = file.toFile().getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + file.getFileExtension() + ")$";
- return name.replaceFirst(regex, "$1");
- }
-
- public static String queryFileName(Shell shell, String title, int dialogOptions, String[] endings) {
- FileDialog dialog= new FileDialog(shell, dialogOptions);
- dialog.setText( title );
- dialog.setFilterExtensions(endings);
- String path= dialog.open();
-
-
- if (path != null && path.length() > 0)
- return path;
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.utils;
+
+import java.io.File;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+
+public class FileUtils {
+
+ /** Token to replace in a regular expression with a bundle name. */
+ private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME";
+ /** Token to replace in a regular expression with a file extension. */
+ private static final String TOKEN_FILE_EXTENSION = "FILEEXTENSION";
+ /** Regex to match a properties file. */
+ private static final String PROPERTIES_FILE_REGEX = "^("
+ + TOKEN_BUNDLE_NAME + ")" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + TOKEN_FILE_EXTENSION
+ + ")$";
+
+ /** The singleton instance of Workspace */
+ private static IWorkspace workspace;
+
+ /** Wrapper project for external file resources */
+ private static IProject project;
+
+ public static boolean isResourceBundle(String fileName) {
+ return fileName.toLowerCase().endsWith(".properties");
+ }
+
+ public static boolean isGlossary(String fileName) {
+ return fileName.toLowerCase().endsWith(".xml");
+ }
+
+ public static IWorkspace getWorkspace() {
+ if (workspace == null) {
+ workspace = ResourcesPlugin.getWorkspace();
+ }
+
+ return workspace;
+ }
+
+ public static IProject getProject() throws CoreException {
+ if (project == null) {
+ project = getWorkspace().getRoot().getProject(
+ "ExternalResourceBundles");
+ }
+
+ if (!project.exists())
+ project.create(null);
+ if (!project.isOpen())
+ project.open(null);
+
+ return project;
+ }
+
+ public static void prePareEditorInputs() {
+ IWorkspace workspace = getWorkspace();
+ }
+
+ public static IFile getResourceBundleRef(String location)
+ throws CoreException {
+ IPath path = new Path(location);
+
+ /**
+ * Create all files of the Resource-Bundle within the project space and
+ * link them to the original file
+ */
+ String regex = getPropertiesFileRegEx(path);
+ String projPathName = toProjectRelativePathName(path);
+ IFile file = getProject().getFile(projPathName);
+ file.createLink(path, IResource.REPLACE, null);
+
+ File parentDir = new File(path.toFile().getParent());
+ String[] files = parentDir.list();
+
+ for (String fn : files) {
+ File fo = new File(parentDir, fn);
+ if (!fo.isFile())
+ continue;
+
+ IPath newFilePath = new Path(fo.getAbsolutePath());
+ if (fo.getName().matches(regex)
+ && !path.toFile().getName()
+ .equals(newFilePath.toFile().getName())) {
+ IFile newFile = project
+ .getFile(toProjectRelativePathName(newFilePath));
+ newFile.createLink(newFilePath, IResource.REPLACE, null);
+ }
+ }
+
+ return file;
+ }
+
+ protected static String toProjectRelativePathName(IPath path) {
+ String projectRelativeName = "";
+
+ projectRelativeName = path.toString().replaceAll(":", "");
+ projectRelativeName = projectRelativeName.replaceAll("/", ".");
+
+ return projectRelativeName;
+ }
+
+ protected static String getPropertiesFileRegEx(IPath file) {
+ String bundleName = getBundleName(file);
+ return PROPERTIES_FILE_REGEX
+ .replaceFirst(TOKEN_BUNDLE_NAME, bundleName).replaceFirst(
+ TOKEN_FILE_EXTENSION, file.getFileExtension());
+ }
+
+ public static String getBundleName(IPath file) {
+ String name = file.toFile().getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
+ + file.getFileExtension() + ")$";
+ return name.replaceFirst(regex, "$1");
+ }
+
+ public static String queryFileName(Shell shell, String title,
+ int dialogOptions, String[] endings) {
+ FileDialog dialog = new FileDialog(shell, dialogOptions);
+ dialog.setText(title);
+ dialog.setFilterExtensions(endings);
+ String path = dialog.open();
+
+ if (path != null && path.length() > 0)
+ return path;
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
index 92764ce8..a2828e2b 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
@@ -1,80 +1,102 @@
-package org.eclipselabs.tapiji.translator.utils;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.Activator;
-
-
-public class FontUtils {
-
- /**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
-
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.utils;
+
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipselabs.tapiji.translator.Activator;
+
+public class FontUtils {
+
+ /**
+ * Gets a system color.
+ *
+ * @param colorId
+ * SWT constant
+ * @return system color
+ */
+ public static Color getSystemColor(int colorId) {
+ return Activator.getDefault().getWorkbench().getDisplay()
+ .getSystemColor(colorId);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style (size is unaffected).
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style) {
+ // TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control and
+ * applying the provided style and relative size.
+ *
+ * @param control
+ * control we base our font data on
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style, int relSize) {
+ // TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
+ }
+
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(int style) {
+ return createFont(style, 0);
+ }
+
+ /**
+ * Creates a font by altering the system font and applying the provided
+ * style and relative size.
+ *
+ * @param style
+ * style to apply to the new font
+ * @param relSize
+ * size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(int style, int relSize) {
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
index 793a9913..2c2b504c 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,6 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator.views;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
@@ -42,8 +51,7 @@
import org.eclipselabs.tapiji.translator.views.menus.GlossaryEntryMenuContribution;
import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
import org.eclipselabs.tapiji.translator.views.widgets.model.GlossaryViewState;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
-
+import org.eclipselabs.tapiji.translator.views.widgets.provider.AbstractGlossaryLabelProvider;
public class GlossaryView extends ViewPart implements ILoadGlossaryListener {
@@ -51,13 +59,13 @@ 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;
@@ -72,42 +80,45 @@ public class GlossaryView extends ViewPart implements ILoadGlossaryListener {
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 () {
- /** Register the view for being informed each time a new glossary is loaded into the translator */
+ 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.
+ * 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);
+
+ initLayout(parent);
+ initSearchBar(parent);
+ initMessagesTree(parent);
makeActions();
hookContextMenu();
contributeToActionBars();
- initListener (parent);
+ initListener(parent);
}
-
- protected void initListener (Composite parent) {
+
+ protected void initListener(Composite parent) {
filter.addModifyListener(new ModifyListener() {
-
+
@Override
public void modifyText(ModifyEvent e) {
if (glossary != null && glossary.getGlossary() != null)
@@ -115,71 +126,76 @@ public void modifyText(ModifyEvent e) {
}
});
}
-
- protected void initLayout (Composite parent) {
- GridLayout mainLayout = new GridLayout ();
+
+ protected void initLayout(Composite parent) {
+ GridLayout mainLayout = new GridLayout();
mainLayout.numColumns = 1;
parent.setLayout(mainLayout);
-
+
}
-
- protected void initSearchBar (Composite parent) {
+
+ 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);
+ 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);
+
+ 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));
+ 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 = 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 = 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
+ .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;
@@ -187,52 +203,68 @@ public void handleEvent (Event event) {
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;
+
+ 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;
+ ((GridData) lblScale.getLayoutData()).heightHint = 0;
+ ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0;
}
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);
-
+ if (treeViewer != null
+ && treeViewer.getViewer() != null
+ && treeViewer.getViewer().getLabelProvider() != null
+ && treeViewer.getViewer().getLabelProvider() instanceof AbstractGlossaryLabelProvider)
+ getSite()
+ .getWorkbenchWindow()
+ .getSelectionService()
+ .removeSelectionListener(
+ ((AbstractGlossaryLabelProvider) 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 (treeViewer.getViewer() != null
+ && treeViewer.getViewer().getLabelProvider() != null
+ && treeViewer.getViewer().getLabelProvider() instanceof AbstractGlossaryLabelProvider)
+ getSite()
+ .getWorkbenchWindow()
+ .getSelectionService()
+ .addSelectionListener(
+ ((AbstractGlossaryLabelProvider) 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.bindContentToSelection(viewState
+ .isSelectiveViewEnabled());
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;
@@ -248,8 +280,8 @@ protected void initMessagesTree(Composite parent) {
public void setFocus() {
treeViewer.setFocus();
}
-
- protected void redrawTreeViewer () {
+
+ protected void redrawTreeViewer() {
parent.setRedraw(false);
treeViewer.dispose();
try {
@@ -265,34 +297,38 @@ protected void redrawTreeViewer () {
treeViewer.layout(true);
refreshSearchbarState();
}
-
+
/*** ACTIONS ***/
private void makeActions() {
- newEntry = new Action () {
+ newEntry = new Action() {
@Override
public void run() {
super.run();
}
};
- newEntry.setText ("New term ...");
+ newEntry.setText("New term ...");
newEntry.setDescription("Creates a new glossary entry");
newEntry.setToolTipText("Creates a new glossary entry");
-
- enableFuzzyMatching = new Action () {
- public void run () {
+
+ enableFuzzyMatching = new Action() {
+ public void run() {
super.run();
- treeViewer.enableFuzzyMatching(!treeViewer.isFuzzyMatchingEnabled());
- viewState.setFuzzyMatchingEnabled(treeViewer.isFuzzyMatchingEnabled());
+ treeViewer.enableFuzzyMatching(!treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
refreshSearchbarState();
}
};
enableFuzzyMatching.setText("Fuzzy-Matching");
- enableFuzzyMatching.setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
+ enableFuzzyMatching
+ .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries.");
enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled());
- enableFuzzyMatching.setToolTipText(enableFuzzyMatching.getDescription());
-
- editable = new Action () {
- public void run () {
+ enableFuzzyMatching
+ .setToolTipText(enableFuzzyMatching.getDescription());
+
+ editable = new Action() {
+ public void run() {
super.run();
treeViewer.setEditable(!treeViewer.isEditable());
}
@@ -301,39 +337,46 @@ public void run () {
editable.setDescription("Allows you to edit Resource-Bundle entries.");
editable.setChecked(viewState.isEditable());
editable.setToolTipText(editable.getDescription());
-
+
/** New Translation */
- newTranslation = new Action ("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 */
+ /*
+ * 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]);
+ 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 */
+
+ /*
+ * 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());
+ return o1.getDisplayName().compareTo(
+ o2.getDisplayName());
}
});
- ListSelectionDialog dlg = new ListSelectionDialog(getSite().getShell(),
- allLocales,
- new LocaleContentProvider(),
- new LocaleLabelProvider(),
- "Select the Translation:");
+ 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();
@@ -357,35 +400,43 @@ public int compare(Locale o1, Locale o2) {
};
newTranslation.setDescription("Adds a new Locale for translation.");
newTranslation.setToolTipText(newTranslation.getDescription());
-
+
/** Delete Translation */
- deleteTranslation = new Action ("Delete Translation ...") {
+ deleteTranslation = new Action("Delete Translation ...") {
public void run() {
- /* Construct a list of type locale from all existing translations */
+ /*
+ * 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)
+
+ 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]);
+ 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:");
+
+ /*
+ * 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();
@@ -393,7 +444,8 @@ public void run() {
for (Object delLoc : delLocales) {
toRemove.add(strLoc.get(locales.indexOf(delLoc)));
}
- glossary.getGlossary().info.translations.removeAll(toRemove);
+ glossary.getGlossary().info.translations
+ .removeAll(toRemove);
try {
glossary.saveGlossary();
displayActions = null;
@@ -406,33 +458,36 @@ public void run() {
}
};
};
- deleteTranslation.setDescription("Deletes a specific Locale from the translation glossary.");
+ 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());
+ glossaryEditContribution = new GlossaryEntryMenuContribution(
+ treeViewer, !treeViewer.getViewer().getSelection()
+ .isEmpty());
manager.add(this.glossaryEditContribution);
manager.add(new Separator());
}
-
+
manager.add(enableFuzzyMatching);
manager.add(editable);
-
+
if (this.glossary != null && this.glossary.getGlossary() != null) {
manager.add(new Separator());
manager.add(newTranslation);
manager.add(deleteTranslation);
- createMenuAdditions (manager);
+ createMenuAdditions(manager);
}
}
@@ -445,40 +500,43 @@ public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
- Menu menu = menuMgr.createContextMenu(treeViewer.getViewer().getControl());
+ 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());
+ 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);
}
-
- createMenuAdditions (manager);
+
+ createMenuAdditions(manager);
}
-
- private void createShowContentMenu (IMenuManager manager) {
- showMenu = new MenuManager ("&Show", "show");
-
- if (showAll == null || showSelectiveContent == null) {
- showAll = new Action ("All terms", Action.AS_RADIO_BUTTON) {
+
+ 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();
@@ -488,56 +546,63 @@ public void run() {
showAll.setDescription("Display all glossary entries");
showAll.setToolTipText(showAll.getDescription());
showAll.setChecked(!viewState.isSelectiveViewEnabled());
-
- showSelectiveContent = new Action ("Relevant terms", Action.AS_RADIO_BUTTON) {
+
+ 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
+ .setDescription("Displays only terms that are relevant for the currently selected Resource-Bundle entry");
+ showSelectiveContent.setToolTipText(showSelectiveContent
+ .getDescription());
showSelectiveContent.setChecked(viewState.isSelectiveViewEnabled());
}
-
+
showMenu.add(showAll);
showMenu.add(showSelectiveContent);
-
+
manager.add(showMenu);
}
-
+
private void createMenuAdditions(IMenuManager manager) {
// Make reference language actions
- if (glossary != null && glossary.getGlossary() != null) {
+ 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");
+
+ 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) {
+ 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();
+ referenceLanguage = viewState
+ .getReferenceLanguage();
if (!lang.equalsIgnoreCase(referenceLanguage)) {
viewState.setReferenceLanguage(lang);
-
+
// trigger redraw of displayed translations menu
displayActions = null;
-
+
redrawTreeViewer();
}
}
@@ -546,42 +611,46 @@ public void run() {
String referenceLanguage = translations[0];
if (viewState.getReferenceLanguage() != null)
referenceLanguage = viewState.getReferenceLanguage();
- else
+ else
viewState.setReferenceLanguage(referenceLanguage);
-
- refLangAction.setChecked(lang.equalsIgnoreCase(referenceLanguage));
+
+ refLangAction.setChecked(lang
+ .equalsIgnoreCase(referenceLanguage));
refLangAction.setText(l.getDisplayName());
referenceActions.add(refLangAction);
}
}
-
+
for (Action a : referenceActions) {
referenceMenu.add(a);
}
-
+
// Make display language actions
- displayMenu = new MenuManager ("&Displayed Translations", "displaylang");
-
+ 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) {
+ 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();
@@ -603,11 +672,11 @@ public void run() {
displayActions.add(refLangAction);
}
}
-
+
for (Action a : displayActions) {
displayMenu.add(a);
}
-
+
manager.add(new Separator());
manager.add(referenceMenu);
manager.add(displayMenu);
@@ -616,32 +685,36 @@ public void run() {
private void fillLocalToolBar(IToolBarManager manager) {
}
-
+
@Override
- public void saveState (IMemento memento) {
+ public void saveState(IMemento memento) {
super.saveState(memento);
try {
- viewState.setEditable (treeViewer.isEditable());
+ 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.setFuzzyMatchingEnabled(treeViewer
+ .isFuzzyMatchingEnabled());
+ viewState.setMatchingPrecision(treeViewer.getMatchingPrecision());
+ viewState.setSelectiveViewEnabled(treeViewer
+ .isSelectiveViewEnabled());
viewState.saveState(memento);
- } catch (Exception e) {}
+ } 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);
+ glossary = new GlossaryManager(new File(
+ viewState.getGlossaryFile()), false);
} catch (Exception e) {
e.printStackTrace();
}
@@ -652,16 +725,19 @@ public void init(IViewSite site, IMemento memento) throws PartInitException {
public void glossaryLoaded(LoadGlossaryEvent event) {
File glossaryFile = event.getGlossaryFile();
try {
- this.glossary = new GlossaryManager (glossaryFile, event.isNewGlossary());
- viewState.setGlossaryFile (glossaryFile.getAbsolutePath());
-
+ this.glossary = new GlossaryManager(glossaryFile,
+ event.isNewGlossary());
+ viewState.setGlossaryFile(glossaryFile.getAbsolutePath());
+
referenceActions = null;
displayActions = null;
- viewState.setDisplayLangArr(glossary.getGlossary().info.getTranslations());
+ 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!");
+ MessageDialog.openError(getViewSite().getShell(),
+ "Cannot open Glossary",
+ "The choosen file does not represent a valid Glossary!");
}
}
-}
\ No newline at end of file
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
index cd0a4536..6c8fcec8 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
@@ -1,29 +1,39 @@
-package org.eclipselabs.tapiji.translator.views.dialog;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-public class LocaleContentProvider implements IStructuredContentProvider {
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
-
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof List) {
- List<Locale> locales = (List<Locale>) inputElement;
- return locales.toArray(new Locale[locales.size()]);
- }
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.dialog;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+public class LocaleContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public void dispose() {
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof List) {
+ List<Locale> locales = (List<Locale>) inputElement;
+ return locales.toArray(new Locale[locales.size()]);
+ }
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
index 6ba650a1..aa5f64f4 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
@@ -1,45 +1,55 @@
-package org.eclipselabs.tapiji.translator.views.dialog;
-
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Image;
-
-public class LocaleLabelProvider implements ILabelProvider {
-
- @Override
- public void addListener(ILabelProviderListener listener) {
-
- }
-
- @Override
- public void dispose() {
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
-
- }
-
- @Override
- public Image getImage(Object element) {
- // TODO add image output for Locale entries
- return null;
- }
-
- @Override
- public String getText(Object element) {
- if (element != null && element instanceof Locale)
- return ((Locale)element).getDisplayName();
-
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.dialog;
+
+import java.util.Locale;
+
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.swt.graphics.Image;
+
+public class LocaleLabelProvider implements ILabelProvider {
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+
+ }
+
+ @Override
+ public void dispose() {
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ // TODO add image output for Locale entries
+ return null;
+ }
+
+ @Override
+ public String getText(Object element) {
+ if (element != null && element instanceof Locale)
+ return ((Locale) element).getDisplayName();
+
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
index 658ce20a..2422e95b 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
@@ -1,92 +1,102 @@
-package org.eclipselabs.tapiji.translator.views.menus;
-
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
-
-
-public class GlossaryEntryMenuContribution extends ContributionItem implements
- ISelectionChangedListener {
-
- private GlossaryWidget parentView;
- private boolean legalSelection = false;
-
- // Menu-Items
- private MenuItem addItem;
- private MenuItem removeItem;
-
- public GlossaryEntryMenuContribution () {
- }
-
- public GlossaryEntryMenuContribution (GlossaryWidget view, boolean legalSelection) {
- this.legalSelection = legalSelection;
- this.parentView = view;
- parentView.addSelectionChangedListener(this);
- }
-
- @Override
- public void fill(Menu menu, int index) {
-
- // MenuItem for adding a new entry
- addItem = new MenuItem(menu, SWT.NONE, index);
- addItem.setText("Add ...");
- addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
- addItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.addNewItem();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
-
- if ((parentView == null && legalSelection) || parentView != null) {
- // MenuItem for deleting the currently selected entry
- removeItem = new MenuItem(menu, SWT.NONE, index + 1);
- removeItem.setText("Remove");
- removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
- .createImage());
- removeItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.deleteSelectedItems();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
- enableMenuItems();
- }
- }
-
- protected void enableMenuItems() {
- try {
- removeItem.setEnabled(legalSelection);
- } catch (Exception e) {
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- legalSelection = !event.getSelection().isEmpty();
-// enableMenuItems ();
- }
-
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.menus;
+
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
+
+public class GlossaryEntryMenuContribution extends ContributionItem implements
+ ISelectionChangedListener {
+
+ private GlossaryWidget parentView;
+ private boolean legalSelection = false;
+
+ // Menu-Items
+ private MenuItem addItem;
+ private MenuItem removeItem;
+
+ public GlossaryEntryMenuContribution() {
+ }
+
+ public GlossaryEntryMenuContribution(GlossaryWidget view,
+ boolean legalSelection) {
+ this.legalSelection = legalSelection;
+ this.parentView = view;
+ parentView.addSelectionChangedListener(this);
+ }
+
+ @Override
+ public void fill(Menu menu, int index) {
+
+ // MenuItem for adding a new entry
+ addItem = new MenuItem(menu, SWT.NONE, index);
+ addItem.setText("Add ...");
+ addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
+ addItem.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.addNewItem();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+
+ if ((parentView == null && legalSelection) || parentView != null) {
+ // MenuItem for deleting the currently selected entry
+ removeItem = new MenuItem(menu, SWT.NONE, index + 1);
+ removeItem.setText("Remove");
+ removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
+ .createImage());
+ removeItem.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.deleteSelectedItems();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+ enableMenuItems();
+ }
+ }
+
+ protected void enableMenuItems() {
+ try {
+ removeItem.setEnabled(legalSelection);
+ } catch (Exception e) {
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ legalSelection = !event.getSelection().isEmpty();
+ // enableMenuItems ();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
index fe5d4b84..8cf99021 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
@@ -1,630 +1,665 @@
-package org.eclipselabs.tapiji.translator.views.widgets;
-
-import java.awt.ComponentOrientation;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDragSource;
-import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDropTarget;
-import org.eclipselabs.tapiji.translator.views.widgets.dnd.TermTransfer;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.ExactMatcher;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.FuzzyMatcher;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.SelectiveMatcher;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
-import org.eclipselabs.tapiji.translator.views.widgets.sorter.GlossaryEntrySorter;
-import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-
-
-public class GlossaryWidget extends Composite implements IResourceChangeListener {
-
- private final int TERM_COLUMN_WEIGHT = 1;
- private final int DESCRIPTION_COLUMN_WEIGHT = 1;
-
- private boolean editable;
-
- private IWorkbenchPartSite site;
- private TreeColumnLayout basicLayout;
- private TreeViewer treeViewer;
- private TreeColumn termColumn;
- private boolean grouped = true;
- private boolean fuzzyMatchingEnabled = false;
- private boolean selectiveViewEnabled = false;
- private float matchingPrecision = .75f;
- private String referenceLocale;
- private List<String> displayedTranslations;
- private String[] translationsToDisplay;
-
- private SortInfo sortInfo;
- private Glossary glossary;
- private GlossaryManager manager;
-
- private GlossaryContentProvider contentProvider;
- private GlossaryLabelProvider labelProvider;
-
- /*** MATCHER ***/
- ExactMatcher matcher;
-
- /*** SORTER ***/
- GlossaryEntrySorter sorter;
-
- /*** ACTIONS ***/
- private Action doubleClickAction;
-
- public GlossaryWidget(IWorkbenchPartSite site,
- Composite parent, int style, GlossaryManager manager, String refLang, List<String> dls) {
- super(parent, style);
- this.site = site;
-
- if (manager != null) {
- this.manager = manager;
- this.glossary = manager.getGlossary();
-
- if (refLang != null)
- this.referenceLocale = refLang;
- else
- this.referenceLocale = glossary.info.getTranslations()[0];
-
- if (dls != null)
- this.translationsToDisplay = dls.toArray(new String[dls.size()]);
- else
- this.translationsToDisplay = glossary.info.getTranslations();
- }
-
- constructWidget();
-
- if (this.glossary!= null) {
- initTreeViewer();
- initMatchers();
- initSorters();
- }
-
- hookDragAndDrop();
- registerListeners();
- }
-
- protected void registerListeners() {
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyPressed (KeyEvent event) {
- if (event.character == SWT.DEL &&
- event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
-
- // Listen resource changes
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
- }
-
- protected void initSorters() {
- sorter = new GlossaryEntrySorter(treeViewer, sortInfo, glossary.getIndexOfLocale (referenceLocale), glossary.info.translations);
- treeViewer.setSorter(sorter);
- }
-
- public void enableFuzzyMatching(boolean enable) {
- String pattern = "";
- if (matcher != null) {
- pattern = matcher.getPattern();
-
- if (!fuzzyMatchingEnabled && enable) {
- if (matcher.getPattern().trim().length() > 1
- && matcher.getPattern().startsWith("*")
- && matcher.getPattern().endsWith("*"))
- pattern = pattern.substring(1).substring(0,
- pattern.length() - 2);
- matcher.setPattern(null);
- }
- }
- fuzzyMatchingEnabled = enable;
- initMatchers();
-
- matcher.setPattern(pattern);
- treeViewer.refresh();
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- protected void initMatchers() {
- treeViewer.resetFilters();
-
- String patternBefore = matcher != null ? matcher.getPattern() : "";
-
- if (fuzzyMatchingEnabled) {
- matcher = new FuzzyMatcher(treeViewer);
- ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
- } else
- matcher = new ExactMatcher(treeViewer);
-
- matcher.setPattern(patternBefore);
-
- if (this.selectiveViewEnabled)
- new SelectiveMatcher(treeViewer, site.getPage());
- }
-
- protected void initTreeViewer() {
- // init content provider
- contentProvider = new GlossaryContentProvider( this.glossary );
- treeViewer.setContentProvider(contentProvider);
-
- // init label provider
- labelProvider = new GlossaryLabelProvider(this.displayedTranslations.indexOf(referenceLocale), this.displayedTranslations, site.getPage());
- treeViewer.setLabelProvider(labelProvider);
-
- setTreeStructure(grouped);
- }
-
- public void setTreeStructure(boolean grouped) {
- this.grouped = grouped;
- ((GlossaryContentProvider)treeViewer.getContentProvider()).setGrouped(this.grouped);
- if (treeViewer.getInput() == null)
- treeViewer.setUseHashlookup(false);
- treeViewer.setInput(this.glossary);
- treeViewer.refresh();
- }
-
- protected void constructWidget() {
- basicLayout = new TreeColumnLayout();
- this.setLayout(basicLayout);
-
- treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
- | SWT.BORDER);
- Tree tree = treeViewer.getTree();
-
- if (glossary != null) {
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // create tree-columns
- constructTreeColumns(tree);
- } else {
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
- }
-
- makeActions();
- hookDoubleClickAction();
-
- // register messages table as selection provider
- site.setSelectionProvider(treeViewer);
- }
-
- /**
- * Gets the orientation suited for a given locale.
- * @param locale the locale
- * @return <code>SWT.RIGHT_TO_LEFT</code> or <code>SWT.LEFT_TO_RIGHT</code>
- */
- private int getOrientation(Locale locale){
- if(locale!=null){
- ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
- if(orientation==ComponentOrientation.RIGHT_TO_LEFT){
- return SWT.RIGHT_TO_LEFT;
- }
- }
- return SWT.LEFT_TO_RIGHT;
- }
-
- protected void constructTreeColumns(Tree tree) {
- tree.removeAll();
- if (this.displayedTranslations == null)
- this.displayedTranslations = new ArrayList <String>();
-
- this.displayedTranslations.clear();
-
- /** Reference term */
- String[] refDef = referenceLocale.split("_");
- Locale l = refDef.length < 3 ? (refDef.length < 2 ? new Locale (refDef[0]) : new Locale(refDef[0], refDef[1])) : new Locale (refDef[0], refDef[1], refDef[2]);
-
- this.displayedTranslations.add(referenceLocale);
- termColumn = new TreeColumn(tree, SWT.RIGHT_TO_LEFT/*getOrientation(l)*/);
-
- termColumn.setText(l.getDisplayName());
- TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn);
- termCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- if (element instanceof Term) {
- Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(referenceLocale);
-
- if (translation != null) {
- translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
- manager.setGlossary(gl);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- treeViewer.refresh();
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, 0);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
- termColumn.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(termColumn, new ColumnWeightData(
- TERM_COLUMN_WEIGHT));
-
-
- /** Translations */
- String[] allLocales = this.translationsToDisplay;
-
- int iCol = 1;
- for (String locale : allLocales) {
- final int ifCall = iCol;
- final String sfLocale = locale;
- if (locale.equalsIgnoreCase(this.referenceLocale))
- continue;
-
- // trac the rendered translation
- this.displayedTranslations.add(locale);
-
- String [] locDef = locale.split("_");
- l = locDef.length < 3 ? (locDef.length < 2 ? new Locale (locDef[0]) : new Locale(locDef[0], locDef[1])) : new Locale (locDef[0], locDef[1], locDef[2]);
-
- // Add editing support to this table column
- TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE);
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, descriptionColumn);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- if (element instanceof Term) {
- Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(sfLocale);
-
- if (translation != null) {
- translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
- manager.setGlossary(gl);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- treeViewer.refresh();
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, ifCall);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
-
- descriptionColumn.setText(l.getDisplayName());
- descriptionColumn.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(ifCall);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(ifCall);
- }
- });
- basicLayout.setColumnData(descriptionColumn, new ColumnWeightData(
- DESCRIPTION_COLUMN_WEIGHT));
- iCol ++;
- }
-
- }
-
- protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sorter.setSortInfo(sortInfo);
- setTreeStructure(idx == 0);
- treeViewer.refresh();
- }
-
- @Override
- public boolean setFocus() {
- return treeViewer.getControl().setFocus();
- }
-
- /*** DRAG AND DROP ***/
- protected void hookDragAndDrop() {
- GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager);
- GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager);
-
- // Initialize drag source for copy event
- DragSource dragSource = new DragSource(treeViewer.getControl(),
- DND.DROP_MOVE);
- dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() });
- dragSource.addDragListener(source);
-
- // Initialize drop target for copy event
- DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
- DND.DROP_MOVE);
- dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() });
- dropTarget.addDropListener(target);
- }
-
- /*** ACTIONS ***/
-
- private void makeActions() {
- doubleClickAction = new Action() {
-
- @Override
- public void run() {
- // implement the cell edit event
- }
-
- };
- }
-
- private void hookDoubleClickAction() {
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
- }
-
- /*** SELECTION LISTENER ***/
-
-
- private void refreshViewer() {
- treeViewer.refresh();
- }
-
- public StructuredViewer getViewer() {
- return this.treeViewer;
- }
-
- public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- if (matcher.getPattern().trim().length() > 0)
- grouped = false;
- else
- grouped = true;
- labelProvider.setSearchEnabled(!grouped);
- this.setTreeStructure(grouped && sorter != null && sorter.getSortInfo().getColIdx() == 0);
- treeViewer.refresh();
- }
-
- public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- setTreeStructure(sortInfo.getColIdx() == 0);
- treeViewer.refresh();
- }
- }
-
- public String getSearchString() {
- return matcher.getPattern();
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public void deleteSelectedItems() {
- List<String> ids = new ArrayList<String>();
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
- ISelection selection = site.getSelectionProvider().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof Term) {
- this.glossary.removeTerm ((Term)elem);
- this.manager.setGlossary(this.glossary);
- try {
- this.manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- this.refreshViewer();
- }
-
- public void addNewItem() {
- // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- Term parentTerm = null;
-
- ISelection selection = site.getSelectionProvider().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof Term) {
- parentTerm = ((Term) elem);
- break;
- }
- }
- }
-
- InputDialog dialog = new InputDialog (this.getShell(), "Neuer Begriff",
- "Please, define the new term:", "", null);
-
- if (dialog.open() == InputDialog.OK) {
- if (dialog.getValue() != null && dialog.getValue().trim().length() > 0) {
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
- // Construct a new term
- Term newTerm = new Term();
- Translation defaultTranslation = new Translation ();
- defaultTranslation.id = referenceLocale;
- defaultTranslation.value = dialog.getValue();
- newTerm.translations.add(defaultTranslation);
-
- this.glossary.addTerm (parentTerm, newTerm);
-
- this.manager.setGlossary(this.glossary);
- try {
- this.manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- this.refreshViewer();
- }
-
- public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public Control getControl() {
- return treeViewer.getControl();
- }
-
- public Glossary getGlossary () {
- return this.glossary;
- }
-
- public void addSelectionChangedListener(
- ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- }
-
- public String getReferenceLanguage() {
- return referenceLocale;
- }
-
- public void setReferenceLanguage (String lang) {
- this.referenceLocale = lang;
- }
-
- public void bindContentToSelection(boolean enable) {
- this.selectiveViewEnabled = enable;
- initMatchers();
- }
-
- public boolean isSelectiveViewEnabled() {
- return selectiveViewEnabled;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- }
-
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- initMatchers();
- this.refreshViewer();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets;
+
+import java.awt.ComponentOrientation;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.compat.MySWT;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDragSource;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDropTarget;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.TermTransfer;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.ExactMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FuzzyMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.SelectiveMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.AbstractGlossaryLabelProvider;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.GlossaryEntrySorter;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
+
+public class GlossaryWidget extends Composite implements
+ IResourceChangeListener {
+
+ private final int TERM_COLUMN_WEIGHT = 1;
+ private final int DESCRIPTION_COLUMN_WEIGHT = 1;
+
+ private boolean editable;
+
+ private IWorkbenchPartSite site;
+ private TreeColumnLayout basicLayout;
+ private TreeViewer treeViewer;
+ private TreeColumn termColumn;
+ private boolean grouped = true;
+ private boolean fuzzyMatchingEnabled = false;
+ private boolean selectiveViewEnabled = false;
+ private float matchingPrecision = .75f;
+ private String referenceLocale;
+ private List<String> displayedTranslations;
+ private String[] translationsToDisplay;
+
+ private SortInfo sortInfo;
+ private Glossary glossary;
+ private GlossaryManager manager;
+
+ private GlossaryContentProvider contentProvider;
+ private AbstractGlossaryLabelProvider labelProvider;
+
+ /*** MATCHER ***/
+ ExactMatcher matcher;
+
+ /*** SORTER ***/
+ GlossaryEntrySorter sorter;
+
+ /*** ACTIONS ***/
+ private Action doubleClickAction;
+
+ public GlossaryWidget(IWorkbenchPartSite site, Composite parent, int style,
+ GlossaryManager manager, String refLang, List<String> dls) {
+ super(parent, style);
+ this.site = site;
+
+ if (manager != null) {
+ this.manager = manager;
+ this.glossary = manager.getGlossary();
+
+ if (refLang != null)
+ this.referenceLocale = refLang;
+ else
+ this.referenceLocale = glossary.info.getTranslations()[0];
+
+ if (dls != null)
+ this.translationsToDisplay = dls
+ .toArray(new String[dls.size()]);
+ else
+ this.translationsToDisplay = glossary.info.getTranslations();
+ }
+
+ constructWidget();
+
+ if (this.glossary != null) {
+ initTreeViewer();
+ initMatchers();
+ initSorters();
+ }
+
+ hookDragAndDrop();
+ registerListeners();
+ }
+
+ protected void registerListeners() {
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
+
+ // Listen resource changes
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
+ }
+
+ protected void initSorters() {
+ sorter = new GlossaryEntrySorter(treeViewer, sortInfo,
+ glossary.getIndexOfLocale(referenceLocale),
+ glossary.info.translations);
+ treeViewer.setSorter(sorter);
+ }
+
+ public void enableFuzzyMatching(boolean enable) {
+ String pattern = "";
+ if (matcher != null) {
+ pattern = matcher.getPattern();
+
+ if (!fuzzyMatchingEnabled && enable) {
+ if (matcher.getPattern().trim().length() > 1
+ && matcher.getPattern().startsWith("*")
+ && matcher.getPattern().endsWith("*"))
+ pattern = pattern.substring(1).substring(0,
+ pattern.length() - 2);
+ matcher.setPattern(null);
+ }
+ }
+ fuzzyMatchingEnabled = enable;
+ initMatchers();
+
+ matcher.setPattern(pattern);
+ treeViewer.refresh();
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ protected void initMatchers() {
+ treeViewer.resetFilters();
+
+ String patternBefore = matcher != null ? matcher.getPattern() : "";
+
+ if (fuzzyMatchingEnabled) {
+ matcher = new FuzzyMatcher(treeViewer);
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
+ } else
+ matcher = new ExactMatcher(treeViewer);
+
+ matcher.setPattern(patternBefore);
+
+ if (this.selectiveViewEnabled)
+ new SelectiveMatcher(treeViewer, site.getPage());
+ }
+
+ protected void initTreeViewer() {
+ // init content provider
+ contentProvider = new GlossaryContentProvider(this.glossary);
+ treeViewer.setContentProvider(contentProvider);
+
+ // init label provider
+ try {
+ Class<?> clazz = Class.forName(AbstractGlossaryLabelProvider.INSTANCE_CLASS);
+ Constructor<?> constr = clazz.getConstructor(Integer.class, List.class, IWorkbenchPage.class);
+ labelProvider = (AbstractGlossaryLabelProvider) constr.newInstance(
+ this.displayedTranslations.indexOf(referenceLocale),
+ this.displayedTranslations, site.getPage());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ 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 MySWT.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, MySWT.RIGHT_TO_LEFT/* getOrientation(l) */);
+
+ termColumn.setText(l.getDisplayName());
+ TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn);
+ termCol.setEditingSupport(new EditingSupport(treeViewer) {
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ if (element instanceof Term) {
+ Term term = (Term) element;
+ Translation translation = (Translation) term
+ .getTranslation(referenceLocale);
+
+ if (translation != null) {
+ translation.value = (String) value;
+ Glossary gl = ((GlossaryContentProvider) treeViewer
+ .getContentProvider()).getGlossary();
+ manager.setGlossary(gl);
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ treeViewer.refresh();
+ }
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element, 0);
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer.getControl();
+ editor = new TextCellEditor(tree);
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+ termColumn.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(termColumn, new ColumnWeightData(
+ TERM_COLUMN_WEIGHT));
+
+ /** Translations */
+ String[] allLocales = this.translationsToDisplay;
+
+ int iCol = 1;
+ for (String locale : allLocales) {
+ final int ifCall = iCol;
+ final String sfLocale = locale;
+ if (locale.equalsIgnoreCase(this.referenceLocale))
+ continue;
+
+ // trac the rendered translation
+ this.displayedTranslations.add(locale);
+
+ String[] locDef = locale.split("_");
+ l = locDef.length < 3 ? (locDef.length < 2 ? new Locale(locDef[0])
+ : new Locale(locDef[0], locDef[1])) : new Locale(locDef[0],
+ locDef[1], locDef[2]);
+
+ // Add editing support to this table column
+ TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE);
+ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer,
+ descriptionColumn);
+ tCol.setEditingSupport(new EditingSupport(treeViewer) {
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ if (element instanceof Term) {
+ Term term = (Term) element;
+ Translation translation = (Translation) term
+ .getTranslation(sfLocale);
+
+ if (translation != null) {
+ translation.value = (String) value;
+ Glossary gl = ((GlossaryContentProvider) treeViewer
+ .getContentProvider()).getGlossary();
+ manager.setGlossary(gl);
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ treeViewer.refresh();
+ }
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element, ifCall);
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer.getControl();
+ editor = new TextCellEditor(tree);
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+
+ descriptionColumn.setText(l.getDisplayName());
+ descriptionColumn.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(ifCall);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(ifCall);
+ }
+ });
+ basicLayout.setColumnData(descriptionColumn, new ColumnWeightData(
+ DESCRIPTION_COLUMN_WEIGHT));
+ iCol++;
+ }
+
+ }
+
+ protected void updateSorter(int idx) {
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sorter.setSortInfo(sortInfo);
+ setTreeStructure(idx == 0);
+ treeViewer.refresh();
+ }
+
+ @Override
+ public boolean setFocus() {
+ return treeViewer.getControl().setFocus();
+ }
+
+ /*** DRAG AND DROP ***/
+ protected void hookDragAndDrop() {
+ GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager);
+ GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager);
+
+ // Initialize drag source for copy event
+ DragSource dragSource = new DragSource(treeViewer.getControl(),
+ DND.DROP_MOVE);
+ dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() });
+ dragSource.addDragListener(source);
+
+ // Initialize drop target for copy event
+ DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
+ DND.DROP_MOVE);
+ dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() });
+ dropTarget.addDropListener(target);
+ }
+
+ /*** ACTIONS ***/
+
+ private void makeActions() {
+ doubleClickAction = new Action() {
+
+ @Override
+ public void run() {
+ // implement the cell edit event
+ }
+
+ };
+ }
+
+ private void hookDoubleClickAction() {
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
+ }
+
+ /*** SELECTION LISTENER ***/
+
+ private void refreshViewer() {
+ treeViewer.refresh();
+ }
+
+ public StructuredViewer getViewer() {
+ return this.treeViewer;
+ }
+
+ public void setSearchString(String pattern) {
+ matcher.setPattern(pattern);
+ if (matcher.getPattern().trim().length() > 0)
+ grouped = false;
+ else
+ grouped = true;
+ labelProvider.setSearchEnabled(!grouped);
+ this.setTreeStructure(grouped && sorter != null
+ && sorter.getSortInfo().getColIdx() == 0);
+ treeViewer.refresh();
+ }
+
+ public SortInfo getSortInfo() {
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ setTreeStructure(sortInfo.getColIdx() == 0);
+ treeViewer.refresh();
+ }
+ }
+
+ public String getSearchString() {
+ return matcher.getPattern();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public void deleteSelectedItems() {
+ List<String> ids = new ArrayList<String>();
+ this.glossary = ((GlossaryContentProvider) treeViewer
+ .getContentProvider()).getGlossary();
+
+ ISelection selection = site.getSelectionProvider().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof Term) {
+ this.glossary.removeTerm((Term) elem);
+ this.manager.setGlossary(this.glossary);
+ try {
+ this.manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ this.refreshViewer();
+ }
+
+ public void addNewItem() {
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ Term parentTerm = null;
+
+ ISelection selection = site.getSelectionProvider().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof Term) {
+ parentTerm = ((Term) elem);
+ break;
+ }
+ }
+ }
+
+ InputDialog dialog = new InputDialog(this.getShell(), "Neuer Begriff",
+ "Please, define the new term:", "", null);
+
+ if (dialog.open() == InputDialog.OK) {
+ if (dialog.getValue() != null
+ && dialog.getValue().trim().length() > 0) {
+ this.glossary = ((GlossaryContentProvider) treeViewer
+ .getContentProvider()).getGlossary();
+
+ // Construct a new term
+ Term newTerm = new Term();
+ Translation defaultTranslation = new Translation();
+ defaultTranslation.id = referenceLocale;
+ defaultTranslation.value = dialog.getValue();
+ newTerm.translations.add(defaultTranslation);
+
+ this.glossary.addTerm(parentTerm, newTerm);
+
+ this.manager.setGlossary(this.glossary);
+ try {
+ this.manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ this.refreshViewer();
+ }
+
+ public void setMatchingPrecision(float value) {
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ public Control getControl() {
+ return treeViewer.getControl();
+ }
+
+ public Glossary getGlossary() {
+ return this.glossary;
+ }
+
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
+ treeViewer.addSelectionChangedListener(listener);
+ }
+
+ public String getReferenceLanguage() {
+ return referenceLocale;
+ }
+
+ public void setReferenceLanguage(String lang) {
+ this.referenceLocale = lang;
+ }
+
+ public void bindContentToSelection(boolean enable) {
+ this.selectiveViewEnabled = enable;
+ initMatchers();
+ }
+
+ public boolean isSelectiveViewEnabled() {
+ return selectiveViewEnabled;
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ }
+
+ @Override
+ public void resourceChanged(IResourceChangeEvent event) {
+ initMatchers();
+ this.refreshViewer();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
index 9456837b..5211bff2 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
@@ -1,57 +1,68 @@
-package org.eclipselabs.tapiji.translator.views.widgets.dnd;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-
-
-public class GlossaryDragSource implements DragSourceListener {
-
- private final TreeViewer source;
- private final GlossaryManager manager;
- private List<Term> selectionList;
-
- public GlossaryDragSource (TreeViewer sourceView, GlossaryManager manager) {
- source = sourceView;
- this.manager = manager;
- this.selectionList = new ArrayList<Term>();
- }
-
- @Override
- public void dragFinished(DragSourceEvent event) {
- GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source.getContentProvider());
- Glossary glossary = contentProvider.getGlossary();
- for (Term selectionObject : selectionList)
- glossary.removeTerm(selectionObject);
- manager.setGlossary(glossary);
- this.source.refresh();
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void dragSetData(DragSourceEvent event) {
- selectionList = new ArrayList<Term> ();
- for (Object selectionObject : ((IStructuredSelection)source.getSelection()).toList())
- selectionList.add((Term) selectionObject);
-
- event.data = selectionList.toArray(new Term[selectionList.size()]);
- }
-
- @Override
- public void dragStart(DragSourceEvent event) {
- event.doit = !source.getSelection().isEmpty();
- }
-
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+
+public class GlossaryDragSource implements DragSourceListener {
+
+ private final TreeViewer source;
+ private final GlossaryManager manager;
+ private List<Term> selectionList;
+
+ public GlossaryDragSource(TreeViewer sourceView, GlossaryManager manager) {
+ source = sourceView;
+ this.manager = manager;
+ this.selectionList = new ArrayList<Term>();
+ }
+
+ @Override
+ public void dragFinished(DragSourceEvent event) {
+ GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source
+ .getContentProvider());
+ Glossary glossary = contentProvider.getGlossary();
+ for (Term selectionObject : selectionList)
+ glossary.removeTerm(selectionObject);
+ manager.setGlossary(glossary);
+ this.source.refresh();
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent event) {
+ selectionList = new ArrayList<Term>();
+ for (Object selectionObject : ((IStructuredSelection) source
+ .getSelection()).toList())
+ selectionList.add((Term) selectionObject);
+
+ event.data = selectionList.toArray(new Term[selectionList.size()]);
+ }
+
+ @Override
+ public void dragStart(DragSourceEvent event) {
+ event.doit = !source.getSelection().isEmpty();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
index 7f96ddd7..46cb8805 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
@@ -1,71 +1,82 @@
-package org.eclipselabs.tapiji.translator.views.widgets.dnd;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-
-
-public class GlossaryDropTarget extends DropTargetAdapter {
- private final TreeViewer target;
- private final GlossaryManager manager;
-
- public GlossaryDropTarget (TreeViewer viewer, GlossaryManager manager) {
- super();
- this.target = viewer;
- this.manager = manager;
- }
-
- public void dragEnter (DropTargetEvent event) {
- if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) {
- if ((event.operations & DND.DROP_MOVE) != 0)
- event.detail = DND.DROP_MOVE;
- else
- event.detail = DND.DROP_NONE;
- }
- }
-
- public void drop (DropTargetEvent event) {
- if (TermTransfer.getInstance().isSupportedType (event.currentDataType)) {
- Term parentTerm = null;
-
- event.detail = DND.DROP_MOVE;
- event.feedback = DND.FEEDBACK_INSERT_AFTER;
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof Term) {
- parentTerm = ((Term) ((TreeItem) event.item).getData());
- }
-
- Term[] moveTerm = (Term[]) event.data;
- Glossary glossary = ((GlossaryContentProvider) target.getContentProvider()).getGlossary();
-
- /* Remove the move term from its initial position
- for (Term selectionObject : moveTerm)
- glossary.removeTerm(selectionObject);*/
-
- /* Insert the move term on its target position */
- if (parentTerm == null) {
- for (Term t : moveTerm)
- glossary.terms.add(t);
- } else {
- for (Term t : moveTerm)
- parentTerm.subTerms.add(t);
- }
-
- manager.setGlossary(glossary);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- target.refresh();
- } else
- event.detail = DND.DROP_NONE;
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
+
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+
+public class GlossaryDropTarget extends DropTargetAdapter {
+ private final TreeViewer target;
+ private final GlossaryManager manager;
+
+ public GlossaryDropTarget(TreeViewer viewer, GlossaryManager manager) {
+ super();
+ this.target = viewer;
+ this.manager = manager;
+ }
+
+ public void dragEnter(DropTargetEvent event) {
+ if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) {
+ if ((event.operations & DND.DROP_MOVE) != 0)
+ event.detail = DND.DROP_MOVE;
+ else
+ event.detail = DND.DROP_NONE;
+ }
+ }
+
+ public void drop(DropTargetEvent event) {
+ if (TermTransfer.getInstance().isSupportedType(event.currentDataType)) {
+ Term parentTerm = null;
+
+ event.detail = DND.DROP_MOVE;
+ event.feedback = DND.FEEDBACK_INSERT_AFTER;
+
+ if (event.item instanceof TreeItem
+ && ((TreeItem) event.item).getData() instanceof Term) {
+ parentTerm = ((Term) ((TreeItem) event.item).getData());
+ }
+
+ Term[] moveTerm = (Term[]) event.data;
+ Glossary glossary = ((GlossaryContentProvider) target
+ .getContentProvider()).getGlossary();
+
+ /*
+ * Remove the move term from its initial position for (Term
+ * selectionObject : moveTerm) glossary.removeTerm(selectionObject);
+ */
+
+ /* Insert the move term on its target position */
+ if (parentTerm == null) {
+ for (Term t : moveTerm)
+ glossary.terms.add(t);
+ } else {
+ for (Term t : moveTerm)
+ parentTerm.subTerms.add(t);
+ }
+
+ manager.setGlossary(glossary);
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ target.refresh();
+ } else
+ event.detail = DND.DROP_NONE;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
index aa723853..2dc7c984 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
@@ -1,106 +1,115 @@
-package org.eclipselabs.tapiji.translator.views.widgets.dnd;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipselabs.tapiji.translator.model.Term;
-
-
-public class TermTransfer extends ByteArrayTransfer {
-
- private static final String TERM = "term";
-
- private static final int TYPEID = registerType(TERM);
-
- private static TermTransfer transfer = new TermTransfer();
-
- public static TermTransfer getInstance() {
- return transfer;
- }
-
- public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
- DND.error(DND.ERROR_INVALID_DATA);
- }
- Term[] terms = (Term[]) object;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream oOut = new ObjectOutputStream(out);
- for (int i = 0, length = terms.length; i < length; i++) {
- oOut.writeObject(terms[i]);
- }
- byte[] buffer = out.toByteArray();
- oOut.close();
-
- super.javaToNative(buffer, transferData);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
-
- byte[] buffer;
- try {
- buffer = (byte[]) super.nativeToJava(transferData);
- } catch (Exception e) {
- e.printStackTrace();
- buffer = null;
- }
- if (buffer == null)
- return null;
-
- List<Term> terms = new ArrayList<Term>();
- try {
- ByteArrayInputStream in = new ByteArrayInputStream(buffer);
- ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
- Term newTerm = (Term) readIn.readObject();
- terms.add(newTerm);
- //}
- readIn.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- return null;
- }
- return terms.toArray(new Term[terms.size()]);
- }
-
- return null;
- }
-
- protected String[] getTypeNames() {
- return new String[] { TERM };
- }
-
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
-
- boolean checkType(Object object) {
- if (object == null || !(object instanceof Term[])
- || ((Term[]) object).length == 0) {
- return false;
- }
- Term[] myTypes = (Term[]) object;
- for (int i = 0; i < myTypes.length; i++) {
- if (myTypes[i] == null) {
- return false;
- }
- }
- return true;
- }
-
- protected boolean validate(Object object) {
- return checkType(object);
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.dnd.ByteArrayTransfer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.TransferData;
+import org.eclipselabs.tapiji.translator.model.Term;
+
+public class TermTransfer extends ByteArrayTransfer {
+
+ private static final String TERM = "term";
+
+ private static final int TYPEID = registerType(TERM);
+
+ private static TermTransfer transfer = new TermTransfer();
+
+ public static TermTransfer getInstance() {
+ return transfer;
+ }
+
+ public void javaToNative(Object object, TransferData transferData) {
+ if (!checkType(object) || !isSupportedType(transferData)) {
+ DND.error(DND.ERROR_INVALID_DATA);
+ }
+ Term[] terms = (Term[]) object;
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream oOut = new ObjectOutputStream(out);
+ for (int i = 0, length = terms.length; i < length; i++) {
+ oOut.writeObject(terms[i]);
+ }
+ byte[] buffer = out.toByteArray();
+ oOut.close();
+
+ super.javaToNative(buffer, transferData);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public Object nativeToJava(TransferData transferData) {
+ if (isSupportedType(transferData)) {
+
+ byte[] buffer;
+ try {
+ buffer = (byte[]) super.nativeToJava(transferData);
+ } catch (Exception e) {
+ e.printStackTrace();
+ buffer = null;
+ }
+ if (buffer == null)
+ return null;
+
+ List<Term> terms = new ArrayList<Term>();
+ try {
+ ByteArrayInputStream in = new ByteArrayInputStream(buffer);
+ ObjectInputStream readIn = new ObjectInputStream(in);
+ // while (readIn.available() > 0) {
+ Term newTerm = (Term) readIn.readObject();
+ terms.add(newTerm);
+ // }
+ readIn.close();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return null;
+ }
+ return terms.toArray(new Term[terms.size()]);
+ }
+
+ return null;
+ }
+
+ protected String[] getTypeNames() {
+ return new String[] { TERM };
+ }
+
+ protected int[] getTypeIds() {
+ return new int[] { TYPEID };
+ }
+
+ boolean checkType(Object object) {
+ if (object == null || !(object instanceof Term[])
+ || ((Term[]) object).length == 0) {
+ return false;
+ }
+ Term[] myTypes = (Term[]) object;
+ for (int i = 0; i < myTypes.length; i++) {
+ if (myTypes[i] == null) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ protected boolean validate(Object object) {
+ return checkType(object);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
index 197aff7a..d31d6bc0 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
@@ -1,68 +1,78 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-
-
-public class ExactMatcher extends ViewerFilter {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public String getPattern () {
- return pattern;
- }
-
- public void setPattern (String p) {
- boolean filtering = matcher != null;
- if (p != null && p.trim().length() > 0) {
- pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
- if (!filtering)
- viewer.addFilter(this);
- else
- viewer.refresh();
- } else {
- pattern = "";
- matcher = null;
- if (filtering) {
- viewer.removeFilter(this);
- }
- }
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- Term term = (Term) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = false;
-
- // Iterate translations
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
- String locale = translation.id;
- if (matcher.match(value)) {
- filterInfo.addFoundInTranslation(locale);
- filterInfo.addSimilarity(locale, 1d);
- int start = -1;
- while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- filterInfo.addFoundInTranslationRange(locale, start, pattern.length());
- }
- selected = true;
- }
- }
-
- term.setInfo(filterInfo);
- return selected;
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class ExactMatcher extends ViewerFilter {
+
+ protected final StructuredViewer viewer;
+ protected String pattern = "";
+ protected StringMatcher matcher;
+
+ public ExactMatcher(StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public String getPattern() {
+ return pattern;
+ }
+
+ public void setPattern(String p) {
+ boolean filtering = matcher != null;
+ if (p != null && p.trim().length() > 0) {
+ pattern = p;
+ matcher = new StringMatcher("*" + pattern + "*", true, false);
+ if (!filtering)
+ viewer.addFilter(this);
+ else
+ viewer.refresh();
+ } else {
+ pattern = "";
+ matcher = null;
+ if (filtering) {
+ viewer.removeFilter(this);
+ }
+ }
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ Term term = (Term) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = false;
+
+ // Iterate translations
+ for (Translation translation : term.getAllTranslations()) {
+ String value = translation.value;
+ String locale = translation.id;
+ if (matcher.match(value)) {
+ filterInfo.addFoundInTranslation(locale);
+ filterInfo.addSimilarity(locale, 1d);
+ int start = -1;
+ while ((start = value.toLowerCase().indexOf(
+ pattern.toLowerCase(), start + 1)) >= 0) {
+ filterInfo.addFoundInTranslationRange(locale, start,
+ pattern.length());
+ }
+ selected = true;
+ }
+ }
+
+ term.setInfo(filterInfo);
+ return selected;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
index ea3f05f6..61a718c3 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
@@ -1,57 +1,67 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.Region;
-
-public class FilterInfo {
-
- private List<String> foundInTranslation = new ArrayList<String> ();
- private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>();
- private Map<String, Double> localeSimilarity = new HashMap<String, Double>();
-
- public FilterInfo() {
-
- }
-
- public void addSimilarity (String l, Double similarity) {
- localeSimilarity.put (l, similarity);
- }
-
- public Double getSimilarityLevel (String l) {
- return localeSimilarity.get(l);
- }
-
- public void addFoundInTranslation (String loc) {
- foundInTranslation.add(loc);
- }
-
- public void removeFoundInTranslation (String loc) {
- foundInTranslation.remove(loc);
- }
-
- public void clearFoundInTranslation () {
- foundInTranslation.clear();
- }
-
- public boolean hasFoundInTranslation (String l) {
- return foundInTranslation.contains(l);
- }
-
- public List<Region> getFoundInTranslationRanges (String locale) {
- List<Region> reg = occurrences.get(locale);
- return (reg == null ? new ArrayList<Region>() : reg);
- }
-
- public void addFoundInTranslationRange (String locale, int start, int length) {
- List<Region> regions = occurrences.get(locale);
- if (regions == null)
- regions = new ArrayList<Region>();
- regions.add(new Region(start, length));
- occurrences.put(locale, regions);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jface.text.Region;
+
+public class FilterInfo {
+
+ private List<String> foundInTranslation = new ArrayList<String>();
+ private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>();
+ private Map<String, Double> localeSimilarity = new HashMap<String, Double>();
+
+ public FilterInfo() {
+
+ }
+
+ public void addSimilarity(String l, Double similarity) {
+ localeSimilarity.put(l, similarity);
+ }
+
+ public Double getSimilarityLevel(String l) {
+ return localeSimilarity.get(l);
+ }
+
+ public void addFoundInTranslation(String loc) {
+ foundInTranslation.add(loc);
+ }
+
+ public void removeFoundInTranslation(String loc) {
+ foundInTranslation.remove(loc);
+ }
+
+ public void clearFoundInTranslation() {
+ foundInTranslation.clear();
+ }
+
+ public boolean hasFoundInTranslation(String l) {
+ return foundInTranslation.contains(l);
+ }
+
+ public List<Region> getFoundInTranslationRanges(String locale) {
+ List<Region> reg = occurrences.get(locale);
+ return (reg == null ? new ArrayList<Region>() : reg);
+ }
+
+ public void addFoundInTranslationRange(String locale, int start, int length) {
+ List<Region> regions = occurrences.get(locale);
+ if (regions == null)
+ regions = new ArrayList<Region>();
+ regions.add(new Region(start, length));
+ occurrences.put(locale, regions);
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
index bc09e5bb..9344aa9d 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
@@ -1,55 +1,66 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import org.eclipse.babel.editor.api.AnalyzerFactory;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-
-public class FuzzyMatcher extends ExactMatcher {
-
- protected ILevenshteinDistanceAnalyzer lvda;
- protected float minimumSimilarity = 0.75f;
-
- public FuzzyMatcher(StructuredViewer viewer) {
- super(viewer);
- lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
- }
-
- public double getMinimumSimilarity () {
- return minimumSimilarity;
- }
-
- public void setMinimumSimilarity (float similarity) {
- this.minimumSimilarity = similarity;
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- boolean exactMatch = super.select(viewer, parentElement, element);
- boolean match = exactMatch;
-
- Term term = (Term) element;
-
- FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
- String locale = translation.id;
- if (filterInfo.hasFoundInTranslation(locale))
- continue;
- double dist = lvda.analyse(value, getPattern());
- if (dist >= minimumSimilarity) {
- filterInfo.addFoundInTranslation(locale);
- filterInfo.addSimilarity(locale, dist);
- match = true;
- filterInfo.addFoundInTranslationRange(locale, 0, value.length());
- }
- }
-
- term.setInfo(filterInfo);
- return match;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import org.eclipse.babel.editor.api.AnalyzerFactory;
+import org.eclipse.babel.editor.api.ILevenshteinDistanceAnalyzer;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class FuzzyMatcher extends ExactMatcher {
+
+ protected ILevenshteinDistanceAnalyzer lvda;
+ protected float minimumSimilarity = 0.75f;
+
+ public FuzzyMatcher(StructuredViewer viewer) {
+ super(viewer);
+ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
+ }
+
+ public double getMinimumSimilarity() {
+ return minimumSimilarity;
+ }
+
+ public void setMinimumSimilarity(float similarity) {
+ this.minimumSimilarity = similarity;
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ boolean exactMatch = super.select(viewer, parentElement, element);
+ boolean match = exactMatch;
+
+ Term term = (Term) element;
+
+ FilterInfo filterInfo = (FilterInfo) term.getInfo();
+
+ for (Translation translation : term.getAllTranslations()) {
+ String value = translation.value;
+ String locale = translation.id;
+ if (filterInfo.hasFoundInTranslation(locale))
+ continue;
+ double dist = lvda.analyse(value, getPattern());
+ if (dist >= minimumSimilarity) {
+ filterInfo.addFoundInTranslation(locale);
+ filterInfo.addSimilarity(locale, dist);
+ match = true;
+ filterInfo
+ .addFoundInTranslationRange(locale, 0, value.length());
+ }
+ }
+
+ term.setInfo(filterInfo);
+ return match;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
index 7f2ae36b..58b6224c 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
@@ -1,95 +1,109 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import org.eclipse.babel.editor.api.EditorUtil;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-
-public class SelectiveMatcher extends ViewerFilter
- implements ISelectionListener, ISelectionChangedListener {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
- protected IKeyTreeNode selectedItem;
- protected IWorkbenchPage page;
-
- public SelectiveMatcher (StructuredViewer viewer, IWorkbenchPage page) {
- this.viewer = viewer;
- if (page.getActiveEditor() != null) {
- this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
- }
-
- this.page = page;
- page.getWorkbenchWindow().getSelectionService().addSelectionListener(this);
-
- viewer.addFilter(this);
- viewer.refresh();
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (selectedItem == null)
- return false;
-
- Term term = (Term) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = false;
-
- // Iterate translations
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
-
- if (value.trim().length() == 0)
- continue;
-
- String locale = translation.id;
-
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
- String ev = entry.getValue();
- String[] subValues = ev.split("[\\s\\p{Punct}]+");
- for (String v : subValues) {
- if (v.trim().equalsIgnoreCase(value.trim()))
- return true;
- }
- }
- }
-
- return false;
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- try {
- if (selection.isEmpty())
- return;
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- IStructuredSelection sel = (IStructuredSelection) selection;
- selectedItem = (IKeyTreeNode) sel.iterator().next();
- viewer.refresh();
- } catch (Exception e) { }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- event.getSelection();
- }
-
- public void dispose () {
- page.getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.editor.api.EditorUtil;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class SelectiveMatcher extends ViewerFilter implements
+ ISelectionListener, ISelectionChangedListener {
+
+ protected final StructuredViewer viewer;
+ protected String pattern = "";
+ protected StringMatcher matcher;
+ protected IKeyTreeNode selectedItem;
+ protected IWorkbenchPage page;
+
+ public SelectiveMatcher(StructuredViewer viewer, IWorkbenchPage page) {
+ this.viewer = viewer;
+ if (page.getActiveEditor() != null) {
+ this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
+ }
+
+ this.page = page;
+ page.getWorkbenchWindow().getSelectionService()
+ .addSelectionListener(this);
+
+ viewer.addFilter(this);
+ viewer.refresh();
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (selectedItem == null)
+ return false;
+
+ Term term = (Term) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = false;
+
+ // Iterate translations
+ for (Translation translation : term.getAllTranslations()) {
+ String value = translation.value;
+
+ if (value.trim().length() == 0)
+ continue;
+
+ String locale = translation.id;
+
+ for (IMessage entry : selectedItem.getMessagesBundleGroup()
+ .getMessages(selectedItem.getMessageKey())) {
+ String ev = entry.getValue();
+ String[] subValues = ev.split("[\\s\\p{Punct}]+");
+ for (String v : subValues) {
+ if (v.trim().equalsIgnoreCase(value.trim()))
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+ try {
+ if (selection.isEmpty())
+ return;
+
+ if (!(selection instanceof IStructuredSelection))
+ return;
+
+ IStructuredSelection sel = (IStructuredSelection) selection;
+ selectedItem = (IKeyTreeNode) sel.iterator().next();
+ viewer.refresh();
+ } catch (Exception e) {
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ event.getSelection();
+ }
+
+ public void dispose() {
+ page.getWorkbenchWindow().getSelectionService()
+ .removeSelectionListener(this);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
index 337d2c9b..39865904 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
@@ -1,441 +1,496 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import java.util.Vector;
-
-/**
- * A string pattern matcher, suppporting "*" and "?" wildcards.
- */
-public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
- throw new IllegalArgumentException();
- }
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
- if (end < 0 || start >= end) {
- return null;
- }
- if (fLength == 0) {
- return new Position(start, start);
- }
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
- return null;
- }
- return new Position(x, x + fLength);
- }
-
- int segCount = fSegments.length;
- if (segCount == 0) {
- return new Position(start, end);
- }
-
- int curPos = start;
- int matchStart = -1;
- int i;
- for (i = 0; i < segCount && curPos < end; ++i) {
- String current = fSegments[i];
- int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0) {
- return null;
- }
- if (i == 0) {
- matchStart = nextMatch;
- }
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
- return null;
- }
- return new Position(matchStart, curPos);
- }
-
- /**
- * match the given <code>text</code> with the pattern
- * @return true if matched otherwise false
- * @param text a String object
- */
- public boolean match(String text) {
- if(text == null) {
- return false;
- }
- return match(text, 0, text.length());
- }
-
- /**
- * Given the starting (inclusive) and the ending (exclusive) positions in the
- * <code>text</code>, determine if the given substring matches with aPattern
- * @return true if the specified portion of the text matches the pattern
- * @param text a String object that contains the substring to match
- * @param start marks the starting position (inclusive) of the substring
- * @param end marks the ending index (exclusive) of the substring
- */
- public boolean match(String text, int start, int end) {
- if (null == text) {
- throw new IllegalArgumentException();
- }
-
- if (start > end) {
- return false;
- }
-
- if (fIgnoreWildCards) {
- return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
- }
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
- return true;
- }
- if (start == end) {
- return fLength == 0;
- }
- if (fLength == 0) {
- return start == end;
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
-
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
- return false;
- }
- int i = 0;
- String current = fSegments[i];
- int segLength = current.length();
-
- /* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos = tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar)
- && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current = fSegments[i];
- int currentMatch;
- int k = current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch = textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- } else {
- currentMatch = regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- }
- tCurPos = currentMatch + current.length();
- i++;
- }
-
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen = current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount;
- }
-
- /**
- * This method parses the given pattern into segments seperated by wildcard '*' characters.
- * Since wildcards are not being used in this case, the pattern consists of a single segment.
- */
- private void parseNoWildCards() {
- fSegments = new String[1];
- fSegments[0] = fPattern;
- fBound = fLength;
- }
-
- /**
- * Parses the given pattern into segments seperated by wildcard '*' characters.
- * @param p, a String object that is a simple regular expression with '*' and/or '?'
- */
- private void parseWildCards() {
- if (fPattern.startsWith("*")) { //$NON-NLS-1$
- fHasLeadingStar = true;
- }
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * @param text a simple regular expression that may only contain '?'(s)
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a simple regular expression that may contains '?'
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int regExpPosIn(String text, int start, int end, String p) {
- int plen = p.length();
-
- int max = end - plen;
- for (int i = start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- *
- * @return boolean
- * @param text a String to match
- * @param start int that indicates the starting index of match, inclusive
- * @param end</code> int that indicates the ending index of match, exclusive
- * @param p String, String, a simple regular expression that may contain '?'
- * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
- */
- protected boolean regExpRegionMatches(String text, int tStart, String p,
- int pStart, int plen) {
- while (plen-- > 0) {
- char tchar = text.charAt(tStart++);
- char pchar = p.charAt(pStart++);
-
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar) {
- continue;
- }
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character
- .toUpperCase(pchar)) {
- continue;
- }
- // comparing after converting to upper case doesn't handle all cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character
- .toLowerCase(pchar)) {
- continue;
- }
- }
- return false;
- }
- return true;
- }
-
- /**
- * @param text the string to match
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a pattern string that has no wildcard
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int textPosIn(String text, int start, int end, String p) {
-
- int plen = p.length();
- int max = end - plen;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(p, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
- return i;
- }
- }
-
- return -1;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import java.util.Vector;
+
+/**
+ * A string pattern matcher, suppporting "*" and "?" wildcards.
+ */
+public class StringMatcher {
+ protected String fPattern;
+
+ protected int fLength; // pattern length
+
+ protected boolean fIgnoreWildCards;
+
+ protected boolean fIgnoreCase;
+
+ protected boolean fHasLeadingStar;
+
+ protected boolean fHasTrailingStar;
+
+ protected String fSegments[]; // the given pattern is split into * separated
+ // segments
+
+ /* boundary value beyond which we don't need to search in the text */
+ protected int fBound = 0;
+
+ protected static final char fSingleWildCard = '\u0000';
+
+ public static class Position {
+ int start; // inclusive
+
+ int end; // exclusive
+
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getEnd() {
+ return end;
+ }
+ }
+
+ /**
+ * StringMatcher constructor takes in a String object that is a simple
+ * pattern which may contain '*' for 0 and many characters and '?' for
+ * exactly one character.
+ *
+ * Literal '*' and '?' characters must be escaped in the pattern e.g.,
+ * "\*" means literal "*", etc.
+ *
+ * Escaping any other character (including the escape character itself),
+ * just results in that character in the pattern. e.g., "\a" means "a" and
+ * "\\" means "\"
+ *
+ * If invoking the StringMatcher with string literals in Java, don't forget
+ * escape characters are represented by "\\".
+ *
+ * @param pattern
+ * the pattern to match text against
+ * @param ignoreCase
+ * if true, case is ignored
+ * @param ignoreWildCards
+ * if true, wild cards and their escape sequences are ignored
+ * (everything is taken literally).
+ */
+ public StringMatcher(String pattern, boolean ignoreCase,
+ boolean ignoreWildCards) {
+ if (pattern == null) {
+ throw new IllegalArgumentException();
+ }
+ fIgnoreCase = ignoreCase;
+ fIgnoreWildCards = ignoreWildCards;
+ fPattern = pattern;
+ fLength = pattern.length();
+
+ if (fIgnoreWildCards) {
+ parseNoWildCards();
+ } else {
+ parseWildCards();
+ }
+ }
+
+ /**
+ * Find the first occurrence of the pattern between <code>start</code
+ * )(inclusive) and <code>end</code>(exclusive).
+ *
+ * @param text
+ * the String object to search in
+ * @param start
+ * the starting index of the search range, inclusive
+ * @param end
+ * the ending index of the search range, exclusive
+ * @return an <code>StringMatcher.Position</code> object that keeps the
+ * starting (inclusive) and ending positions (exclusive) of the
+ * first occurrence of the pattern in the specified range of the
+ * text; return null if not found or subtext is empty (start==end).
+ * A pair of zeros is returned if pattern is empty string Note that
+ * for pattern like "*abc*" with leading and trailing stars,
+ * position of "abc" is returned. For a pattern like"*??*" in text
+ * "abcdf", (1,3) is returned
+ */
+ public StringMatcher.Position find(String text, int start, int end) {
+ if (text == null) {
+ throw new IllegalArgumentException();
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+ if (end < 0 || start >= end) {
+ return null;
+ }
+ if (fLength == 0) {
+ return new Position(start, start);
+ }
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
+ return null;
+ }
+ return new Position(x, x + fLength);
+ }
+
+ int segCount = fSegments.length;
+ if (segCount == 0) {
+ return new Position(start, end);
+ }
+
+ int curPos = start;
+ int matchStart = -1;
+ int i;
+ for (i = 0; i < segCount && curPos < end; ++i) {
+ String current = fSegments[i];
+ int nextMatch = regExpPosIn(text, curPos, end, current);
+ if (nextMatch < 0) {
+ return null;
+ }
+ if (i == 0) {
+ matchStart = nextMatch;
+ }
+ curPos = nextMatch + current.length();
+ }
+ if (i < segCount) {
+ return null;
+ }
+ return new Position(matchStart, curPos);
+ }
+
+ /**
+ * match the given <code>text</code> with the pattern
+ *
+ * @return true if matched otherwise false
+ * @param text
+ * a String object
+ */
+ public boolean match(String text) {
+ if (text == null) {
+ return false;
+ }
+ return match(text, 0, text.length());
+ }
+
+ /**
+ * Given the starting (inclusive) and the ending (exclusive) positions in
+ * the <code>text</code>, determine if the given substring matches with
+ * aPattern
+ *
+ * @return true if the specified portion of the text matches the pattern
+ * @param text
+ * a String object that contains the substring to match
+ * @param start
+ * marks the starting position (inclusive) of the substring
+ * @param end
+ * marks the ending index (exclusive) of the substring
+ */
+ public boolean match(String text, int start, int end) {
+ if (null == text) {
+ throw new IllegalArgumentException();
+ }
+
+ if (start > end) {
+ return false;
+ }
+
+ if (fIgnoreWildCards) {
+ return (end - start == fLength)
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
+ }
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ return true;
+ }
+ if (start == end) {
+ return fLength == 0;
+ }
+ if (fLength == 0) {
+ return start == end;
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+
+ int tCurPos = start;
+ int bound = end - fBound;
+ if (bound < 0) {
+ return false;
+ }
+ int i = 0;
+ String current = fSegments[i];
+ int segLength = current.length();
+
+ /* process first segment */
+ if (!fHasLeadingStar) {
+ if (!regExpRegionMatches(text, start, current, 0, segLength)) {
+ return false;
+ } else {
+ ++i;
+ tCurPos = tCurPos + segLength;
+ }
+ }
+ if ((fSegments.length == 1) && (!fHasLeadingStar)
+ && (!fHasTrailingStar)) {
+ // only one segment to match, no wildcards specified
+ return tCurPos == end;
+ }
+ /* process middle segments */
+ while (i < segCount) {
+ current = fSegments[i];
+ int currentMatch;
+ int k = current.indexOf(fSingleWildCard);
+ if (k < 0) {
+ currentMatch = textPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ } else {
+ currentMatch = regExpPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
+
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
+ }
+
+ /**
+ * This method parses the given pattern into segments seperated by wildcard
+ * '*' characters. Since wildcards are not being used in this case, the
+ * pattern consists of a single segment.
+ */
+ private void parseNoWildCards() {
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
+ }
+
+ /**
+ * Parses the given pattern into segments seperated by wildcard '*'
+ * characters.
+ *
+ * @param p
+ * , a String object that is a simple regular expression with '*'
+ * and/or '?'
+ */
+ private void parseWildCards() {
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
+ fHasLeadingStar = true;
+ }
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
+
+ Vector temp = new Vector();
+
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
+
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
+
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
+ }
+
+ /**
+ * @param text
+ * a string which contains no wildcard
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int posIn(String text, int start, int end) {// no wild card in
+ // pattern
+ int max = end - fLength;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ /**
+ * @param text
+ * a simple regular expression that may only contain '?'(s)
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @param p
+ * a simple regular expression that may contains '?'
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int regExpPosIn(String text, int start, int end, String p) {
+ int plen = p.length();
+
+ int max = end - plen;
+ for (int i = start; i <= max; ++i) {
+ if (regExpRegionMatches(text, i, p, 0, plen)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ *
+ * @return boolean
+ * @param text
+ * a String to match
+ * @param start
+ * int that indicates the starting index of match, inclusive
+ * @param end
+ * </code> int that indicates the ending index of match,
+ * exclusive
+ * @param p
+ * String, String, a simple regular expression that may contain
+ * '?'
+ * @param ignoreCase
+ * boolean indicating wether code>p</code> is case sensitive
+ */
+ protected boolean regExpRegionMatches(String text, int tStart, String p,
+ int pStart, int plen) {
+ while (plen-- > 0) {
+ char tchar = text.charAt(tStart++);
+ char pchar = p.charAt(pStart++);
+
+ /* process wild cards */
+ if (!fIgnoreWildCards) {
+ /* skip single wild cards */
+ if (pchar == fSingleWildCard) {
+ continue;
+ }
+ }
+ if (pchar == tchar) {
+ continue;
+ }
+ if (fIgnoreCase) {
+ if (Character.toUpperCase(tchar) == Character
+ .toUpperCase(pchar)) {
+ continue;
+ }
+ // comparing after converting to upper case doesn't handle all
+ // cases;
+ // also compare after converting to lower case
+ if (Character.toLowerCase(tchar) == Character
+ .toLowerCase(pchar)) {
+ continue;
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @param text
+ * the string to match
+ * @param start
+ * the starting index in the text for search, inclusive
+ * @param end
+ * the stopping point of search, exclusive
+ * @param p
+ * a pattern string that has no wildcard
+ * @return the starting index in the text of the pattern , or -1 if not
+ * found
+ */
+ protected int textPosIn(String text, int start, int end, String p) {
+
+ int plen = p.length();
+ int max = end - plen;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(p, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
index 9280bd2d..d7781fed 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
@@ -1,212 +1,221 @@
-package org.eclipselabs.tapiji.translator.views.widgets.model;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-
-
-public class GlossaryViewState {
-
- private static final String TAG_GLOSSARY_FILE = "glossary_file";
- private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
- private static final String TAG_SELECTIVE_VIEW = "selective_content";
- private static final String TAG_DISPLAYED_LOCALES = "displayed_locales";
- private static final String TAG_LOCALE = "locale";
- private static final String TAG_REFERENCE_LANG = "reference_language";
- private static final String TAG_MATCHING_PRECISION= "matching_precision";
- private static final String TAG_ENABLED = "enabled";
- private static final String TAG_VALUE = "value";
- private static final String TAG_SEARCH_STRING = "search_string";
- private static final String TAG_EDITABLE = "editable";
-
- private SortInfo sortings;
- private boolean fuzzyMatchingEnabled;
- private boolean selectiveViewEnabled;
- private float matchingPrecision = .75f;
- private String searchString;
- private boolean editable;
- private String glossaryFile;
- private String referenceLanguage;
- private List<String> displayLanguages;
-
- public void saveState (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (sortings != null) {
- sortings.saveState(memento);
- }
-
- IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
- memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
-
- IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW);
- memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled);
-
- IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
- memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
-
- IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
- memSStr.putString(TAG_VALUE, searchString);
-
- IMemento memEditable = memento.createChild(TAG_EDITABLE);
- memEditable.putBoolean(TAG_ENABLED, editable);
-
- IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG);
- memRefLang.putString(TAG_VALUE, referenceLanguage);
-
- IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE);
- memGlossaryFile.putString(TAG_VALUE, glossaryFile);
-
- IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES);
- if (displayLanguages != null) {
- for (String lang : displayLanguages) {
- IMemento memLoc = memDispLoc.createChild(TAG_LOCALE);
- memLoc.putString(TAG_VALUE, lang);
- }
- }
- } catch (Exception e) {
-
- }
- }
-
- public void init (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (sortings == null)
- sortings = new SortInfo();
- sortings.init(memento);
-
- IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
- if (mFuzzyMatching != null)
- fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
-
- IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW);
- if (mSelectiveView != null)
- selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED);
-
- IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
- if (mMP != null)
- matchingPrecision = mMP.getFloat(TAG_VALUE);
-
- IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
- if (mSStr != null)
- searchString = mSStr.getString(TAG_VALUE);
-
- IMemento mEditable = memento.getChild(TAG_EDITABLE);
- if (mEditable != null)
- editable = mEditable.getBoolean(TAG_ENABLED);
-
- IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG);
- if (mRefLang != null)
- referenceLanguage = mRefLang.getString(TAG_VALUE);
-
- IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE);
- if (mGlossaryFile != null)
- glossaryFile = mGlossaryFile.getString(TAG_VALUE);
-
- IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES);
- if (memDispLoc != null) {
- displayLanguages = new ArrayList<String>();
- for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) {
- displayLanguages.add(locale.getString(TAG_VALUE));
- }
- }
- } catch (Exception e) {
-
- }
- }
-
- public GlossaryViewState(List<Locale> visibleLocales,
- SortInfo sortings, boolean fuzzyMatchingEnabled,
- String selectedBundleId) {
- super();
- this.sortings = sortings;
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public SortInfo getSortings() {
- return sortings;
- }
-
- public void setSortings(SortInfo sortings) {
- this.sortings = sortings;
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public void setSearchString(String searchString) {
- this.searchString = searchString;
- }
-
- public String getSearchString() {
- return searchString;
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public void setMatchingPrecision (float value) {
- this.matchingPrecision = value;
- }
-
- public String getReferenceLanguage() {
- return this.referenceLanguage;
- }
-
- public void setReferenceLanguage (String refLang) {
- this.referenceLanguage = refLang;
- }
-
- public List<String> getDisplayLanguages() {
- return displayLanguages;
- }
-
- public void setDisplayLanguages(List<String> displayLanguages) {
- this.displayLanguages = displayLanguages;
- }
-
- public void setDisplayLangArr (String[] displayLanguages) {
- this.displayLanguages = new ArrayList<String>();
- for (String dl : displayLanguages) {
- this.displayLanguages.add(dl);
- }
- }
-
- public void setGlossaryFile(String absolutePath) {
- this.glossaryFile = absolutePath;
- }
-
- public String getGlossaryFile() {
- return glossaryFile;
- }
-
- public void setSelectiveViewEnabled(boolean selectiveViewEnabled) {
- this.selectiveViewEnabled = selectiveViewEnabled;
- }
-
- public boolean isSelectiveViewEnabled() {
- return selectiveViewEnabled;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.model;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
+
+public class GlossaryViewState {
+
+ private static final String TAG_GLOSSARY_FILE = "glossary_file";
+ private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
+ private static final String TAG_SELECTIVE_VIEW = "selective_content";
+ private static final String TAG_DISPLAYED_LOCALES = "displayed_locales";
+ private static final String TAG_LOCALE = "locale";
+ private static final String TAG_REFERENCE_LANG = "reference_language";
+ private static final String TAG_MATCHING_PRECISION = "matching_precision";
+ private static final String TAG_ENABLED = "enabled";
+ private static final String TAG_VALUE = "value";
+ private static final String TAG_SEARCH_STRING = "search_string";
+ private static final String TAG_EDITABLE = "editable";
+
+ private SortInfo sortings;
+ private boolean fuzzyMatchingEnabled;
+ private boolean selectiveViewEnabled;
+ private float matchingPrecision = .75f;
+ private String searchString;
+ private boolean editable;
+ private String glossaryFile;
+ private String referenceLanguage;
+ private List<String> displayLanguages;
+
+ public void saveState(IMemento memento) {
+ try {
+ if (memento == null)
+ return;
+
+ if (sortings != null) {
+ sortings.saveState(memento);
+ }
+
+ IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
+ memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
+
+ IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW);
+ memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled);
+
+ IMemento memMatchingPrec = memento
+ .createChild(TAG_MATCHING_PRECISION);
+ memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
+
+ IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
+ memSStr.putString(TAG_VALUE, searchString);
+
+ IMemento memEditable = memento.createChild(TAG_EDITABLE);
+ memEditable.putBoolean(TAG_ENABLED, editable);
+
+ IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG);
+ memRefLang.putString(TAG_VALUE, referenceLanguage);
+
+ IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE);
+ memGlossaryFile.putString(TAG_VALUE, glossaryFile);
+
+ IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES);
+ if (displayLanguages != null) {
+ for (String lang : displayLanguages) {
+ IMemento memLoc = memDispLoc.createChild(TAG_LOCALE);
+ memLoc.putString(TAG_VALUE, lang);
+ }
+ }
+ } catch (Exception e) {
+
+ }
+ }
+
+ public void init(IMemento memento) {
+ try {
+ if (memento == null)
+ return;
+
+ if (sortings == null)
+ sortings = new SortInfo();
+ sortings.init(memento);
+
+ IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
+ if (mFuzzyMatching != null)
+ fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
+
+ IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW);
+ if (mSelectiveView != null)
+ selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED);
+
+ IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
+ if (mMP != null)
+ matchingPrecision = mMP.getFloat(TAG_VALUE);
+
+ IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
+ if (mSStr != null)
+ searchString = mSStr.getString(TAG_VALUE);
+
+ IMemento mEditable = memento.getChild(TAG_EDITABLE);
+ if (mEditable != null)
+ editable = mEditable.getBoolean(TAG_ENABLED);
+
+ IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG);
+ if (mRefLang != null)
+ referenceLanguage = mRefLang.getString(TAG_VALUE);
+
+ IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE);
+ if (mGlossaryFile != null)
+ glossaryFile = mGlossaryFile.getString(TAG_VALUE);
+
+ IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES);
+ if (memDispLoc != null) {
+ displayLanguages = new ArrayList<String>();
+ for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) {
+ displayLanguages.add(locale.getString(TAG_VALUE));
+ }
+ }
+ } catch (Exception e) {
+
+ }
+ }
+
+ public GlossaryViewState(List<Locale> visibleLocales, SortInfo sortings,
+ boolean fuzzyMatchingEnabled, String selectedBundleId) {
+ super();
+ this.sortings = sortings;
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ }
+
+ public SortInfo getSortings() {
+ return sortings;
+ }
+
+ public void setSortings(SortInfo sortings) {
+ this.sortings = sortings;
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ }
+
+ public void setSearchString(String searchString) {
+ this.searchString = searchString;
+ }
+
+ public String getSearchString() {
+ return searchString;
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ public void setMatchingPrecision(float value) {
+ this.matchingPrecision = value;
+ }
+
+ public String getReferenceLanguage() {
+ return this.referenceLanguage;
+ }
+
+ public void setReferenceLanguage(String refLang) {
+ this.referenceLanguage = refLang;
+ }
+
+ public List<String> getDisplayLanguages() {
+ return displayLanguages;
+ }
+
+ public void setDisplayLanguages(List<String> displayLanguages) {
+ this.displayLanguages = displayLanguages;
+ }
+
+ public void setDisplayLangArr(String[] displayLanguages) {
+ this.displayLanguages = new ArrayList<String>();
+ for (String dl : displayLanguages) {
+ this.displayLanguages.add(dl);
+ }
+ }
+
+ public void setGlossaryFile(String absolutePath) {
+ this.glossaryFile = absolutePath;
+ }
+
+ public String getGlossaryFile() {
+ return glossaryFile;
+ }
+
+ public void setSelectiveViewEnabled(boolean selectiveViewEnabled) {
+ this.selectiveViewEnabled = selectiveViewEnabled;
+ }
+
+ public boolean isSelectiveViewEnabled() {
+ return selectiveViewEnabled;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/AbstractGlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/AbstractGlossaryLabelProvider.java
new file mode 100644
index 00000000..253d7081
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/AbstractGlossaryLabelProvider.java
@@ -0,0 +1,153 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
+
+import java.util.List;
+
+import org.eclipse.babel.core.message.IMessage;
+import org.eclipse.babel.core.message.tree.IKeyTreeNode;
+import org.eclipse.babel.editor.api.EditorUtil;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.utils.FontUtils;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
+
+public abstract class AbstractGlossaryLabelProvider extends StyledCellLabelProvider implements
+ ISelectionListener, ISelectionChangedListener {
+
+ private static final long serialVersionUID = -1833407818565507359L;
+ public static final String INSTANCE_CLASS = "org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider";
+
+ protected boolean searchEnabled = false;
+ protected int referenceColumn = 0;
+ protected List<String> translations;
+ protected IKeyTreeNode selectedItem;
+
+ /*** COLORS ***/
+ protected Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+ protected Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
+ protected Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
+ protected Color info_crossref = FontUtils
+ .getSystemColor(SWT.COLOR_INFO_BACKGROUND);
+ protected Color info_crossref_foreground = FontUtils
+ .getSystemColor(SWT.COLOR_INFO_FOREGROUND);
+ protected Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE);
+
+ /*** FONTS ***/
+ protected Font bold = FontUtils.createFont(SWT.BOLD);
+ protected Font bold_italic = FontUtils.createFont(SWT.ITALIC);
+
+ public void setSearchEnabled(boolean b) {
+ this.searchEnabled = b;
+ }
+
+ public AbstractGlossaryLabelProvider(int referenceColumn,
+ List<String> translations, IWorkbenchPage page) {
+ this.referenceColumn = referenceColumn;
+ this.translations = translations;
+ if (page.getActiveEditor() != null) {
+ selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
+ }
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ try {
+ Term term = (Term) element;
+ if (term != null) {
+ Translation transl = term.getTranslation(this.translations
+ .get(columnIndex));
+ return transl != null ? transl.value : "";
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return "";
+ }
+
+ public boolean isSearchEnabled() {
+ return this.searchEnabled;
+ }
+
+ protected boolean isMatchingToPattern(Object element, int columnIndex) {
+ boolean matching = false;
+
+ if (element instanceof Term) {
+ Term term = (Term) element;
+
+ if (term.getInfo() == null)
+ return false;
+
+ FilterInfo filterInfo = (FilterInfo) term.getInfo();
+
+ matching = filterInfo.hasFoundInTranslation(translations
+ .get(columnIndex));
+ }
+
+ return matching;
+ }
+
+ protected boolean isCrossRefRegion(String cellText) {
+ if (selectedItem != null) {
+ for (IMessage entry : selectedItem.getMessagesBundleGroup()
+ .getMessages(selectedItem.getMessageKey())) {
+ String value = entry.getValue();
+ String[] subValues = value.split("[\\s\\p{Punct}]+");
+ for (String v : subValues) {
+ if (v.trim().equalsIgnoreCase(cellText.trim()))
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ protected Font getColumnFont(Object element, int columnIndex) {
+ if (columnIndex == 0) {
+ return bold_italic;
+ }
+ return null;
+ }
+
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+ try {
+ if (selection.isEmpty())
+ return;
+
+ if (!(selection instanceof IStructuredSelection))
+ return;
+
+ IStructuredSelection sel = (IStructuredSelection) selection;
+ selectedItem = (IKeyTreeNode) sel.iterator().next();
+ this.getViewer().refresh();
+ } catch (Exception e) {
+ // silent catch
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ event.getSelection();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
index c36862fa..0546c7ad 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
@@ -1,97 +1,107 @@
-package org.eclipselabs.tapiji.translator.views.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-
-
-public class GlossaryContentProvider implements ITreeContentProvider {
-
- private Glossary glossary;
- private boolean grouped = false;
-
- public GlossaryContentProvider (Glossary glossary) {
- this.glossary = glossary;
- }
-
- public Glossary getGlossary () {
- return glossary;
- }
-
- public void setGrouped (boolean grouped) {
- this.grouped = grouped;
- }
-
- @Override
- public void dispose() {
- this.glossary = null;
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput instanceof Glossary)
- this.glossary = (Glossary) newInput;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (!grouped)
- return getAllElements(glossary.terms).toArray(new Term[glossary.terms.size()]);
-
- if (glossary != null)
- return glossary.getAllTerms();
-
- return null;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (!grouped)
- return null;
-
- if (parentElement instanceof Term) {
- Term t = (Term) parentElement;
- return t.getAllSubTerms ();
- }
- return null;
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof Term) {
- Term t = (Term) element;
- return t.getParentTerm();
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (!grouped)
- return false;
-
- if (element instanceof Term) {
- Term t = (Term) element;
- return t.hasChildTerms();
- }
- return false;
- }
-
- public List<Term> getAllElements (List<Term> terms) {
- List<Term> allTerms = new ArrayList<Term>();
-
- if (terms != null) {
- for (Term term : terms) {
- allTerms.add(term);
- allTerms.addAll(getAllElements(term.subTerms));
- }
- }
-
- return allTerms;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+
+public class GlossaryContentProvider implements ITreeContentProvider {
+
+ private Glossary glossary;
+ private boolean grouped = false;
+
+ public GlossaryContentProvider(Glossary glossary) {
+ this.glossary = glossary;
+ }
+
+ public Glossary getGlossary() {
+ return glossary;
+ }
+
+ public void setGrouped(boolean grouped) {
+ this.grouped = grouped;
+ }
+
+ @Override
+ public void dispose() {
+ this.glossary = null;
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ if (newInput instanceof Glossary)
+ this.glossary = (Glossary) newInput;
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (!grouped)
+ return getAllElements(glossary.terms).toArray(
+ new Term[glossary.terms.size()]);
+
+ if (glossary != null)
+ return glossary.getAllTerms();
+
+ return null;
+ }
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (!grouped)
+ return null;
+
+ if (parentElement instanceof Term) {
+ Term t = (Term) parentElement;
+ return t.getAllSubTerms();
+ }
+ return null;
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof Term) {
+ Term t = (Term) element;
+ return t.getParentTerm();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ if (!grouped)
+ return false;
+
+ if (element instanceof Term) {
+ Term t = (Term) element;
+ return t.hasChildTerms();
+ }
+ return false;
+ }
+
+ public List<Term> getAllElements(List<Term> terms) {
+ List<Term> allTerms = new ArrayList<Term>();
+
+ if (terms != null) {
+ for (Term term : terms) {
+ allTerms.add(term);
+ allTerms.addAll(getAllElements(term.subTerms));
+ }
+ }
+
+ return allTerms;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
deleted file mode 100644
index 958d081f..00000000
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package org.eclipselabs.tapiji.translator.views.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.editor.api.EditorUtil;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipselabs.tapiji.translator.utils.FontUtils;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
-
-public class GlossaryLabelProvider extends StyledCellLabelProvider implements
- ISelectionListener, ISelectionChangedListener {
-
- private boolean searchEnabled = false;
- private int referenceColumn = 0;
- private List<String> translations;
- private IKeyTreeNode selectedItem;
-
- /*** COLORS ***/
- private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
- private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
- private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
- private Color info_crossref = FontUtils.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- private Color info_crossref_foreground = FontUtils.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- private Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE);
-
- /*** FONTS ***/
- private Font bold = FontUtils.createFont(SWT.BOLD);
- private Font bold_italic = FontUtils.createFont(SWT.ITALIC);
-
- public void setSearchEnabled(boolean b) {
- this.searchEnabled = b;
- }
-
- public GlossaryLabelProvider(int referenceColumn, List<String> translations, IWorkbenchPage page) {
- this.referenceColumn = referenceColumn;
- this.translations = translations;
- if (page.getActiveEditor() != null) {
- selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
- }
- }
-
- public String getColumnText(Object element, int columnIndex) {
- try {
- Term term = (Term) element;
- if (term != null) {
- Translation transl = term.getTranslation(this.translations.get(columnIndex));
- return transl != null ? transl.value : "";
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "";
- }
-
- public boolean isSearchEnabled () {
- return this.searchEnabled;
- }
-
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
- boolean matching = false;
-
- if (element instanceof Term) {
- Term term = (Term) element;
-
- if (term.getInfo() == null)
- return false;
-
- FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- matching = filterInfo.hasFoundInTranslation(translations.get(columnIndex));
- }
-
- return matching;
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
- cell.setText(this.getColumnText(element, columnIndex));
-
- if (isCrossRefRegion(cell.getText())) {
- cell.setFont (bold);
- cell.setBackground(info_crossref);
- cell.setForeground(info_crossref_foreground);
- } else {
- cell.setFont(this.getColumnFont(element, columnIndex));
- cell.setBackground(transparent);
- }
-
- if (isSearchEnabled()) {
- if (isMatchingToPattern(element, columnIndex) ) {
- List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((Term)element).getInfo();
-
- for (Region reg : filterInfo.getFoundInTranslationRanges(translations.get(columnIndex < referenceColumn ? columnIndex + 1 : columnIndex))) {
- styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
- }
-
- cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
- } else {
- cell.setForeground(gray);
- }
- }
- }
-
- private boolean isCrossRefRegion(String cellText) {
- if (selectedItem != null) {
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
- String value = entry.getValue();
- String[] subValues = value.split("[\\s\\p{Punct}]+");
- for (String v : subValues) {
- if (v.trim().equalsIgnoreCase(cellText.trim()))
- return true;
- }
- }
- }
-
- return false;
- }
-
- private Font getColumnFont(Object element, int columnIndex) {
- if (columnIndex == 0) {
- return bold_italic;
- }
- return null;
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- try {
- if (selection.isEmpty())
- return;
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- IStructuredSelection sel = (IStructuredSelection) selection;
- selectedItem = (IKeyTreeNode) sel.iterator().next();
- this.getViewer().refresh();
- } catch (Exception e) {
- // silent catch
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- event.getSelection();
- }
-
-}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
index e8de6d4c..30e603f0 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
@@ -1,85 +1,97 @@
-package org.eclipselabs.tapiji.translator.views.widgets.sorter;
-
-import java.util.List;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-
-
-public class GlossaryEntrySorter extends ViewerSorter {
-
- private StructuredViewer viewer;
- private SortInfo sortInfo;
- private int referenceCol;
- private List<String> translations;
-
- public GlossaryEntrySorter (StructuredViewer viewer,
- SortInfo sortInfo,
- int referenceCol,
- List<String> translations) {
- this.viewer = viewer;
- this.referenceCol = referenceCol;
- this.translations = translations;
-
- if (sortInfo != null)
- this.sortInfo = sortInfo;
- else
- this.sortInfo = new SortInfo();
- }
-
- public StructuredViewer getViewer() {
- return viewer;
- }
-
- public void setViewer(StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public SortInfo getSortInfo() {
- return sortInfo;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- this.sortInfo = sortInfo;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- try {
- if (!(e1 instanceof Term && e2 instanceof Term))
- return super.compare(viewer, e1, e2);
- Term comp1 = (Term) e1;
- Term comp2 = (Term) e2;
-
- int result = 0;
-
- if (sortInfo == null)
- return 0;
-
- if (sortInfo.getColIdx() == 0) {
- Translation transComp1 = comp1.getTranslation(translations.get(referenceCol));
- Translation transComp2 = comp2.getTranslation(translations.get(referenceCol));
- if (transComp1 != null && transComp2 != null)
- result = transComp1.value.compareTo(transComp2.value);
- } else {
- int col = sortInfo.getColIdx() < referenceCol ? sortInfo.getColIdx() + 1 : sortInfo.getColIdx();
- Translation transComp1 = comp1.getTranslation(translations.get(col));
- Translation transComp2 = comp2.getTranslation(translations.get(col));
-
- if (transComp1 == null)
- transComp1 = new Translation();
- if (transComp2 == null)
- transComp2 = new Translation();
- result = transComp1.value.compareTo(transComp2.value);
- }
-
- return result * (sortInfo.isDESC() ? -1 : 1);
- } catch (Exception e) {
- return 0;
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.sorter;
+
+import java.util.List;
+
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class GlossaryEntrySorter extends ViewerSorter {
+
+ private StructuredViewer viewer;
+ private SortInfo sortInfo;
+ private int referenceCol;
+ private List<String> translations;
+
+ public GlossaryEntrySorter(StructuredViewer viewer, SortInfo sortInfo,
+ int referenceCol, List<String> translations) {
+ this.viewer = viewer;
+ this.referenceCol = referenceCol;
+ this.translations = translations;
+
+ if (sortInfo != null)
+ this.sortInfo = sortInfo;
+ else
+ this.sortInfo = new SortInfo();
+ }
+
+ public StructuredViewer getViewer() {
+ return viewer;
+ }
+
+ public void setViewer(StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public SortInfo getSortInfo() {
+ return sortInfo;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ this.sortInfo = sortInfo;
+ }
+
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ try {
+ if (!(e1 instanceof Term && e2 instanceof Term))
+ return super.compare(viewer, e1, e2);
+ Term comp1 = (Term) e1;
+ Term comp2 = (Term) e2;
+
+ int result = 0;
+
+ if (sortInfo == null)
+ return 0;
+
+ if (sortInfo.getColIdx() == 0) {
+ Translation transComp1 = comp1.getTranslation(translations
+ .get(referenceCol));
+ Translation transComp2 = comp2.getTranslation(translations
+ .get(referenceCol));
+ if (transComp1 != null && transComp2 != null)
+ result = transComp1.value.compareTo(transComp2.value);
+ } else {
+ int col = sortInfo.getColIdx() < referenceCol ? sortInfo
+ .getColIdx() + 1 : sortInfo.getColIdx();
+ Translation transComp1 = comp1.getTranslation(translations
+ .get(col));
+ Translation transComp2 = comp2.getTranslation(translations
+ .get(col));
+
+ if (transComp1 == null)
+ transComp1 = new Translation();
+ if (transComp2 == null)
+ transComp2 = new Translation();
+ result = transComp1.value.compareTo(transComp2.value);
+ }
+
+ return result * (sortInfo.isDESC() ? -1 : 1);
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
index a5f8e99e..1118283e 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
@@ -1,56 +1,65 @@
-package org.eclipselabs.tapiji.translator.views.widgets.sorter;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-
-public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
- private int colIdx;
- private boolean DESC;
- private List<Locale> visibleLocales;
-
- public void setDESC(boolean dESC) {
- DESC = dESC;
- }
-
- public boolean isDESC() {
- return DESC;
- }
-
- public void setColIdx(int colIdx) {
- this.colIdx = colIdx;
- }
-
- public int getColIdx() {
- return colIdx;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void saveState (IMemento memento) {
- IMemento mCI = memento.createChild(TAG_SORT_INFO);
- mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
- mCI.putBoolean(TAG_ORDER, DESC);
- }
-
- public void init (IMemento memento) {
- IMemento mCI = memento.getChild(TAG_SORT_INFO);
- if (mCI == null)
- return;
- colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
- DESC = mCI.getBoolean(TAG_ORDER);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.sorter;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+
+public class SortInfo {
+
+ public static final String TAG_SORT_INFO = "sort_info";
+ public static final String TAG_COLUMN_INDEX = "col_idx";
+ public static final String TAG_ORDER = "order";
+
+ private int colIdx;
+ private boolean DESC;
+ private List<Locale> visibleLocales;
+
+ public void setDESC(boolean dESC) {
+ DESC = dESC;
+ }
+
+ public boolean isDESC() {
+ return DESC;
+ }
+
+ public void setColIdx(int colIdx) {
+ this.colIdx = colIdx;
+ }
+
+ public int getColIdx() {
+ return colIdx;
+ }
+
+ public void setVisibleLocales(List<Locale> visibleLocales) {
+ this.visibleLocales = visibleLocales;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public void saveState(IMemento memento) {
+ IMemento mCI = memento.createChild(TAG_SORT_INFO);
+ mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
+ mCI.putBoolean(TAG_ORDER, DESC);
+ }
+
+ public void init(IMemento memento) {
+ IMemento mCI = memento.getChild(TAG_SORT_INFO);
+ if (mCI == null)
+ return;
+ colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
+ DESC = mCI.getBoolean(TAG_ORDER);
+ }
+}
|
eefd1c4ca69fc82c63230dfe30a5752c661388e9
|
spring-framework
|
Add context hierarchy tests to Spring MVC Test--Issue: SPR-5613-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java
index fb75d1048f6c..63ee9376bf9f 100644
--- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java
+++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java
@@ -16,20 +16,21 @@
package org.springframework.test.web.servlet.samples.context;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.samples.context.JavaConfigTests.RootConfig;
import org.springframework.test.web.servlet.samples.context.JavaConfigTests.WebConfig;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@@ -42,6 +43,13 @@
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+import static org.mockito.Mockito.*;
+
+
/**
* Tests with Java configuration.
*
@@ -50,18 +58,33 @@
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/test/resources/META-INF/web-resources")
-@ContextConfiguration(classes = WebConfig.class)
+@ContextHierarchy({
+ @ContextConfiguration(classes = RootConfig.class),
+ @ContextConfiguration(classes = WebConfig.class)
+})
public class JavaConfigTests {
@Autowired
private WebApplicationContext wac;
+ @Autowired
+ private PersonDao personDao;
+
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
+ when(this.personDao.getPerson(5L)).thenReturn(new Person("Joe"));
+ }
+
+ @Test
+ public void person() throws Exception {
+ this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Test
@@ -72,10 +95,27 @@ public void tilesDefinitions() throws Exception {
}
+ @Configuration
+ static class RootConfig {
+
+ @Bean
+ public PersonDao personDao() {
+ return Mockito.mock(PersonDao.class);
+ }
+ }
+
@Configuration
@EnableWebMvc
static class WebConfig extends WebMvcConfigurerAdapter {
+ @Autowired
+ private RootConfig rootConfig;
+
+ @Bean
+ public PersonController personController() {
+ return new PersonController(this.rootConfig.personDao());
+ }
+
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java
new file mode 100644
index 000000000000..ffeea88e449f
--- /dev/null
+++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.springframework.test.web.servlet.samples.context;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.test.web.Person;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@Controller
+public class PersonController {
+
+ private final PersonDao personDao;
+
+
+ public PersonController(PersonDao personDao) {
+ this.personDao = personDao;
+ }
+
+ @RequestMapping(value="/person/{id}", method=RequestMethod.GET)
+ @ResponseBody
+ public Person getPerson(@PathVariable long id) {
+ return this.personDao.getPerson(id);
+ }
+
+}
diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java
new file mode 100644
index 000000000000..035b9595d4c4
--- /dev/null
+++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+
+package org.springframework.test.web.servlet.samples.context;
+
+import org.springframework.test.web.Person;
+
+public interface PersonDao {
+
+ Person getPerson(Long id);
+
+}
diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java
index 2fb361f9154e..23cd46d5c34f 100644
--- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java
+++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java
@@ -28,6 +28,7 @@
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
@@ -42,7 +43,10 @@
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/test/resources/META-INF/web-resources")
-@ContextConfiguration("servlet-context.xml")
+@ContextHierarchy({
+ @ContextConfiguration("root-context.xml"),
+ @ContextConfiguration("servlet-context.xml")
+})
public class WebAppResourceTests {
@Autowired
diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java
index 73ab1ab0a95c..e9091ef5b08d 100644
--- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java
+++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java
@@ -16,20 +16,26 @@
package org.springframework.test.web.servlet.samples.context;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
+import static org.mockito.Mockito.*;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
/**
* Tests with XML configuration.
*
@@ -38,18 +44,33 @@
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/test/resources/META-INF/web-resources")
-@ContextConfiguration("servlet-context.xml")
+@ContextHierarchy({
+ @ContextConfiguration("root-context.xml"),
+ @ContextConfiguration("servlet-context.xml")
+})
public class XmlConfigTests {
@Autowired
private WebApplicationContext wac;
+ @Autowired
+ private PersonDao personDao;
+
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
+ when(this.personDao.getPerson(5L)).thenReturn(new Person("Joe"));
+ }
+
+ @Test
+ public void person() throws Exception {
+ this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Test
diff --git a/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml
new file mode 100644
index 000000000000..6456a634caeb
--- /dev/null
+++ b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
+
+ <bean id="personDao" class="org.mockito.Mockito" factory-method="mock">
+ <constructor-arg value="org.springframework.test.web.servlet.samples.context.PersonDao" />
+ </bean>
+
+</beans>
\ No newline at end of file
diff --git a/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml
index 4e567b1a843d..615534d26d6c 100644
--- a/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml
+++ b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml
@@ -7,6 +7,10 @@
<mvc:annotation-driven />
+ <bean class="org.springframework.test.web.servlet.samples.context.PersonController">
+ <constructor-arg ref="personDao"/>
+ </bean>
+
<mvc:view-controller path="/" view-name="home" />
<mvc:resources mapping="/resources/**" location="/resources/" />
|
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\
|
337192523cb453b134d6279f18d9edf4ef5f40aa
|
apache$hama
|
Optimize memory use.
git-svn-id: https://svn.apache.org/repos/asf/hama/trunk@1412065 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/hama
|
diff --git a/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java b/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java
index a5a066afc..cf7eb8b16 100644
--- a/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java
+++ b/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java
@@ -24,7 +24,6 @@
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -72,7 +71,7 @@ public static enum GraphJobCounter {
private Combiner<M> combiner;
private Partitioner<V, M> partitioner;
- private Map<V, Vertex<V, E, M>> vertices = new HashMap<V, Vertex<V, E, M>>();
+ private List<Vertex<V, E, M>> vertices = new ArrayList<Vertex<V, E, M>>();
private boolean updated = true;
private int globalUpdateCounts = 0;
@@ -144,8 +143,8 @@ public final void bsp(
public final void cleanup(
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException {
- for (Entry<V, Vertex<V, E, M>> e : vertices.entrySet()) {
- peer.write(e.getValue().getVertexID(), e.getValue().getValue());
+ for (Vertex<V, E, M> e : vertices) {
+ peer.write(e.getVertexID(), e.getValue());
}
}
@@ -180,7 +179,7 @@ private void doSuperstep(Map<V, List<M>> messages,
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException {
int activeVertices = 0;
- for (Vertex<V, E, M> vertex : vertices.values()) {
+ for (Vertex<V, E, M> vertex : vertices) {
List<M> msgs = messages.get(vertex.getVertexID());
// If there are newly received messages, restart.
if (vertex.isHalted() && msgs != null) {
@@ -216,7 +215,7 @@ private void doSuperstep(Map<V, List<M>> messages,
private void doInitialSuperstep(
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException {
- for (Vertex<V, E, M> vertex : vertices.values()) {
+ for (Vertex<V, E, M> vertex : vertices) {
List<M> singletonList = Collections.singletonList(vertex.getValue());
M lastValue = vertex.getValue();
vertex.compute(singletonList.iterator());
@@ -341,7 +340,7 @@ private void loadVertices(
peer.send(peer.getPeerName(partition), new GraphJobMessage(vertex));
} else {
vertex.setup(conf);
- vertices.put(vertex.getVertexID(), vertex);
+ vertices.add(vertex);
}
vertex = newVertexInstance(vertexClass, conf);
vertex.runner = this;
@@ -355,7 +354,7 @@ private void loadVertices(
Vertex<V, E, M> messagedVertex = (Vertex<V, E, M>) msg.getVertex();
messagedVertex.runner = this;
messagedVertex.setup(conf);
- vertices.put(messagedVertex.getVertexID(), messagedVertex);
+ vertices.add(messagedVertex);
}
startPos = peer.getPos();
}
@@ -370,7 +369,7 @@ private void loadVertices(
Vertex<V, E, M> messagedVertex = (Vertex<V, E, M>) msg.getVertex();
messagedVertex.runner = this;
messagedVertex.setup(conf);
- vertices.put(messagedVertex.getVertexID(), messagedVertex);
+ vertices.add(messagedVertex);
}
}
LOG.debug("Loading finished at " + peer.getSuperstepCount() + " steps.");
@@ -384,89 +383,77 @@ private void loadVertices(
*/
if (repairNeeded) {
LOG.debug("Starting repair of this graph!");
+ repair(peer, partitioningSteps, selfReference);
+ }
- int multiSteps = 0;
- MapWritable ssize = new MapWritable();
- ssize.put(new IntWritable(peer.getPeerIndex()),
- new IntWritable(vertices.size()));
- peer.send(getMasterTask(peer), new GraphJobMessage(ssize));
- ssize = null;
- peer.sync();
+ LOG.debug("Starting Vertex processing!");
+ }
- if (isMasterTask(peer)) {
- int minVerticesSize = Integer.MAX_VALUE;
- GraphJobMessage received = null;
- while ((received = peer.getCurrentMessage()) != null) {
- MapWritable x = received.getMap();
- for (Entry<Writable, Writable> e : x.entrySet()) {
- int curr = ((IntWritable) e.getValue()).get();
- if (minVerticesSize > curr) {
- minVerticesSize = curr;
- }
- }
- }
+ @SuppressWarnings("unchecked")
+ private void repair(
+ BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer,
+ int partitioningSteps, boolean selfReference) throws IOException,
+ SyncException, InterruptedException {
- if (minVerticesSize < (partitioningSteps * 2)) {
- multiSteps = minVerticesSize;
- } else {
- multiSteps = (partitioningSteps * 2);
- }
+ int multiSteps = 0;
+ MapWritable ssize = new MapWritable();
+ ssize.put(new IntWritable(peer.getPeerIndex()),
+ new IntWritable(vertices.size()));
+ peer.send(getMasterTask(peer), new GraphJobMessage(ssize));
+ ssize = null;
+ peer.sync();
- for (String peerName : peer.getAllPeerNames()) {
- MapWritable temp = new MapWritable();
- temp.put(new Text("steps"), new IntWritable(multiSteps));
- peer.send(peerName, new GraphJobMessage(temp));
+ if (isMasterTask(peer)) {
+ int minVerticesSize = Integer.MAX_VALUE;
+ GraphJobMessage received = null;
+ while ((received = peer.getCurrentMessage()) != null) {
+ MapWritable x = received.getMap();
+ for (Entry<Writable, Writable> e : x.entrySet()) {
+ int curr = ((IntWritable) e.getValue()).get();
+ if (minVerticesSize > curr) {
+ minVerticesSize = curr;
+ }
}
}
- peer.sync();
- GraphJobMessage received = peer.getCurrentMessage();
- MapWritable x = received.getMap();
- for (Entry<Writable, Writable> e : x.entrySet()) {
- multiSteps = ((IntWritable) e.getValue()).get();
+ if (minVerticesSize < (partitioningSteps * 2)) {
+ multiSteps = minVerticesSize;
+ } else {
+ multiSteps = (partitioningSteps * 2);
}
- Set<V> keys = vertices.keySet();
- Map<V, Vertex<V, E, M>> tmp = new HashMap<V, Vertex<V, E, M>>();
+ for (String peerName : peer.getAllPeerNames()) {
+ MapWritable temp = new MapWritable();
+ temp.put(new Text("steps"), new IntWritable(multiSteps));
+ peer.send(peerName, new GraphJobMessage(temp));
+ }
+ }
+ peer.sync();
- int i = 0;
- int syncs = 0;
- for (V v : keys) {
- Vertex<V, E, M> vertex2 = vertices.get(v);
- for (Edge<V, E> e : vertices.get(v).getEdges()) {
- peer.send(vertex2.getDestinationPeerName(e),
- new GraphJobMessage(e.getDestinationVertexID()));
- }
+ GraphJobMessage received = peer.getCurrentMessage();
+ MapWritable x = received.getMap();
+ for (Entry<Writable, Writable> e : x.entrySet()) {
+ multiSteps = ((IntWritable) e.getValue()).get();
+ }
- if (syncs < multiSteps && (i % (vertices.size() / multiSteps)) == 0) {
- peer.sync();
- syncs++;
- GraphJobMessage msg = null;
- while ((msg = peer.getCurrentMessage()) != null) {
- V vertexName = (V) msg.getVertexId();
- if (!vertices.containsKey(vertexName)) {
- Vertex<V, E, M> newVertex = newVertexInstance(vertexClass, conf);
- newVertex.setVertexID(vertexName);
- newVertex.runner = this;
- if (selfReference) {
- newVertex.setEdges(Collections.singletonList(new Edge<V, E>(
- newVertex.getVertexID(), null)));
- } else {
- newVertex.setEdges(new ArrayList<Edge<V, E>>(0));
- }
- newVertex.setup(conf);
- tmp.put(vertexName, newVertex);
- }
- }
- }
- i++;
+ Map<V, Vertex<V, E, M>> tmp = new HashMap<V, Vertex<V, E, M>>();
+
+ int i = 0;
+ int syncs = 0;
+
+ for (Vertex<V, E, M> v : vertices) {
+ for (Edge<V, E> e : v.getEdges()) {
+ peer.send(v.getDestinationPeerName(e),
+ new GraphJobMessage(e.getDestinationVertexID()));
}
- peer.sync();
- GraphJobMessage msg = null;
- while ((msg = peer.getCurrentMessage()) != null) {
- V vertexName = (V) msg.getVertexId();
- if (!vertices.containsKey(vertexName)) {
+ if (syncs < multiSteps && (i % (vertices.size() / multiSteps)) == 0) {
+ peer.sync();
+ syncs++;
+ GraphJobMessage msg = null;
+ while ((msg = peer.getCurrentMessage()) != null) {
+ V vertexName = (V) msg.getVertexId();
+
Vertex<V, E, M> newVertex = newVertexInstance(vertexClass, conf);
newVertex.setVertexID(vertexName);
newVertex.runner = this;
@@ -477,18 +464,41 @@ private void loadVertices(
newVertex.setEdges(new ArrayList<Edge<V, E>>(0));
}
newVertex.setup(conf);
- vertices.put(vertexName, newVertex);
- newVertex = null;
+ tmp.put(vertexName, newVertex);
+
}
}
+ i++;
+ }
+
+ peer.sync();
+ GraphJobMessage msg = null;
+ while ((msg = peer.getCurrentMessage()) != null) {
+ V vertexName = (V) msg.getVertexId();
- for (Map.Entry<V, Vertex<V, E, M>> e : tmp.entrySet()) {
- vertices.put(e.getKey(), e.getValue());
+ Vertex<V, E, M> newVertex = newVertexInstance(vertexClass, conf);
+ newVertex.setVertexID(vertexName);
+ newVertex.runner = this;
+ if (selfReference) {
+ newVertex.setEdges(Collections.singletonList(new Edge<V, E>(newVertex
+ .getVertexID(), null)));
+ } else {
+ newVertex.setEdges(new ArrayList<Edge<V, E>>(0));
}
- tmp.clear();
+ newVertex.setup(conf);
+ tmp.put(vertexName, newVertex);
+ newVertex = null;
+
}
- LOG.debug("Starting Vertex processing!");
+ for (Vertex<V, E, M> e : vertices) {
+ if (tmp.containsKey((e.getVertexID()))) {
+ tmp.remove(e.getVertexID());
+ }
+ }
+
+ vertices.addAll(tmp.values());
+ tmp.clear();
}
/**
|
27725c56de43ad0ef67b32b1977e086d0704913c
|
Valadoc
|
Add support for vala 0.15.1
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/configure.in b/configure.in
index 3bfc86451c..95248c5761 100755
--- a/configure.in
+++ b/configure.in
@@ -62,12 +62,18 @@ AC_SUBST(LIBGDKPIXBUF_LIBS)
## Drivers:
##
-PKG_CHECK_MODULES(LIBVALA_0_16_X, libvala-0.16 >= 0.14.0, have_libvala_0_16_x="yes", have_libvala_0_16_x="no")
+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)
AC_SUBST(LIBVALA_0_16_X_LIBS)
+PKG_CHECK_MODULES(LIBVALA_0_15_0, libvala-0.16 = 0.15.0, have_libvala_0_15_0="yes", have_libvala_0_15_0="no")
+AM_CONDITIONAL(HAVE_LIBVALA_0_15_0, test "$have_libvala_0_15_0" = "yes")
+AC_SUBST(LIBVALA_0_15_0_CFLAGS)
+AC_SUBST(LIBVALA_0_15_0_LIBS)
+
+
PKG_CHECK_MODULES(LIBVALA_0_14_X, libvala-0.14 >= 0.13.2, have_libvala_0_14_x="yes", have_libvala_0_14_x="no")
AM_CONDITIONAL(HAVE_LIBVALA_0_14_X, test "$have_libvala_0_14_x" = "yes")
AC_SUBST(LIBVALA_0_14_X_CFLAGS)
diff --git a/src/driver/0.16.x/Makefile.am b/src/driver/0.16.x/Makefile.am
index a48f8219ce..b390213baa 100755
--- a/src/driver/0.16.x/Makefile.am
+++ b/src/driver/0.16.x/Makefile.am
@@ -5,11 +5,17 @@ NULL =
VERSIONED_VAPI_DIR=`pkg-config libvala-0.16 --variable vapidir`
+if HAVE_LIBVALA_0_15_0
+VALA_FLAGS = -D VALA_0_15_0
+endif
+
+
AM_CFLAGS = -g \
-DPACKAGE_ICONDIR=\"$(datadir)/valadoc/icons/\" \
-I ../../libvaladoc/ \
$(GLIB_CFLAGS) \
$(LIBGEE_CFLAGS) \
+ $(LIBVALA_0_15_0_CFLAGS) \
$(LIBVALA_0_16_X_CFLAGS) \
$(NULL)
@@ -52,6 +58,7 @@ libdriver.vala.stamp: $(libdriver_la_VALASOURCES)
libdriver_la_LIBADD = \
../../libvaladoc/libvaladoc.la \
$(GLIB_LIBS) \
+ $(LIBVALA_0_15_0_LIBS) \
$(LIBVALA_0_16_X_LIBS) \
$(LIBGEE_LIBS) \
$(NULL)
diff --git a/src/driver/0.16.x/driver.vala b/src/driver/0.16.x/driver.vala
index 35d43d1381..1a164976c0 100755
--- a/src/driver/0.16.x/driver.vala
+++ b/src/driver/0.16.x/driver.vala
@@ -33,7 +33,11 @@ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver {
private Api.Tree? tree;
public void write_gir (Settings settings, ErrorReporter reporter) {
+#if VALA_0_15_0
+ var gir_writer = new Vala.GIRWriter ();
+#else
var gir_writer = new Drivers.GirWriter (resolver);
+#endif
// put .gir file in current directory unless -d has been explicitly specified
string gir_directory = ".";
diff --git a/src/driver/0.16.x/girwriter.vala b/src/driver/0.16.x/girwriter.vala
index 12762d14fa..4128409b90 100644
--- a/src/driver/0.16.x/girwriter.vala
+++ b/src/driver/0.16.x/girwriter.vala
@@ -24,6 +24,8 @@
using Valadoc.Api;
+#if ! VALA_0_15_0
+
/**
* Code visitor generating .gir file for the public interface.
*/
@@ -201,3 +203,6 @@ public class Valadoc.Drivers.GirWriter : Vala.GIRWriter {
}
}
+
+#endif
+
diff --git a/src/driver/0.16.x/treebuilder.vala b/src/driver/0.16.x/treebuilder.vala
index 353119eb33..4813bcdd8f 100644
--- a/src/driver/0.16.x/treebuilder.vala
+++ b/src/driver/0.16.x/treebuilder.vala
@@ -82,11 +82,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
foreach (Vala.Comment c in vns.get_comments()) {
if (c.source_reference.file == vns.source_reference.file) {
Vala.SourceReference pos = c.source_reference;
+#if ! VALA_0_15_0
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);
}
+#else
+ comment = new SourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+#endif
break;
}
}
@@ -291,6 +295,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private SourceComment? create_comment (Vala.Comment? comment) {
+#if VALA_0_15_0
+ if (comment != null) {
+ Vala.SourceReference pos = comment.source_reference;
+ SourceFile file = files.get (pos.file);
+ return new SourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ }
+#else
if (comment != null) {
Vala.SourceReference pos = comment.source_reference;
SourceFile file = files.get (pos.file);
@@ -313,7 +324,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
return new SourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
}
}
-
+#endif
return null;
}
diff --git a/src/driver/Makefile.am b/src/driver/Makefile.am
index e366d3acf0..863cc95f6f 100755
--- a/src/driver/Makefile.am
+++ b/src/driver/Makefile.am
@@ -26,6 +26,10 @@ if HAVE_LIBVALA_0_14_X
DRIVER_0_14_X_DIR = 0.14.x
endif
+if HAVE_LIBVALA_0_15_0
+DRIVER_0_16_X_DIR = 0.16.x
+endif
+
if HAVE_LIBVALA_0_16_X
DRIVER_0_16_X_DIR = 0.16.x
endif
diff --git a/src/libvaladoc/Makefile.am b/src/libvaladoc/Makefile.am
index 7db46be6bd..b2f07a629d 100755
--- a/src/libvaladoc/Makefile.am
+++ b/src/libvaladoc/Makefile.am
@@ -1,5 +1,6 @@
NULL =
+DEFAULT_DRIVER = "`$(VALAC) --version`"
AM_CFLAGS = \
|
8a96307a3e4851e914e5fd6cbe698534f81e664b
|
Valadoc
|
driver/0.12.x: Add support for attributes
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/driver/0.12.x/treebuilder.vala b/src/driver/0.12.x/treebuilder.vala
index d64c2c9238..3099ceb23b 100644
--- a/src/driver/0.12.x/treebuilder.vala
+++ b/src/driver/0.12.x/treebuilder.vala
@@ -184,6 +184,55 @@ 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"
+ };
+
+ 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 SourceComment? create_comment (Vala.Comment? comment) {
if (comment != null) {
Vala.SourceReference pos = comment.source_reference;
@@ -700,6 +749,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
}
+ process_attributes (node, element.attributes);
process_children (node, element);
// save GLib.Error
@@ -730,6 +780,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
}
+ process_attributes (node, element.attributes);
process_children (node, element);
}
@@ -753,6 +804,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);
}
@@ -769,6 +821,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);
}
@@ -796,6 +849,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);
}
@@ -812,6 +866,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);
}
@@ -828,6 +883,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);
}
@@ -844,6 +900,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);
}
@@ -860,6 +917,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);
}
@@ -875,6 +933,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);
}
@@ -890,6 +949,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);
}
@@ -906,6 +966,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);
}
@@ -921,6 +982,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);
}
@@ -936,6 +998,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);
}
|
dc9563874163393853426a050003de459a86f048
|
kotlin
|
Method cache for ClassDescriptorSerializer--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java b/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java
index 0f7ad6edcbf3f..96435ae1283ad 100644
--- a/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java
+++ b/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java
@@ -728,12 +728,18 @@ public void serialize(ClassDescriptor klass) {
}
}
+ private static final MethodCache CLASS_OBJECT_SERIALIZER_METHOD_CACHE = new MethodCache(ClassObjectSerializer.class);
private class ClassObjectSerializer extends FullContentSerialier {
private ClassObjectSerializer(StringBuilder sb) {
super(sb);
}
+ @Override
+ protected MethodCache doGetMethodCache() {
+ return CLASS_OBJECT_SERIALIZER_METHOD_CACHE;
+ }
+
@Override
public void serialize(ClassKind kind) {
assert kind == ClassKind.OBJECT : "Must be called for class objects only";
|
c94e990f4670af28bc87528c1874946e920eabab
|
orientdb
|
OOM reported by NMSWorks was fixed.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/common/concur/lock/ODistributedCounter.java b/core/src/main/java/com/orientechnologies/common/concur/lock/ODistributedCounter.java
new file mode 100755
index 00000000000..b211899b797
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/common/concur/lock/ODistributedCounter.java
@@ -0,0 +1,117 @@
+package com.orientechnologies.common.concur.lock;
+
+import com.orientechnologies.orient.core.OOrientListenerAbstract;
+import com.orientechnologies.orient.core.Orient;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * * @author Andrey Lomakin (a.lomakin-at-orientechnologies.com)
+ */
+public class ODistributedCounter extends OOrientListenerAbstract {
+ private static final int HASH_INCREMENT = 0x61c88647;
+
+ private static final AtomicInteger nextHashCode = new AtomicInteger();
+ private final AtomicBoolean poolBusy = new AtomicBoolean();
+ private final int maxPartitions = Runtime.getRuntime().availableProcessors() << 3;
+ private final int MAX_RETRIES = 8;
+
+ private final ThreadLocal<Integer> threadHashCode = new ThreadHashCode();
+ private volatile AtomicLong[] counters = new AtomicLong[2];
+
+ public ODistributedCounter() {
+ for (int i = 0; i < counters.length; i++) {
+ counters[i] = new AtomicLong();
+ }
+
+ Orient.instance().registerWeakOrientStartupListener(this);
+ Orient.instance().registerWeakOrientShutdownListener(this);
+ }
+
+ public void increment() {
+ updateCounter(+1);
+ }
+
+ public void decrement() {
+ updateCounter(-1);
+ }
+
+ private void updateCounter(int delta) {
+ final int hashCode = threadHashCode.get();
+
+ while (true) {
+ final AtomicLong[] cts = counters;
+ final int index = (cts.length - 1) & hashCode;
+
+ AtomicLong counter = cts[index];
+
+ if (counter == null) {
+ if (!poolBusy.get() && poolBusy.compareAndSet(false, true)) {
+ if (cts == counters) {
+ counter = cts[index];
+
+ if (counter == null)
+ cts[index] = new AtomicLong();
+ }
+
+ poolBusy.set(false);
+ }
+
+ continue;
+ } else {
+ long v = counter.get();
+ int retries = 0;
+
+ if (cts.length < maxPartitions) {
+ while (retries < MAX_RETRIES) {
+ if (!counter.compareAndSet(v, v + delta)) {
+ retries++;
+ v = counter.get();
+ } else {
+ return;
+ }
+ }
+ } else {
+ counter.addAndGet(delta);
+ return;
+ }
+
+ if (!poolBusy.get() && poolBusy.compareAndSet(false, true)) {
+ if (cts == counters) {
+ if (cts.length < maxPartitions) {
+ counters = new AtomicLong[cts.length << 1];
+ System.arraycopy(cts, 0, counters, 0, cts.length);
+ }
+ }
+
+ poolBusy.set(false);
+ }
+
+ continue;
+ }
+ }
+ }
+
+ public boolean isEmpty() {
+ long sum = 0;
+
+ for (AtomicLong counter : counters)
+ if (counter != null)
+ sum += counter.get();
+
+ return sum == 0;
+ }
+
+ private static int nextHashCode() {
+ return nextHashCode.getAndAdd(HASH_INCREMENT);
+ }
+
+ private static class ThreadHashCode extends ThreadLocal<Integer> {
+ @Override
+ protected Integer initialValue() {
+ return nextHashCode();
+ }
+ }
+}
diff --git a/core/src/main/java/com/orientechnologies/common/concur/lock/OReadersWriterSpinLock.java b/core/src/main/java/com/orientechnologies/common/concur/lock/OReadersWriterSpinLock.java
old mode 100644
new mode 100755
index 5bacf186405..5cc90542279
--- a/core/src/main/java/com/orientechnologies/common/concur/lock/OReadersWriterSpinLock.java
+++ b/core/src/main/java/com/orientechnologies/common/concur/lock/OReadersWriterSpinLock.java
@@ -36,13 +36,13 @@
* @since 8/18/14
*/
public class OReadersWriterSpinLock extends AbstractOwnableSynchronizer implements OOrientStartupListener, OOrientShutdownListener {
- private final OThreadCountersHashTable threadCountersHashTable = new OThreadCountersHashTable();
+ private final ODistributedCounter distributedCounter = new ODistributedCounter();
- private final AtomicReference<WNode> tail = new AtomicReference<WNode>();
- private volatile ThreadLocal<OModifiableInteger> lockHolds = new InitOModifiableInteger();
+ private final AtomicReference<WNode> tail = new AtomicReference<WNode>();
+ private volatile ThreadLocal<OModifiableInteger> lockHolds = new InitOModifiableInteger();
- private volatile ThreadLocal<WNode> myNode = new InitWNode();
- private volatile ThreadLocal<WNode> predNode = new ThreadLocal<WNode>();
+ private volatile ThreadLocal<WNode> myNode = new InitWNode();
+ private volatile ThreadLocal<WNode> predNode = new ThreadLocal<WNode>();
public OReadersWriterSpinLock() {
final WNode wNode = new WNode();
@@ -67,11 +67,11 @@ public void acquireReadLock() {
return;
}
- threadCountersHashTable.increment();
+ distributedCounter.increment();
WNode wNode = tail.get();
while (wNode.locked) {
- threadCountersHashTable.decrement();
+ distributedCounter.decrement();
while (wNode.locked && wNode == tail.get()) {
wNode.waitingReaders.add(Thread.currentThread());
@@ -82,7 +82,7 @@ public void acquireReadLock() {
wNode = tail.get();
}
- threadCountersHashTable.increment();
+ distributedCounter.increment();
wNode = tail.get();
}
@@ -102,7 +102,7 @@ public void releaseReadLock() {
return;
}
- threadCountersHashTable.decrement();
+ distributedCounter.decrement();
lHolds.decrement();
assert lHolds.intValue() == 0;
@@ -131,7 +131,7 @@ public void acquireWriteLock() {
pNode.waitingWriter = null;
- while (!threadCountersHashTable.isEmpty())
+ while (!distributedCounter.isEmpty())
;
setExclusiveOwnerThread(Thread.currentThread());
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/OPartitionedDatabasePool.java b/core/src/main/java/com/orientechnologies/orient/core/db/OPartitionedDatabasePool.java
old mode 100644
new mode 100755
index cdc6d31b598..f0d536ee542
--- a/core/src/main/java/com/orientechnologies/orient/core/db/OPartitionedDatabasePool.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/OPartitionedDatabasePool.java
@@ -84,12 +84,7 @@ public class OPartitionedDatabasePool extends OOrientListenerAbstract {
private final String userName;
private final String password;
private final int maxSize;
- private final ThreadLocal<PoolData> poolData = new ThreadLocal<PoolData>() {
- @Override
- protected PoolData initialValue() {
- return new PoolData();
- }
- };
+ private final ThreadLocal<PoolData> poolData = new ThreadPoolData();
private final AtomicBoolean poolBusy = new AtomicBoolean();
private final int maxPartitions = Runtime.getRuntime().availableProcessors() << 3;
private volatile PoolPartition[] partitions;
@@ -111,6 +106,13 @@ private static final class PoolPartition {
private final ConcurrentLinkedQueue<DatabaseDocumentTxPolled> queue = new ConcurrentLinkedQueue<DatabaseDocumentTxPolled>();
}
+ private static class ThreadPoolData extends ThreadLocal<PoolData> {
+ @Override
+ protected PoolData initialValue() {
+ return new PoolData();
+ }
+ }
+
private final class DatabaseDocumentTxPolled extends ODatabaseDocumentTx {
private PoolPartition partition;
|
ae6a2d38200dfe98755abfedf645621fe21ecf00
|
kotlin
|
Base class for surrounders for statements--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinIfSurrounderBase.java b/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinIfSurrounderBase.java
index 44851a6119c68..cc8467b3ef236 100644
--- a/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinIfSurrounderBase.java
+++ b/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinIfSurrounderBase.java
@@ -18,12 +18,10 @@
import com.intellij.codeInsight.CodeInsightUtilBase;
-import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
-import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.psi.JetBlockExpression;
@@ -34,30 +32,13 @@
import java.lang.String;
-public abstract class KotlinIfSurrounderBase implements Surrounder {
-
- @Override
- public boolean isApplicable(@NotNull PsiElement[] elements) {
- return true;
- }
+public abstract class KotlinIfSurrounderBase extends KotlinStatementsSurrounder {
@Nullable
@Override
- public TextRange surroundElements(
- @NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements
- ) throws IncorrectOperationException {
- PsiElement container = elements[0].getParent();
- if (container == null) return null;
- return surroundStatements (project, editor, container, elements);
- }
-
- public TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) throws IncorrectOperationException{
+ protected TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) {
// TODO extract variables declaration
- if (statements.length == 0){
- return null;
- }
-
JetIfExpression ifExpression = (JetIfExpression) JetPsiFactory.createExpression(project, getCodeTemplate());
ifExpression = (JetIfExpression) container.addAfter(ifExpression, statements[statements.length - 1]);
diff --git a/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinStatementsSurrounder.java b/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinStatementsSurrounder.java
new file mode 100644
index 0000000000000..93dd50169c15c
--- /dev/null
+++ b/idea/src/org/jetbrains/jet/plugin/codeInsight/surroundWith/statement/KotlinStatementsSurrounder.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2010-2013 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.plugin.codeInsight.surroundWith.statement;
+
+import com.intellij.lang.surroundWith.Surrounder;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.TextRange;
+import com.intellij.psi.PsiElement;
+import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public abstract class KotlinStatementsSurrounder implements Surrounder {
+
+ @Override
+ public boolean isApplicable(@NotNull PsiElement[] elements) {
+ return elements.length > 0;
+ }
+
+ @Override
+ @Nullable
+ public TextRange surroundElements(
+ @NotNull Project project,
+ @NotNull Editor editor,
+ @NotNull PsiElement[] elements
+ ) throws IncorrectOperationException {
+ PsiElement container = elements[0].getParent();
+ if (container == null) return null;
+ return surroundStatements(project, editor, container, elements);
+ }
+
+ @Nullable
+ protected abstract TextRange surroundStatements(
+ final Project project,
+ final Editor editor,
+ final PsiElement container,
+ final PsiElement[] statements
+ );
+}
|
efd0e554ca7e9365ec3880ef10706c9b6eca4394
|
camel
|
allow the installed languages to be browsed- restfully for CAMEL-1355--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@752938 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/camel
|
diff --git a/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java b/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java
index f8a72eb002eac..1015e9fd3c4cc 100644
--- a/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java
+++ b/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java
@@ -122,12 +122,11 @@ public RoutesResource getRoutesResource() {
public ConvertersResource getConvertersResource() {
return new ConvertersResource(this);
}
-/*
- public List<EndpointLink> getEndpoints() {
- return getEndpointsResource().getDTO().getEndpoints();
+ @Path("languages")
+ public LanguagesResource getLanguages() {
+ return new LanguagesResource(this);
}
-*/
}
diff --git a/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguageResource.java b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguageResource.java
new file mode 100644
index 0000000000000..9c09684852503
--- /dev/null
+++ b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguageResource.java
@@ -0,0 +1,46 @@
+/**
+ * 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.web.resources;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+
+import org.apache.camel.impl.converter.DefaultTypeConverter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * @version $Revision: 1.1 $
+ */
+public class LanguageResource extends CamelChildResourceSupport {
+ private static final transient Log LOG = LogFactory.getLog(LanguageResource.class);
+ private String id;
+
+ public LanguageResource(CamelContextResource contextResource, String id) {
+ super(contextResource);
+ this.id = id;
+ }
+
+
+ public String getId() {
+ return id;
+ }
+}
\ No newline at end of file
diff --git a/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguagesResource.java b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguagesResource.java
new file mode 100644
index 0000000000000..59b1de63c933b
--- /dev/null
+++ b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguagesResource.java
@@ -0,0 +1,57 @@
+/**
+ * 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.web.resources;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.List;
+
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+
+import org.apache.camel.impl.converter.DefaultTypeConverter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Represents the list of languages available in the current camel context
+ *
+ * @version $Revision: 1.1 $
+ */
+public class LanguagesResource extends CamelChildResourceSupport {
+ private static final transient Log LOG = LogFactory.getLog(LanguagesResource.class);
+
+ public LanguagesResource(CamelContextResource contextResource) {
+ super(contextResource);
+ }
+
+ public List<String> getLanguageIds() {
+ return getCamelContext().getLanguageNames();
+ }
+
+ /**
+ * Returns a specific language
+ */
+ @Path("{id}")
+ public LanguageResource getLanguage(@PathParam("id") String id) {
+ if (id == null) {
+ return null;
+ }
+ return new LanguageResource(getContextResource(), id);
+ }
+}
\ No newline at end of file
diff --git a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp
index c28f0dcd36d17..fb2f6b1acbcdc 100644
--- a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp
+++ b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp
@@ -26,6 +26,9 @@
</p>
<ul>
+ <li>
+ <a href="<c:url value='/languages'/>" title="View the available languages you can use with Camel">Languages</a>
+ </li>
<li>
<a href="<c:url value='/converters'/>" title="View the available type converters currently registered with Camel">Type Converters</a>
</li>
diff --git a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguageResource/index.jsp b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguageResource/index.jsp
new file mode 100644
index 0000000000000..e3d53f8863ae0
--- /dev/null
+++ b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguageResource/index.jsp
@@ -0,0 +1,18 @@
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <title>${it.id}</title>
+</head>
+<body>
+
+<h1>${it.id}</h1>
+
+<p>
+ Welcome to the ${it.id} language.
+</p>
+<p>
+ For more information see the <a href="http://camel.apache.org/${it.id}.html">documentation</a>
+</p>
+
+</body>
+</html>
diff --git a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguagesResource/index.jsp b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguagesResource/index.jsp
new file mode 100644
index 0000000000000..3306818ee7906
--- /dev/null
+++ b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguagesResource/index.jsp
@@ -0,0 +1,25 @@
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <title>Languages</title>
+</head>
+<body>
+
+<h1>Languages</h1>
+
+
+<table>
+ <tr>
+ <th>Language</th>
+ <th>Documentation</th>
+ </tr>
+ <c:forEach items="${it.languageIds}" var="id">
+ <tr>
+ <td><a href="languages/${id}">${id}</a></td>
+ <td><a href="http://camel.apache.org/${id}.html">documentation</a></td>
+ </tr>
+ </c:forEach>
+</table>
+
+</body>
+</html>
|
8a670906e9e04b883afeca949a6791fa02dc9058
|
Valadoc
|
gee-0.8
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/configure.ac b/configure.ac
index 5260732724..a8fc5543a0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -19,7 +19,7 @@ AC_PROG_LIBTOOL
##
VALA_REQUIRED=0.13.2
-LIBGEE_REQUIRED=0.5
+LIBGEE_REQUIRED=0.8.0
LIBGVC_REQUIRED=2.16
GLIB_REQUIRED=2.12.0
LIBGDKPIXBUF_REQUIRED=2.0
@@ -47,7 +47,7 @@ PKG_CHECK_MODULES(GMODULE, gmodule-2.0 >= $GLIB_REQUIRED)
AC_SUBST(GMODULE_CFLAGS)
AC_SUBST(GMODULE_LIBS)
-PKG_CHECK_MODULES(LIBGEE, gee-1.0 >= $LIBGEE_REQUIRED)
+PKG_CHECK_MODULES(LIBGEE, gee-0.8 >= $LIBGEE_REQUIRED)
AC_SUBST(LIBGEE_CFLAGS)
AC_SUBST(LIBGEE_LIBS)
diff --git a/src/doclets/devhelp/Makefile.am b/src/doclets/devhelp/Makefile.am
index 8cbd65060d..e7c2446290 100644
--- a/src/doclets/devhelp/Makefile.am
+++ b/src/doclets/devhelp/Makefile.am
@@ -36,7 +36,7 @@ libdoclet_la_SOURCES = \
libdoclet.vala.stamp: $(libdoclet_la_VALASOURCES)
- $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $^
+ $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $^
touch $@
diff --git a/src/doclets/gtkdoc/Makefile.am b/src/doclets/gtkdoc/Makefile.am
index b0ba3e0ca4..66dcc5576f 100644
--- a/src/doclets/gtkdoc/Makefile.am
+++ b/src/doclets/gtkdoc/Makefile.am
@@ -41,7 +41,7 @@ libdoclet_la_SOURCES = \
libdoclet.vala.stamp: $(libdoclet_la_VALASOURCES)
- $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $^
+ $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $^
touch $@
diff --git a/src/doclets/gtkdoc/gcomment.vala b/src/doclets/gtkdoc/gcomment.vala
index 4e683cac15..ae86792b1e 100644
--- a/src/doclets/gtkdoc/gcomment.vala
+++ b/src/doclets/gtkdoc/gcomment.vala
@@ -69,7 +69,7 @@ public class Gtkdoc.GComment {
builder.append_printf ("\n * @short_description: %s", commentize (brief_comment));
}
- headers.sort ((CompareFunc) Header.cmp);
+ headers.sort ((CompareDataFunc) Header.cmp);
foreach (var header in headers) {
builder.append_printf ("\n * @%s:", header.name);
if (header.annotations != null && header.annotations.length > 0) {
@@ -78,7 +78,7 @@ public class Gtkdoc.GComment {
}
builder.append_c (':');
}
-
+
if (header.value != null) {
builder.append_c (' ');
builder.append (commentize (header.value));
@@ -165,7 +165,7 @@ public class Gtkdoc.GComment {
builder.append (long_comment);
}
- headers.sort ((CompareFunc) Header.cmp);
+ headers.sort ((CompareDataFunc) Header.cmp);
if (headers.size > 0 || returns != null) {
builder.append ("""<variablelist role="params">""");
foreach (var header in headers) {
diff --git a/src/doclets/htm/Makefile.am b/src/doclets/htm/Makefile.am
index 75161b8eec..5f3be836e2 100644
--- a/src/doclets/htm/Makefile.am
+++ b/src/doclets/htm/Makefile.am
@@ -36,7 +36,7 @@ libdoclet_la_SOURCES = \
libdoclet.vala.stamp: $(libdoclet_la_VALASOURCES)
- $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $^
+ $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $^
touch $@
diff --git a/src/driver/0.10.x/Makefile.am b/src/driver/0.10.x/Makefile.am
index 9c285fda44..25e7289900 100644
--- a/src/driver/0.10.x/Makefile.am
+++ b/src/driver/0.10.x/Makefile.am
@@ -43,7 +43,7 @@ libdriver_la_SOURCES = \
libdriver.vala.stamp: $(libdriver_la_VALASOURCES)
- $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg vala-0.10 --pkg gee-1.0 --pkg valadoc-1.0 --vapidir $(VERSIONED_VAPI_DIR) --basedir . $^
+ $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg vala-0.10 --pkg gee-0.8 --pkg valadoc-1.0 --vapidir $(VERSIONED_VAPI_DIR) --basedir . $^
touch $@
diff --git a/src/driver/0.12.x/Makefile.am b/src/driver/0.12.x/Makefile.am
index 1c99d1d73e..00447b35ac 100644
--- a/src/driver/0.12.x/Makefile.am
+++ b/src/driver/0.12.x/Makefile.am
@@ -52,7 +52,7 @@ libdriver_la_SOURCES = \
libdriver.vala.stamp: $(libdriver_la_VALASOURCES)
- $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg $(VALA_PACKAGE_NAME) --pkg gee-1.0 --pkg valadoc-1.0 --vapidir $(VERSIONED_VAPI_DIR) --basedir . -D $(VALARUNTIMEFLAGS) $^
+ $(VALAC) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg $(VALA_PACKAGE_NAME) --pkg gee-0.8 --pkg valadoc-1.0 --vapidir $(VERSIONED_VAPI_DIR) --basedir . -D $(VALARUNTIMEFLAGS) $^
touch $@
diff --git a/src/driver/0.14.x/Makefile.am b/src/driver/0.14.x/Makefile.am
index 2e4fe6cf88..07c4c95062 100644
--- a/src/driver/0.14.x/Makefile.am
+++ b/src/driver/0.14.x/Makefile.am
@@ -52,7 +52,7 @@ libdriver_la_SOURCES = \
libdriver.vala.stamp: $(libdriver_la_VALASOURCES)
- $(VALAC) $(VALA_FLAGS) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(VERSIONED_VAPI_DIR) --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.14 --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $(VALA_FLAGS) $^
+ $(VALAC) $(VALA_FLAGS) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(VERSIONED_VAPI_DIR) --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.14 --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $(VALA_FLAGS) $^
touch $@
diff --git a/src/driver/0.16.x/Makefile.am b/src/driver/0.16.x/Makefile.am
index b390213baa..c33cc9f74f 100644
--- a/src/driver/0.16.x/Makefile.am
+++ b/src/driver/0.16.x/Makefile.am
@@ -51,7 +51,7 @@ libdriver_la_SOURCES = \
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.16 --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $^
+ $(VALAC) $(VALA_FLAGS) -C --vapidir $(VERSIONED_VAPI_DIR) --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.16 --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $^
touch $@
diff --git a/src/driver/0.18.x/Makefile.am b/src/driver/0.18.x/Makefile.am
index ad64d18208..d626a7f730 100644
--- a/src/driver/0.18.x/Makefile.am
+++ b/src/driver/0.18.x/Makefile.am
@@ -57,7 +57,7 @@ libdriver_la_SOURCES = \
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 . $^
+ $(VALAC) $(VALA_FLAGS) -C --vapidir $(VERSIONED_VAPI_DIR) --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.18 --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $^
touch $@
diff --git a/src/libvaladoc/Makefile.am b/src/libvaladoc/Makefile.am
index def3017776..5b81e1f429 100644
--- a/src/libvaladoc/Makefile.am
+++ b/src/libvaladoc/Makefile.am
@@ -173,7 +173,7 @@ libvaladocincludedir = $(includedir)/
libvaladoc.vala.stamp: $(libvaladoc_la_VALASOURCES)
- $(VALAC) $(VALAFLAGS) -C -H valadoc-1.0.h --pkg gee-1.0 --pkg libgvc --pkg gmodule-2.0 --pkg libgvc --vapidir $(top_srcdir)/src/vapi --pkg config --library valadoc-1.0 --basedir $(top_srcdir)/src/libvaladoc/ --save-temps $^
+ $(VALAC) $(VALAFLAGS) -C -H valadoc-1.0.h --pkg gee-0.8 --pkg libgvc --pkg gmodule-2.0 --pkg libgvc --vapidir $(top_srcdir)/src/vapi --pkg config --library valadoc-1.0 --basedir $(top_srcdir)/src/libvaladoc/ --save-temps $^
touch $@
diff --git a/src/libvaladoc/api/node.vala b/src/libvaladoc/api/node.vala
index c97d366899..9b2cee7feb 100644
--- a/src/libvaladoc/api/node.vala
+++ b/src/libvaladoc/api/node.vala
@@ -48,15 +48,15 @@ public abstract class Valadoc.Api.Node : Item, Browsable, Documentation, Compara
*/
public abstract NodeType node_type { get; }
- private Map<string,Node> per_name_children;
- private Map<NodeType?, Gee.List<Node>> per_type_children;
+ private Map<string, Node> per_name_children;
+ private Map<NodeType, Gee.List<Node>> per_type_children;
public Node (Node? parent, SourceFile? file, string? name, void* data) {
base (data);
- per_name_children = new HashMap<string,Node> ();
- per_type_children = new HashMap<NodeType?, Gee.List<Node>> (int_hash, int_equal);
+ per_name_children = new HashMap<string, Node> ();
+ per_type_children = new HashMap<NodeType, Gee.List<Node>> ();
if (name != null && (is_keyword (name) || name[0].isdigit ())) {
this.name = "@" + name;
diff --git a/src/libvaladoc/api/package.vala b/src/libvaladoc/api/package.vala
index 85be9bd835..8c2cad1846 100644
--- a/src/libvaladoc/api/package.vala
+++ b/src/libvaladoc/api/package.vala
@@ -85,27 +85,7 @@ public class Valadoc.Api.Package : Node {
internal void register_deprecated_symbol (Symbol symbol, string? version) {
if (deprecated == null) {
- // some libgee-versions do not like nullable strings
-
- EqualFunc<string?> str_eq0 = (a, b) => {
- if (a == null && b == null) {
- return true;
- } else if (a == null || b == null) {
- return false;
- }
-
- return a == b;
- };
-
- HashFunc<string?> str_hash0 = (a) => {
- if (a == null) {
- return 0;
- }
-
- return a.hash ();
- };
-
- deprecated = new HashMap<string?, ArrayList<Symbol>> (str_hash0, str_eq0);
+ deprecated = new HashMap<string?, ArrayList<Symbol>> ();
}
ArrayList<Symbol> list = deprecated.get (version);
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index f725ef7c3b..8b9c13e9e6 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -132,7 +132,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
Run? sec = null;
Iterator<Inline> iter = run.content.iterator ();
- for (bool has_next = iter.first (); has_next; has_next = iter.next ()) {
+ for (bool has_next = iter.next (); has_next; has_next = iter.next ()) {
Inline item = iter.get ();
if (sec == null) {
Inline? tmp = split_inline (item);
@@ -163,7 +163,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
Paragraph? sec = null;
Iterator<Inline> iter = p.content.iterator ();
- for (bool has_next = iter.first (); has_next; has_next = iter.next ()) {
+ for (bool has_next = iter.next (); has_next; has_next = iter.next ()) {
Inline item = iter.get ();
if (sec == null) {
Inline? tmp = split_inline (item);
@@ -262,7 +262,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
MapIterator<string, Api.SourceComment> iter = gir_comment.parameter_iterator ();
- for (bool has_next = iter.first (); has_next; has_next = iter.next ()) {
+ for (bool has_next = iter.next (); has_next; has_next = iter.next ()) {
Taglets.Param? taglet = this.parse_block_taglet (iter.get_value (), "param") as Taglets.Param;
if (taglet == null) {
return null;
diff --git a/src/libvaladoc/markupreader.vala b/src/libvaladoc/markupreader.vala
index 1d63642bf0..9752bf9904 100644
--- a/src/libvaladoc/markupreader.vala
+++ b/src/libvaladoc/markupreader.vala
@@ -54,7 +54,7 @@ public class Valadoc.MarkupReader : Object {
private int line;
private int column;
- private Map<string, string> attributes = new HashMap<string, string> (str_hash, str_equal);
+ private Map<string, string> attributes = new HashMap<string, string> ();
private bool empty_element;
private ErrorReporter reporter;
@@ -109,7 +109,7 @@ public class Valadoc.MarkupReader : Object {
* @return map of current attributes
*/
public Map<string,string> get_attributes () {
- var result = new HashMap<string,string> (str_hash, str_equal);
+ var result = new HashMap<string, string> ();
foreach (var key in attributes.keys) {
result.set (key, attributes.get (key));
}
diff --git a/src/libvaladoc/valadoc-1.0.deps.in b/src/libvaladoc/valadoc-1.0.deps.in
index 2e4a8477c6..485c5a5cea 100644
--- a/src/libvaladoc/valadoc-1.0.deps.in
+++ b/src/libvaladoc/valadoc-1.0.deps.in
@@ -1,3 +1,3 @@
libgvc
-gee-1.0
+gee-0.8
gmodule-2.0
diff --git a/src/libvaladoc/valadoc-1.0.pc.in b/src/libvaladoc/valadoc-1.0.pc.in
index b16036f359..8cf9ab02e0 100644
--- a/src/libvaladoc/valadoc-1.0.pc.in
+++ b/src/libvaladoc/valadoc-1.0.pc.in
@@ -9,6 +9,6 @@ vapidir=@datadir@/vala/vapi
Name: Valadoc
Description: The Vala documentation compiler library
Version: @VERSION@
-Requires: libgvc gee-1.0 gmodule-2.0
+Requires: libgvc gee-0.8 gmodule-2.0
Libs: -L${libdir} -lvaladoc
Cflags: -I${includedir}/valadoc-1.0
diff --git a/src/valadoc/Makefile.am b/src/valadoc/Makefile.am
index 156f8830d4..21013f5f96 100644
--- a/src/valadoc/Makefile.am
+++ b/src/valadoc/Makefile.am
@@ -41,7 +41,7 @@ valadoc_LDADD = \
valadoc.vala.stamp: $(valadoc_VALASOURCES)
- $(VALAC) -C --pkg config --pkg gee-1.0 --pkg gmodule-2.0 --vapidir $(top_srcdir)/src/vapi/ --vapidir ../libvaladoc/ --pkg valadoc-1.0 $^
+ $(VALAC) -C --pkg config --pkg gee-0.8 --pkg gmodule-2.0 --vapidir $(top_srcdir)/src/vapi/ --vapidir ../libvaladoc/ --pkg valadoc-1.0 $^
touch $@
diff --git a/tests/testrunner.sh b/tests/testrunner.sh
index 8de474a06d..ae22e633a8 100755
--- a/tests/testrunner.sh
+++ b/tests/testrunner.sh
@@ -30,7 +30,7 @@ export G_DEBUG=fatal_warnings
export PKG_CONFIG_PATH=../../src/libvaladoc
VALAC=valac
-VALAFLAGS="-X -D -X TOP_SRC_DIR=\"$topsrcdir\" --vapidir $topsrcdir/src/libvaladoc --pkg valadoc-1.0 --pkg gee-1.0 --disable-warnings --main main --save-temps -X -g -X -O0 -X -pipe -X -lm -X -Werror=return-type -X -Werror=init-self -X -Werror=implicit -X -Werror=sequence-point -X -Werror=return-type -X -Werror=uninitialized -X -Werror=pointer-arith -X -Werror=int-to-pointer-cast -X -Werror=pointer-to-int-cast -X -L$topsrcdir//src/libvaladoc/.libs -X -I$topsrcdir/src/libvaladoc $topsrcdir/tests/libvaladoc/parser/generic-scanner.vala $topsrcdir/tests/drivers/generic-api-test.vala"
+VALAFLAGS="-X -D -X TOP_SRC_DIR=\"$topsrcdir\" --vapidir $topsrcdir/src/libvaladoc --pkg valadoc-1.0 --pkg gee-0.8 --disable-warnings --main main --save-temps -X -g -X -O0 -X -pipe -X -lm -X -Werror=return-type -X -Werror=init-self -X -Werror=implicit -X -Werror=sequence-point -X -Werror=return-type -X -Werror=uninitialized -X -Werror=pointer-arith -X -Werror=int-to-pointer-cast -X -Werror=pointer-to-int-cast -X -L$topsrcdir//src/libvaladoc/.libs -X -I$topsrcdir/src/libvaladoc $topsrcdir/tests/libvaladoc/parser/generic-scanner.vala $topsrcdir/tests/drivers/generic-api-test.vala"
VAPIGEN=$topbuilddir/vapigen/vapigen
VAPIGENFLAGS=
|
058d4d4b5ffe40b8e93c7593f0b5346373455480
|
camel
|
CAMEL-3788 Merged the patch into camel-http4--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1083724 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/HttpProducer.java b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
index cf24b151c985a..8de7b8d7aca64 100644
--- a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
+++ b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
@@ -127,11 +127,13 @@ public HttpEndpoint getEndpoint() {
protected void populateResponse(Exchange exchange, HttpRequestBase httpRequest, HttpResponse httpResponse,
Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException, ClassNotFoundException {
+ // We just make the out message is not create when extractResponseBody throws exception
+ Object response = extractResponseBody(httpRequest, httpResponse, exchange);
Message answer = exchange.getOut();
answer.setHeaders(in.getHeaders());
answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
- answer.setBody(extractResponseBody(httpRequest, httpResponse, exchange));
+ answer.setBody(response);
// propagate HTTP response headers
Header[] headers = httpResponse.getAllHeaders();
|
9b7e3502534f268009d20160da252be094402867
|
coremedia$jangaroo-tools
|
Result of last night's hack session: Jangaroo IDEA 9 plugins have about the same functionality and bugs as their IDEA 8 counterparts!
* Found out that in IDEA 9, there still is a FacetImporter (only in another package)
and reverted to implementing that instead of MavenImporter.
* Added post-Maven-import tasks to patch Jangaroo libraries so that IDEA 9 finds
their source and let Jangaroo compiler output contribute to IDEA artefacts. Also fixed
that not only actual compiler output, but also resources are copied.
* Fixed several NPE problems.
[git-p4: depot-paths = "//coremedia/jangaroo/": change = 172489]
|
p
|
https://github.com/coremedia/jangaroo-tools
|
diff --git a/jangaroo-idea-9/ext-xml-idea-plugin/META-INF/plugin.xml b/jangaroo-idea-9/ext-xml-idea-plugin/META-INF/plugin.xml
index 969ff9c8d..6fcb109c7 100644
--- a/jangaroo-idea-9/ext-xml-idea-plugin/META-INF/plugin.xml
+++ b/jangaroo-idea-9/ext-xml-idea-plugin/META-INF/plugin.xml
@@ -5,13 +5,14 @@
<description>
A plugin supporting the Jangaroo EXML format for Ext JS UI development.
</description>
- <version>9-0.4.8-0</version>
+ <version>9-0.4.8-1</version>
<vendor url="http://www.jangaroo.net"
email="[email protected]"
logo="/net/jangaroo/jooley-16x16.png">Jangaroo</vendor>
<idea-version since-build="IU-93.94"/>
<depends>JavaScript</depends>
+ <depends>org.jetbrains.idea.maven</depends>
<depends>net.jangaroo.idea.language</depends>
<application-components>
@@ -40,7 +41,7 @@
</extensions>
<extensions defaultExtensionNs="org.jetbrains.idea.maven">
- <importer implementation="net.jangaroo.ide.idea.exml.ExmlMavenImporter"/>
+ <importer implementation="net.jangaroo.ide.idea.exml.ExmlFacetImporter"/>
</extensions>
</idea-plugin>
\ No newline at end of file
diff --git a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlCompiler.java b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlCompiler.java
index bc7eb92e0..ca1daf2ac 100644
--- a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlCompiler.java
+++ b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlCompiler.java
@@ -3,10 +3,12 @@
import com.intellij.compiler.impl.javaCompiler.OutputItemImpl;
import com.intellij.compiler.make.MakeUtil;
import com.intellij.facet.FacetManager;
+import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import com.intellij.openapi.compiler.TranslatingCompiler;
+import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModuleOrderEntry;
import com.intellij.openapi.roots.ModuleRootManager;
@@ -39,7 +41,6 @@
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
@@ -51,9 +52,6 @@
*/
public class ExmlCompiler implements TranslatingCompiler {
- private static final String JOO_SOURCES_PATH_REG_EXP = ".*\\bmain[/\\\\]joo\\b.*";
- private static final String GENERATED_SOURCES_PATH_REG_EXP = ".*\\bgenerated-sources\\b.*";
-
@NotNull
public String getDescription() {
return "EXML Compiler";
@@ -74,17 +72,14 @@ public boolean isCompilableFile(VirtualFile file, CompileContext context) {
return false;
}
- private static ExmlcConfigurationBean getExmlcConfiguration(Module module) {
+ private static ExmlcConfigurationBean getExmlConfig(Module module) {
ExmlFacet exmlFacet = FacetManager.getInstance(module).getFacetByType(ExmlFacetType.ID);
- if (exmlFacet==null) {
- return null;
- }
- return exmlFacet.getConfiguration().getState();
+ return exmlFacet == null ? null : exmlFacet.getConfiguration().getState();
}
static String getXsdFilename(Module module) {
if (module != null) {
- ExmlcConfigurationBean exmlcConfig = getExmlcConfiguration(module);
+ ExmlcConfigurationBean exmlcConfig = getExmlConfig(module);
if (exmlcConfig != null) {
return exmlcConfig.getGeneratedResourcesDirectory() + "/" + exmlcConfig.getXsd();
}
@@ -155,10 +150,14 @@ static ZipEntry findXsdZipEntry(ZipFile zipFile) throws IOException {
}
private ComponentSuite scanSrcFiles(Module module) {
- String sourceRootDir = findSourceRootDir(module, JOO_SOURCES_PATH_REG_EXP);
+ String sourceRootDir = findSourceRootDir(module);
+ String generatedAs3RootDir = findGeneratedAs3RootDir(module);
+ if (sourceRootDir == null || generatedAs3RootDir == null) {
+ return null;
+ }
String moduleName = module.getName();
ComponentSuite suite = new ComponentSuite(moduleName, moduleName.substring(0, Math.max(1, moduleName.length())).toLowerCase(),
- new File(sourceRootDir), new File(findGeneratedAs3RootDir(module)));
+ new File(sourceRootDir), new File(generatedAs3RootDir));
SrcFileScanner fileScanner = new SrcFileScanner(suite);
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
@@ -176,22 +175,26 @@ private ComponentSuite scanSrcFiles(Module module) {
private void generateXsd(Module module, ComponentSuite suite) {
if (!suite.getComponentClasses().isEmpty()) {
String xsdFilename = getXsdFilename(module);
- Writer out;
- File xsdFile;
- try {
- xsdFile = new File(xsdFilename);
- // (re-)generate the XSD for the given module.
- Log.setCurrentFile(xsdFile);
- out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xsdFile), "UTF-8"));
- } catch (Exception e) {
- Log.e("Cannot write component suite XSD file.", e);
- return;
- }
- try {
- new XsdGenerator(suite).generateXsd(out);
- LocalFileSystem.getInstance().refreshIoFiles(Arrays.asList(xsdFile));
- } catch (IOException e) {
- Log.e("Error while writing component suite XSD file.", e);
+ if (xsdFilename != null) {
+ Writer out;
+ File xsdFile;
+ try {
+ xsdFile = new File(xsdFilename);
+ //noinspection ResultOfMethodCallIgnored
+ xsdFile.getParentFile().mkdirs();
+ // (re-)generate the XSD for the given module.
+ Log.setCurrentFile(xsdFile);
+ out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xsdFile), "UTF-8"));
+ } catch (Exception e) {
+ Log.e("Cannot write component suite XSD file.", e);
+ return;
+ }
+ try {
+ new XsdGenerator(suite).generateXsd(out);
+ LocalFileSystem.getInstance().refreshIoFiles(Arrays.asList(xsdFile));
+ } catch (IOException e) {
+ Log.e("Error while writing component suite XSD file.", e);
+ }
}
}
}
@@ -221,6 +224,7 @@ private String compile(final CompileContext context, Module module, final List<V
} else {
OutputItem outputItem = new OutputItemImpl(outputFile.getPath().replace(File.separatorChar, '/'), file);
context.addMessage(CompilerMessageCategory.INFORMATION, "exml->as (" + outputItem.getOutputPath() + ")", file.getUrl(), -1, -1);
+ getLog().info("exml->as: " + file.getUrl() + " -> " + outputItem.getOutputPath());
LocalFileSystem.getInstance().refreshIoFiles(Arrays.asList(outputFile));
outputItems.add(outputItem);
}
@@ -235,18 +239,18 @@ private String compile(final CompileContext context, Module module, final List<V
}
private String findGeneratedAs3RootDir(Module module) {
- return findSourceRootDir(module, GENERATED_SOURCES_PATH_REG_EXP);
+ ExmlcConfigurationBean exmlConfig = getExmlConfig(module);
+ return exmlConfig == null ? null : getVFPath(exmlConfig.getGeneratedSourcesDirectory());
}
- private String findSourceRootDir(Module module, String GENERATED_SOURCES_PATH_REG_EXP) {
- VirtualFile[] srcRoots = ModuleRootManager.getInstance(module).getSourceRoots();
- for (VirtualFile srcRoot : srcRoots) {
- String path = srcRoot.getPath();
- if (path.matches(GENERATED_SOURCES_PATH_REG_EXP)) {
- return path;
- }
- }
- return srcRoots[0].getPath();
+ private String findSourceRootDir(Module module) {
+ ExmlcConfigurationBean exmlConfig = getExmlConfig(module);
+ return exmlConfig == null ? null : getVFPath(exmlConfig.getSourceDirectory());
+ }
+
+ private static String getVFPath(String path) {
+ VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path);
+ return virtualFile == null ? null : virtualFile.getPath();
}
public void compile(CompileContext context, Chunk<Module> moduleChunk, VirtualFile[] files, OutputSink outputSink) {
@@ -265,21 +269,26 @@ public void compile(CompileContext context, Chunk<Module> moduleChunk, VirtualFi
}
filesOfModule.add(file);
}
- final Map<String, String> resourceMap = new LinkedHashMap<String, String>();
for (Map.Entry<Module, List<VirtualFile>> filesOfModuleEntry : filesByModule.entrySet()) {
Module module = filesOfModuleEntry.getKey();
addModuleDependenciesToComponentSuiteRegistry(module);
ComponentSuite suite = scanSrcFiles(module);
- List<OutputItem> outputItems = new ArrayList<OutputItem>(files.length);
- List<VirtualFile> filesToRecompile = new ArrayList<VirtualFile>(files.length);
- String outputRoot = compile(context, module, filesOfModuleEntry.getValue(), outputItems, filesToRecompile);
- if (outputRoot != null) {
- outputSink.add(outputRoot, outputItems, filesToRecompile.toArray(new VirtualFile[filesToRecompile.size()]));
- generateXsd(module, suite);
+ if (suite != null) {
+ List<OutputItem> outputItems = new ArrayList<OutputItem>(files.length);
+ List<VirtualFile> filesToRecompile = new ArrayList<VirtualFile>(files.length);
+ String outputRoot = compile(context, module, filesOfModuleEntry.getValue(), outputItems, filesToRecompile);
+ if (outputRoot != null) {
+ outputSink.add(outputRoot, outputItems, filesToRecompile.toArray(new VirtualFile[filesToRecompile.size()]));
+ generateXsd(module, suite);
+ }
}
}
}
+ static Logger getLog() {
+ return IdeaLogger.getInstance("net.jangaroo.ide.idea.exml.ExmlCompiler");
+ }
+
private static class IdeaErrorHandler implements LogHandler {
private final CompileContext context;
private File currentFile;
@@ -301,29 +310,33 @@ private VirtualFile addMessage(CompilerMessageCategory compilerMessageCategory,
public void error(String message, int lineNumber, int columnNumber) {
addMessage(CompilerMessageCategory.ERROR, message, lineNumber, columnNumber);
+ getLog().error(message);
}
public void error(String message, Exception exception) {
- addMessage(CompilerMessageCategory.ERROR, message + ": " + exception.getLocalizedMessage(), -1, -1);
+ error(message + ": " + exception.getLocalizedMessage(), -1, -1);
}
public void error(String message) {
- addMessage(CompilerMessageCategory.ERROR, message, -1, -1);
+ error(message, -1, -1);
}
public void warning(String message) {
- addMessage(CompilerMessageCategory.WARNING, message, -1, -1);
+ warning(message, -1, -1);
}
public void warning(String message, int lineNumber, int columnNumber) {
addMessage(CompilerMessageCategory.WARNING, message, lineNumber, columnNumber);
+ getLog().warn(message);
}
public void info(String message) {
addMessage(CompilerMessageCategory.INFORMATION, message, -1, -1);
+ getLog().info(message);
}
public void debug(String message) {
+ getLog().debug(message);
//ignore debug messages for now
}
}
diff --git a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetConfiguration.java b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetConfiguration.java
index 3f3b90d92..0c1648b7b 100644
--- a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetConfiguration.java
+++ b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetConfiguration.java
@@ -26,35 +26,27 @@
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
/**
* EXML IDEA Facet configuration, so far empty.
*/
public class ExmlFacetConfiguration implements FacetConfiguration, PersistentStateComponent<ExmlcConfigurationBean> {
- private ExmlcConfigurationBean exmlcConfigurationBean;
+ private ExmlcConfigurationBean exmlcConfigurationBean = new ExmlcConfigurationBean();
public FacetEditorTab[] createEditorTabs(FacetEditorContext facetEditorContext, FacetValidatorsManager facetValidatorsManager) {
- return new FacetEditorTab[]{ new ExmlFacetEditorTab(getExmlcConfigurationBean(facetEditorContext))};
+ return new FacetEditorTab[]{ new ExmlFacetEditorTab(initExmlcConfigurationBean(facetEditorContext))};
}
- private synchronized ExmlcConfigurationBean getExmlcConfigurationBean(FacetEditorContext facetEditorContext) {
- if (exmlcConfigurationBean==null) {
- String outputPrefix = null, moduleName = null;
- if (facetEditorContext!=null) {
- Module module = facetEditorContext.getModule();
- if (module != null) {
- ModuleRootModel rootModel = facetEditorContext.getRootModel();
- if (rootModel != null) {
- VirtualFile[] contentRoots = rootModel.getContentRoots();
- if (contentRoots.length > 0) {
- outputPrefix = contentRoots[0].getPath();
- moduleName = module.getName();
- }
- }
- }
+ private synchronized ExmlcConfigurationBean initExmlcConfigurationBean(@NotNull FacetEditorContext facetEditorContext) {
+ if (exmlcConfigurationBean.getXsd() == null) {
+ Module module = facetEditorContext.getModule();
+ ModuleRootModel rootModel = facetEditorContext.getRootModel();
+ VirtualFile[] contentRoots = rootModel.getContentRoots();
+ if (contentRoots.length > 0) {
+ exmlcConfigurationBean.init(contentRoots[0].getPath(), module.getName());
}
- exmlcConfigurationBean = new ExmlcConfigurationBean(outputPrefix, moduleName);
}
return exmlcConfigurationBean;
}
@@ -68,15 +60,11 @@ public void writeExternal(Element element) throws WriteExternalException {
}
public ExmlcConfigurationBean getState() {
- return getExmlcConfigurationBean(null);
+ return exmlcConfigurationBean;
}
public void loadState(ExmlcConfigurationBean state) {
- if (exmlcConfigurationBean==null) {
- exmlcConfigurationBean = state;
- } else {
- // copy into existing instance, as it may already be used by some JangarooFacetEditorTab:
- XmlSerializerUtil.copyBean(state, exmlcConfigurationBean);
- }
+ // copy into existing instance, as it may already be used by some JangarooFacetEditorTab:
+ XmlSerializerUtil.copyBean(state, exmlcConfigurationBean);
}
}
\ No newline at end of file
diff --git a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlMavenImporter.java b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetImporter.java
similarity index 73%
rename from jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlMavenImporter.java
rename to jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetImporter.java
index 654685608..2e1f0be09 100644
--- a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlMavenImporter.java
+++ b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlFacetImporter.java
@@ -1,6 +1,6 @@
package net.jangaroo.ide.idea.exml;
-import com.intellij.facet.FacetManager;
+import com.intellij.idea.IdeaLogger;
import com.intellij.javaee.ExternalResourceManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModuleRootManager;
@@ -9,9 +9,13 @@
import net.jangaroo.extxml.model.ComponentSuite;
import net.jangaroo.extxml.xml.XsdScanner;
import net.jangaroo.utils.log.Log;
+import org.jetbrains.idea.maven.importing.FacetImporter;
import org.jetbrains.idea.maven.importing.MavenModifiableModelsProvider;
import org.jetbrains.idea.maven.importing.MavenRootModelAdapter;
-import org.jetbrains.idea.maven.project.*;
+import org.jetbrains.idea.maven.project.MavenProject;
+import org.jetbrains.idea.maven.project.MavenProjectChanges;
+import org.jetbrains.idea.maven.project.MavenProjectsProcessorTask;
+import org.jetbrains.idea.maven.project.MavenProjectsTree;
import javax.swing.*;
import java.io.FileInputStream;
@@ -28,47 +32,36 @@
/**
* A Facet-from-Maven Importer for the EXML Facet type.
*/
-public class ExmlMavenImporter extends org.jetbrains.idea.maven.importing.MavenImporter {
+public class ExmlFacetImporter extends FacetImporter<ExmlFacet, ExmlFacetConfiguration, ExmlFacetType> {
// TODO: share these constants with Jangaroo Language plugin:
private static final String JANGAROO_GROUP_ID = "net.jangaroo";
private static final String JANGAROO_LIFECYCLE_MAVEN_PLUGIN_ARTIFACT_ID = "jangaroo-lifecycle";
private static final String EXML_MAVEN_PLUGIN_ARTIFACT_ID = "ext-xml-maven-plugin";
private static final String DEFAULT_EXML_FACET_NAME = "EXML";
- public ExmlMavenImporter() {
- super();
+ public ExmlFacetImporter() {
+ super(JANGAROO_GROUP_ID, EXML_MAVEN_PLUGIN_ARTIFACT_ID, ExmlFacetType.INSTANCE, DEFAULT_EXML_FACET_NAME);
}
- @Override
- public boolean isSupportedDependency(MavenArtifact artifact) {
- return false;
- }
-
- @Override
public boolean isApplicable(MavenProject mavenProjectModel) {
return mavenProjectModel.findPlugin(JANGAROO_GROUP_ID, JANGAROO_LIFECYCLE_MAVEN_PLUGIN_ARTIFACT_ID) != null ||
mavenProjectModel.findPlugin(JANGAROO_GROUP_ID, EXML_MAVEN_PLUGIN_ARTIFACT_ID) != null;
}
- @Override
- public void preProcess(Module module, MavenProject mavenProject, MavenProjectChanges mavenProjectChanges, MavenModifiableModelsProvider mavenModifiableModelsProvider) {
- // TODO: anything to do here?
+ protected void setupFacet(ExmlFacet exmlFacet, MavenProject mavenProjectModel) {
+ //System.out.println("setupFacet called!");
}
@Override
- public void process(MavenModifiableModelsProvider modifiableModelsProvider, Module module,
- MavenRootModelAdapter rootModel, MavenProjectsTree mavenModel, MavenProject mavenProjectModel,
- MavenProjectChanges changes, Map<MavenProject, String> mavenProjectToModuleName,
- List<MavenProjectsProcessorTask> postTasks) {
- FacetManager facetManager = FacetManager.getInstance(module);
- ExmlFacet exmlFacet = facetManager.getFacetByType(ExmlFacetType.ID);
- if (exmlFacet == null) {
- exmlFacet = facetManager.addFacet(ExmlFacetType.INSTANCE, DEFAULT_EXML_FACET_NAME, null);
- }
+ protected void reimportFacet(MavenModifiableModelsProvider modelsProvider, Module module,
+ MavenRootModelAdapter rootModel, ExmlFacet exmlFacet, MavenProjectsTree mavenTree,
+ MavenProject mavenProjectModel, MavenProjectChanges changes,
+ Map<MavenProject, String> mavenProjectToModuleName, List<MavenProjectsProcessorTask> postTasks) {
+ //System.out.println("reimportFacet called!");
ExmlcConfigurationBean exmlConfig = exmlFacet.getConfiguration().getState();
exmlConfig.setSourceDirectory(mavenProjectModel.getSources().get(0));
exmlConfig.setGeneratedSourcesDirectory(mavenProjectModel.getGeneratedSourcesDirectory() + "/joo");
- exmlConfig.setGeneratedResourcesDirectory(mavenProjectModel.getBuildDirectory() + "/generated-resources");
+ exmlConfig.setGeneratedResourcesDirectory(getTargetOutputPath(mavenProjectModel, "generated-resources"));
exmlConfig.setNamespace(mavenProjectModel.getMavenModel().getArtifactId());
exmlConfig.setNamespacePrefix(mavenProjectModel.getMavenModel().getArtifactId());
exmlConfig.setXsd(mavenProjectModel.getMavenModel().getArtifactId() + ".xsd");
@@ -85,6 +78,11 @@ public void run() {
});
}
+ public void collectSourceFolders(MavenProject mavenProject, List<String> result) {
+ // TODO: peek into Maven config of ext-xml goal!
+ result.add("target/generated-sources/joo");
+ }
+
private Map<String, String> getXsdResourcesOfModule(Module module) {
// Collect the XSD resource mappings of this modules and all its dependent component suites.
//System.out.println("Scanning dependencies of " + moduleName + " for component suite XSDs...");
@@ -116,11 +114,11 @@ private Map<String, String> getXsdResourcesOfModule(Module module) {
}
}
String xsdFilename = ExmlCompiler.getXsdFilename(module);
- if (xsdFilename != null) {
+ if (xsdFilename != null && new File(xsdFilename).exists()) {
try {
addResource(resourceMap, scanner, new FileInputStream(xsdFilename), xsdFilename);
} catch (FileNotFoundException e) {
- Log.e("Error while scanning XSD file " + xsdFilename, e);
+ IdeaLogger.getInstance("exml").warn("Error while scanning XSD file " + xsdFilename, e);
}
}
return resourceMap;
@@ -134,7 +132,7 @@ private void addResource(Map<String, String> resourceMap, XsdScanner scanner, In
resourceMap.put(componentSuite.getNamespace(), filename);
}
} catch (IOException e) {
- Log.e("Error while scanning XSD file " + filename, e);
+ ExmlCompiler.getLog().warn("Error while scanning XSD file " + filename, e);
}
}
diff --git a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlcConfigurationBean.java b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlcConfigurationBean.java
index 495421420..e37dc5ef4 100644
--- a/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlcConfigurationBean.java
+++ b/jangaroo-idea-9/ext-xml-idea-plugin/src/main/java/net/jangaroo/ide/idea/exml/ExmlcConfigurationBean.java
@@ -60,10 +60,9 @@ public class ExmlcConfigurationBean {
private String generatedResourcesDirectory;
public ExmlcConfigurationBean() {
- this(null, null);
}
- public ExmlcConfigurationBean(String outputPrefix, String moduleName) {
+ public void init(String outputPrefix, String moduleName) {
if (outputPrefix != null) {
sourceDirectory = getIdeaUrl(outputPrefix + "/" + DEFAULT_SOURCE_DIRECTORY);
generatedSourcesDirectory = getIdeaUrl(outputPrefix + "/" + DEFAULT_GENERATED_SOURCES_DIRECTORY);
diff --git a/jangaroo-idea-9/idea-plugin/META-INF/plugin.xml b/jangaroo-idea-9/idea-plugin/META-INF/plugin.xml
index f9b08ce8b..6af0aee07 100644
--- a/jangaroo-idea-9/idea-plugin/META-INF/plugin.xml
+++ b/jangaroo-idea-9/idea-plugin/META-INF/plugin.xml
@@ -6,7 +6,7 @@
A plugin for compiling ActionScript 3 code to JavaScript using the Jangaroo Open Source
Compiler jooc.
</description>
- <version>9-0.4.8-0</version>
+ <version>9-0.4.8-1</version>
<vendor url="http://www.jangaroo.net"
email="[email protected]"
logo="/net/jangaroo/jooley-16x16.png">Jangaroo</vendor>
@@ -38,7 +38,7 @@
</extensions>
<extensions defaultExtensionNs="org.jetbrains.idea.maven">
- <importer implementation="net.jangaroo.ide.idea.JangarooMavenImporter"/>
+ <importer implementation="net.jangaroo.ide.idea.JangarooFacetImporter"/>
</extensions>
</idea-plugin>
\ No newline at end of file
diff --git a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompiler.java b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompiler.java
index b2aece4de..cf909e856 100644
--- a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompiler.java
+++ b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompiler.java
@@ -14,10 +14,12 @@
*/
package net.jangaroo.ide.idea;
+import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.TranslatingCompiler;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompilerMessageCategory;
+import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
@@ -71,7 +73,9 @@ private String compile(CompileContext context, Module module, final List<Virtual
? LocalFileSystem.getInstance().refreshAndFindFileByPath(outputDirectoryPath)
: LocalFileSystem.getInstance().findFileByPath(outputDirectoryPath);
if (outputDirectoryVirtualFile == null) {
- context.addMessage(CompilerMessageCategory.ERROR, "Output directory does not exist and could not be created: "+outputDirectoryPath, null, -1, -1);
+ String message = "Output directory does not exist and could not be created: " + outputDirectoryPath;
+ context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1);
+ getLog().error(message);
return null;
}
outputDirectoryPath = outputDirectoryVirtualFile.getPath();
@@ -86,7 +90,9 @@ private String compile(CompileContext context, Module module, final List<Virtual
? new OutputItemImpl(outputFileName, file)
: createOutputItem(outputDirectoryPath, MakeUtil.getSourceRoot(context, module, file), file);
outputItems.add(outputItem);
- context.addMessage(CompilerMessageCategory.INFORMATION, "as->js ("+outputItem.getOutputPath()+")", outputItem.getSourceFile().getUrl(), -1, -1);
+ String fileUrl = outputItem.getSourceFile().getUrl();
+ context.addMessage(CompilerMessageCategory.INFORMATION, "as->js (" + outputItem.getOutputPath() + ")", fileUrl, -1, -1);
+ getLog().info("as->js: " + fileUrl + " -> " + outputItem.getOutputPath());
}
}
}
@@ -161,6 +167,10 @@ public void compile(CompileContext context, Chunk<Module> moduleChunk, VirtualFi
}
}
+ private static Logger getLog() {
+ return IdeaLogger.getInstance("net.jangaroo.ide.idea.JangarooCompiler");
+ }
+
private static class IdeaCompileLog implements CompileLog {
private CompileContext compileContext;
private Set<VirtualFile> filesWithErrors;
@@ -179,18 +189,22 @@ private VirtualFile addMessage(CompilerMessageCategory compilerMessageCategory,
public void error(JooSymbol sym, String msg) {
filesWithErrors.add(addMessage(CompilerMessageCategory.ERROR, msg, sym));
+ getLog().error(sym.getFileName() + ":" + msg);
}
public void error(String msg) {
compileContext.addMessage(CompilerMessageCategory.ERROR, msg, null, -1, -1);
+ getLog().error(msg);
}
public void warning(JooSymbol sym, String msg) {
addMessage(CompilerMessageCategory.WARNING, msg, sym);
+ getLog().warn(sym.getFileName() + ":" + msg);
}
public void warning(String msg) {
compileContext.addMessage(CompilerMessageCategory.WARNING, msg, null, -1, -1);
+ getLog().warn(msg);
}
public boolean hasErrors() {
diff --git a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompilerOutputElement.java b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompilerOutputElement.java
index f2e42e43a..e73b4f37f 100644
--- a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompilerOutputElement.java
+++ b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooCompilerOutputElement.java
@@ -46,13 +46,11 @@ public void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerI
@NotNull ArtifactType artifactType) {
JangarooFacet facet = (JangarooFacet)myFacetPointer.getFacet();
if (facet != null) {
- // TODO: compute relativePath from webModule's JangarooFacet, if it exists:
- String relativePath = DeploymentUtil.trimForwardSlashes("/scripts/classes");
- File outputDirectory = facet.getConfiguration().getState().getOutputDirectory();
+ File outputDirectory = facet.getConfiguration().getState().getOutputDirectory().getParentFile();
if (outputDirectory.exists()) {
VirtualFile outputRoot = LocalFileSystem.getInstance().findFileByIoFile(outputDirectory);
assert outputRoot != null;
- creator.subFolderByRelativePath(relativePath).addDirectoryCopyInstructions(outputRoot);
+ creator.addDirectoryCopyInstructions(outputRoot);
}
}
}
diff --git a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetConfiguration.java b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetConfiguration.java
index b3879549f..e7f245c9e 100644
--- a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetConfiguration.java
+++ b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetConfiguration.java
@@ -21,41 +21,32 @@
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ModuleRootModel;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.module.Module;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
/**
* Jangaroo IDEA Facet configuration.
*/
public class JangarooFacetConfiguration implements FacetConfiguration, PersistentStateComponent<JoocConfigurationBean> {
- private JoocConfigurationBean joocConfigurationBean;
+ private JoocConfigurationBean joocConfigurationBean = new JoocConfigurationBean();
public FacetEditorTab[] createEditorTabs(FacetEditorContext facetEditorContext, FacetValidatorsManager facetValidatorsManager) {
- return new FacetEditorTab[]{ new JangarooFacetEditorTab(getJoocConfigurationBean(facetEditorContext))};
+ return new FacetEditorTab[]{ new JangarooFacetEditorTab(initJoocConfigurationBean(facetEditorContext))};
}
- private synchronized JoocConfigurationBean getJoocConfigurationBean(FacetEditorContext facetEditorContext) {
- if (joocConfigurationBean==null) {
- String outputPrefix = null, moduleName = null;
- if (facetEditorContext!=null) {
- Module module = facetEditorContext.getModule();
- if (module != null) {
- ModuleRootModel rootModel = facetEditorContext.getRootModel();
- if (rootModel != null) {
- VirtualFile[] contentRoots = rootModel.getContentRoots();
- if (contentRoots.length > 0) {
- outputPrefix = contentRoots[0].getPath();
- moduleName = module.getName();
- }
- }
- }
+ private synchronized JoocConfigurationBean initJoocConfigurationBean(@NotNull FacetEditorContext facetEditorContext) {
+ if (joocConfigurationBean.getOutputFileName() == null) {
+ Module module = facetEditorContext.getModule();
+ ModuleRootModel rootModel = facetEditorContext.getRootModel();
+ VirtualFile[] contentRoots = rootModel.getContentRoots();
+ if (contentRoots.length > 0) {
+ joocConfigurationBean.init(contentRoots[0].getPath(), module.getName());
}
- joocConfigurationBean = new JoocConfigurationBean(outputPrefix, moduleName);
}
return joocConfigurationBean;
}
@@ -69,15 +60,11 @@ public void writeExternal(Element element) throws WriteExternalException {
}
public JoocConfigurationBean getState() {
- return getJoocConfigurationBean(null);
+ return joocConfigurationBean;
}
public void loadState(JoocConfigurationBean state) {
- if (joocConfigurationBean==null) {
- joocConfigurationBean = state;
- } else {
- // copy into existing instance, as it may already be used by some JangarooFacetEditorTab:
- XmlSerializerUtil.copyBean(state, joocConfigurationBean);
- }
+ // copy into existing instance, as it may already be used by some JangarooFacetEditorTab:
+ XmlSerializerUtil.copyBean(state, joocConfigurationBean);
}
}
diff --git a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetImporter.java b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetImporter.java
new file mode 100644
index 000000000..b09d5abf7
--- /dev/null
+++ b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooFacetImporter.java
@@ -0,0 +1,243 @@
+package net.jangaroo.ide.idea;
+
+import com.intellij.javaee.facet.JavaeeFacet;
+import com.intellij.javaee.ui.packaging.ExplodedWarArtifactType;
+import com.intellij.javaee.ui.packaging.JavaeeFacetResourcesPackagingElement;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleManager;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.JavadocOrderRootType;
+import com.intellij.openapi.roots.ModifiableRootModel;
+import com.intellij.openapi.roots.ModuleRootManager;
+import com.intellij.openapi.roots.OrderRootType;
+import com.intellij.openapi.roots.libraries.Library;
+import com.intellij.openapi.roots.libraries.LibraryTable;
+import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
+import com.intellij.openapi.vfs.JarFileSystem;
+import com.intellij.packaging.artifacts.*;
+import com.intellij.packaging.elements.CompositePackagingElement;
+import com.intellij.packaging.elements.PackagingElement;
+import com.intellij.packaging.elements.PackagingElementFactory;
+import com.intellij.packaging.elements.PackagingElementResolvingContext;
+import org.jdom.Element;
+import org.jetbrains.idea.maven.embedder.MavenConsole;
+import org.jetbrains.idea.maven.importing.FacetImporter;
+import org.jetbrains.idea.maven.importing.MavenModifiableModelsProvider;
+import org.jetbrains.idea.maven.importing.MavenRootModelAdapter;
+import org.jetbrains.idea.maven.project.*;
+import org.jetbrains.idea.maven.utils.MavenConstants;
+import org.jetbrains.idea.maven.utils.MavenProcessCanceledException;
+import org.jetbrains.idea.maven.utils.MavenProgressIndicator;
+
+import java.util.*;
+import java.io.File;
+
+/**
+ * A Facet-from-Maven Importer for the Jangaroo Facet type.
+ */
+public class JangarooFacetImporter extends FacetImporter<JangarooFacet, JangarooFacetConfiguration, JangarooFacetType> {
+ private static final String JANGAROO_GROUP_ID = "net.jangaroo";
+ private static final String JANGAROO_LIFECYCLE_MAVEN_PLUGIN_ARTIFACT_ID = "jangaroo-lifecycle";
+ private static final String JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID = "jangaroo-maven-plugin";
+ private static final String JANGAROO_PACKAGING_TYPE = "jangaroo";
+ private static final String DEFAULT_JANGAROO_FACET_NAME = "Jangaroo";
+
+ public JangarooFacetImporter() {
+ super(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID, JangarooFacetType.INSTANCE, DEFAULT_JANGAROO_FACET_NAME);
+ }
+
+ public boolean isApplicable(MavenProject mavenProjectModel) {
+ return JANGAROO_PACKAGING_TYPE.equals(mavenProjectModel.getPackaging()) ||
+ mavenProjectModel.findPlugin(JANGAROO_GROUP_ID, JANGAROO_LIFECYCLE_MAVEN_PLUGIN_ARTIFACT_ID) != null ||
+ mavenProjectModel.findPlugin(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID) != null;
+ }
+
+ @Override
+ public boolean isSupportedDependency(MavenArtifact artifact) {
+ return JANGAROO_PACKAGING_TYPE.equals(artifact.getType());
+ }
+
+ @Override
+ protected void setupFacet(JangarooFacet f, MavenProject mavenProject) {
+ //System.out.println("setupFacet called!");
+ }
+
+ private boolean getBooleanConfigurationValue(MavenProject mavenProjectModel, String configName, boolean defaultValue) {
+ String value = mavenProjectModel.findPluginGoalConfigurationValue(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID, "war-compile", configName);
+ if (value == null) {
+ value = mavenProjectModel.findPluginGoalConfigurationValue(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID, "compile", configName);
+ }
+ if (value == null) {
+ value = findConfigValue(mavenProjectModel, configName);
+ }
+ return value != null ? Boolean.valueOf(value) : defaultValue;
+ }
+
+ @Override
+ protected void reimportFacet(MavenModifiableModelsProvider modelsProvider, Module module, MavenRootModelAdapter rootModel, JangarooFacet jangarooFacet, MavenProjectsTree mavenTree, MavenProject mavenProjectModel, MavenProjectChanges changes, Map<MavenProject, String> mavenProjectToModuleName, List<MavenProjectsProcessorTask> postTasks) {
+ //System.out.println("reimportFacet called!");
+ JoocConfigurationBean jooConfig = jangarooFacet.getConfiguration().getState();
+ jooConfig.allowDuplicateLocalVariables = getBooleanConfigurationValue(mavenProjectModel, "allowDuplicateLocalVariables", jooConfig.allowDuplicateLocalVariables);
+ jooConfig.verbose = getBooleanConfigurationValue(mavenProjectModel, "verbose", false);
+ jooConfig.enableAssertions = getBooleanConfigurationValue(mavenProjectModel, "enableAssertions", false);
+ jooConfig.enableGuessingClasses = getBooleanConfigurationValue(mavenProjectModel, "enableGuessingClasses", true);
+ jooConfig.enableGuessingMembers = getBooleanConfigurationValue(mavenProjectModel, "enableGuessingMembers", true);
+ jooConfig.enableGuessingTypeCasts = getBooleanConfigurationValue(mavenProjectModel, "enableGuessingTypeCasts", false);
+ // "debug" (boolean; true), "debuglevel" ("none", "lines", "source"; "source")
+ jooConfig.outputDirectory = "war".equals(mavenProjectModel.getPackaging())
+ ? mavenProjectModel.getBuildDirectory() + File.separator + mavenProjectModel.getMavenModel().getBuild().getFinalName() + File.separator + "scripts" + File.separator + "classes"
+ : mavenProjectModel.getBuildDirectory() + File.separator + "joo" + File.separator + "classes";
+
+ ModifiableRootModel moduleRootModel = ModuleRootManager.getInstance(module).getModifiableModel();
+ for (MavenArtifact mavenArtifact : mavenProjectModel.getDependencies()) {
+ if (JANGAROO_PACKAGING_TYPE.equals(mavenArtifact.getType())) {
+ System.out.println("Found 'jangaroo' dependency: " + mavenArtifact.getFile().getAbsolutePath());
+ postTasks.add(new PatchJangarooLibraryTask(mavenArtifact));
+ }
+ }
+ moduleRootModel.commit();
+ postTasks.add(new AddJangarooCompilerOutputToExplodedWebArtifactsTask(jangarooFacet));
+ }
+
+ public void collectSourceFolders(MavenProject mavenProject, List<String> result) {
+ collectSourceOrTestFolders(mavenProject, "compile", "src/main/joo", result);
+ }
+
+ public void collectTestFolders(MavenProject mavenProject, List<String> result) {
+ collectSourceOrTestFolders(mavenProject, "testCompile", "src/test/joo", result);
+ }
+
+ private void collectSourceOrTestFolders(MavenProject mavenProject, String goal, String defaultDir, List<String> result) {
+ Element sourcesElement = mavenProject.findPluginGoalConfigurationElement(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID, goal, "sources");
+ if (sourcesElement == null) {
+ result.add(defaultDir);
+ return;
+ }
+ for (Object each : sourcesElement.getChildren("fileset")) {
+ String dir = findChildElementValue((Element)each, "directory", null);
+ if (dir != null) {
+ result.add(dir);
+ }
+ }
+ }
+
+ private static class PatchJangarooLibraryTask implements MavenProjectsProcessorTask {
+ private final MavenArtifact artifact;
+
+ public PatchJangarooLibraryTask(MavenArtifact mavenArtifact) {
+ this.artifact = mavenArtifact;
+ }
+
+ public void perform(Project project, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator indicator) throws MavenProcessCanceledException {
+ // add Maven artifact with classifier "-sources" as module library!
+ LibraryTable table = LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(LibraryTablesRegistrar.PROJECT_LEVEL, project);
+ if (table == null) {
+ System.out.println(" Project level libraries could not be retrieved to patch 'jangaroo' dependency " + artifact.getFile().getAbsolutePath());
+ return;
+ }
+ String libName = "Maven: " + artifact.getDisplayStringForLibraryName();
+ final Library library = table.getLibraryByName(libName);
+ if (library == null) {
+ System.out.println(" Project level library '"+libName+"' not found, cannot patch 'jangaroo' dependency " + artifact.getFile().getAbsolutePath());
+ return;
+ }
+ ApplicationManager.getApplication().invokeLater(new Runnable() {
+ public void run() {
+ ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ public void run() {
+ Library.ModifiableModel libraryModel = library.getModifiableModel();
+ // Jangaroo specialty: add a CLASSES root for the SOURCES artifact!
+ String newUrl = artifact.getUrlForClassifier(MavenConstants.SOURCES_CLASSIFIER);
+ for (String url : libraryModel.getUrls(OrderRootType.CLASSES)) {
+ if (newUrl != null && newUrl.equals(url)) {
+ newUrl = null; // do not add again!
+ break;
+ }
+ if (MavenConstants.SCOPE_SYSTEM.equals(artifact.getScope()) || isRepositoryUrl(artifact, url, MavenConstants.SOURCES_CLASSIFIER)) {
+ libraryModel.removeRoot(url, OrderRootType.CLASSES);
+ }
+ }
+ if (newUrl != null) {
+ libraryModel.addRoot(newUrl, OrderRootType.CLASSES);
+ }
+ // Jangaroo specialty: there is no javadoc!
+ OrderRootType javadocOrderRootType = JavadocOrderRootType.getInstance();
+ for (String javadocUrl : libraryModel.getUrls(javadocOrderRootType)) {
+ libraryModel.removeRoot(javadocUrl, javadocOrderRootType);
+ }
+ libraryModel.commit();
+ }
+ });
+ }
+ });
+ }
+
+ private boolean isRepositoryUrl(MavenArtifact artifact, String url, String classifier) {
+ return url.endsWith(artifact.getRelativePathForClassifier(classifier) + JarFileSystem.JAR_SEPARATOR);
+ }
+
+
+ }
+
+ private static class AddJangarooCompilerOutputToExplodedWebArtifactsTask implements MavenProjectsProcessorTask {
+ private final JangarooFacet jangarooFacet;
+
+ private AddJangarooCompilerOutputToExplodedWebArtifactsTask(JangarooFacet jangarooFacet) {
+ this.jangarooFacet = jangarooFacet;
+ }
+
+ public void perform(final Project project, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator indicator) throws MavenProcessCanceledException {
+ ApplicationManager.getApplication().runReadAction(new Runnable() {
+ public void run() {
+ // find all modules in this project that use our Jangaroo module:
+ Set<Module> dependingModules = getDependingModules(jangarooFacet.getModule(), project);
+ // Find all exploded war artifacts that contain the output of a Web facet of a module that has a (transitive)
+ // dependency on our Jangaroo module.
+ // This includes the Jangaroo module itself, if it also has a Web facet!
+ ArtifactManager artifactManager = ArtifactManager.getInstance(project);
+ PackagingElementResolvingContext packagingElementResolvingContext = artifactManager.getResolvingContext();
+ JangarooCompilerOutputElement jangarooCompilerOutput = null;
+ for (Artifact artifact : artifactManager.getArtifactsByType(ExplodedWarArtifactType.getInstance())) {
+ CompositePackagingElement<?> rootElement = artifact.getRootElement();
+ if (hasWebFacetWithDependency(dependingModules, packagingElementResolvingContext, rootElement)) {
+ if (jangarooCompilerOutput == null) {
+ jangarooCompilerOutput = new JangarooCompilerOutputElement(project, jangarooFacet);
+ }
+ PackagingElementFactory.getInstance().getOrCreateDirectory(rootElement, "scripts").addOrFindChild(jangarooCompilerOutput);
+ }
+ }
+ }
+ });
+ }
+
+ private static Set<Module> getDependingModules(Module jooModule, Project project) {
+ Module[] modules = ModuleManager.getInstance(project).getSortedModules();
+ Set<Module> dependingModules = new HashSet<Module>();
+ dependingModules.add(jooModule);
+ for (Module module : modules) {
+ Module[] dependencies = ModuleRootManager.getInstance(module).getDependencies();
+ for (Module dependency : dependencies) {
+ if (dependingModules.contains(dependency)) {
+ dependingModules.add(module);
+ break;
+ }
+ }
+ }
+ return dependingModules;
+ }
+
+ private static boolean hasWebFacetWithDependency(Set<Module> dependingModules, PackagingElementResolvingContext packagingElementResolvingContext, CompositePackagingElement<?> rootElement) {
+ List<PackagingElement<?>> children = rootElement.getChildren();
+ for (PackagingElement<?> packagingElement : children) {
+ if (packagingElement instanceof JavaeeFacetResourcesPackagingElement) {
+ JavaeeFacet facet = ((JavaeeFacetResourcesPackagingElement) packagingElement).findFacet(packagingElementResolvingContext);
+ if (facet != null && dependingModules.contains(facet.getModule())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ }
+}
diff --git a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooMavenImporter.java b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooMavenImporter.java
deleted file mode 100644
index 802385799..000000000
--- a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JangarooMavenImporter.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package net.jangaroo.ide.idea;
-
-import com.intellij.facet.FacetManager;
-import com.intellij.openapi.module.Module;
-import com.intellij.openapi.roots.libraries.Library;
-import com.intellij.openapi.roots.libraries.LibraryTable;
-import com.intellij.openapi.roots.ModifiableRootModel;
-import com.intellij.openapi.roots.OrderRootType;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.LocalFileSystem;
-import org.jetbrains.idea.maven.importing.MavenModifiableModelsProvider;
-import org.jetbrains.idea.maven.importing.MavenRootModelAdapter;
-import org.jetbrains.idea.maven.project.*;
-
-import java.util.Map;
-import java.util.List;
-import java.io.File;
-
-/**
- * A Facet-from-Maven Importer for the Jangaroo Facet type.
- */
-public class JangarooMavenImporter extends org.jetbrains.idea.maven.importing.MavenImporter {
- private static final String JANGAROO_GROUP_ID = "net.jangaroo";
- private static final String JANGAROO_LIFECYCLE_MAVEN_PLUGIN_ARTIFACT_ID = "jangaroo-lifecycle";
- private static final String JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID = "jangaroo-maven-plugin";
- private static final String JANGAROO_PACKAGING_TYPE = "jangaroo";
- private static final String DEFAULT_JANGAROO_FACET_NAME = "Jangaroo";
-
- public JangarooMavenImporter() {
- super();
- }
-
- @Override
- public boolean isApplicable(MavenProject mavenProjectModel) {
- return JANGAROO_PACKAGING_TYPE.equals(mavenProjectModel.getPackaging()) ||
- mavenProjectModel.findPlugin(JANGAROO_GROUP_ID, JANGAROO_LIFECYCLE_MAVEN_PLUGIN_ARTIFACT_ID) != null ||
- mavenProjectModel.findPlugin(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID) != null;
- }
-
- @Override
- public boolean isSupportedDependency(MavenArtifact artifact) {
- return JANGAROO_PACKAGING_TYPE.equals(artifact.getType());
- }
-
- private boolean getBooleanConfigurationValue(MavenProject mavenProject, String configName, boolean defaultValue) {
- String value = findGoalConfigValue(mavenProject, "war-compile", configName);
- if (value == null) {
- value = findGoalConfigValue(mavenProject, "compile", configName);
- }
- if (value == null) {
- value = findConfigValue(mavenProject, configName);
- }
- return value != null ? Boolean.valueOf(value) : defaultValue;
- }
-
- private String findGoalConfigValue(MavenProject mavenProject, String goalName, String configName) {
- return mavenProject.findPluginGoalConfigurationValue(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID, goalName, configName);
- }
-
- private String findConfigValue(MavenProject mavenProject, String configName) {
- return mavenProject.findPluginConfigurationValue(JANGAROO_GROUP_ID, JANGAROO_MAVEN_PLUGIN_ARTIFACT_ID, configName);
- }
-
- private void createModuleLibrary(ModifiableRootModel moduleRootModel, MavenArtifact artifact) {
- // add Maven artifact with classifier "-sources" as module library!
- LibraryTable table = moduleRootModel.getModuleLibraryTable();
- String libName = "Maven: " + artifact.getMavenId();
- Library library = table.getLibraryByName(libName);
- if (library == null) {
- library = table.createLibrary(libName);
- Library.ModifiableModel libraryModel = library.getModifiableModel();
- String jarPath = artifact.getPath();
- int lastDotPos = jarPath.lastIndexOf('.');
- jarPath = jarPath.substring(0, lastDotPos) + "-sources" + jarPath.substring(lastDotPos);
- VirtualFile jarVirtualFile = LocalFileSystem.getInstance().findFileByPath(jarPath);
- if (jarVirtualFile != null) {
- libraryModel.addRoot(jarVirtualFile, OrderRootType.CLASSES);
- libraryModel.commit();
- }
- }
- }
-
- @Override
- public void preProcess(Module module, MavenProject mavenProject, MavenProjectChanges mavenProjectChanges, MavenModifiableModelsProvider mavenModifiableModelsProvider) {
- // TODO: anything to do here?
- }
-
- @Override
- public void process(MavenModifiableModelsProvider mavenModifiableModelsProvider, Module module, MavenRootModelAdapter mavenRootModelAdapter, MavenProjectsTree mavenProjectsTree, MavenProject mavenProject, MavenProjectChanges mavenProjectChanges, Map<MavenProject, String> mavenProjectStringMap, List<MavenProjectsProcessorTask> postProjectConfigurationTasks) {
- FacetManager facetManager = FacetManager.getInstance(module);
- JangarooFacet jangarooFacet = facetManager.getFacetByType(JangarooFacetType.ID);
- if (jangarooFacet == null) {
- jangarooFacet = facetManager.addFacet(JangarooFacetType.INSTANCE, DEFAULT_JANGAROO_FACET_NAME, null);
- }
- JoocConfigurationBean jooConfig = jangarooFacet.getConfiguration().getState();
- jooConfig.allowDuplicateLocalVariables = getBooleanConfigurationValue(mavenProject, "allowDuplicateLocalVariables", jooConfig.allowDuplicateLocalVariables);
- jooConfig.verbose = getBooleanConfigurationValue(mavenProject, "verbose", false);
- jooConfig.enableAssertions = getBooleanConfigurationValue(mavenProject, "enableAssertions", false);
- jooConfig.enableGuessingClasses = getBooleanConfigurationValue(mavenProject, "enableGuessingClasses", true);
- jooConfig.enableGuessingMembers = getBooleanConfigurationValue(mavenProject, "enableGuessingMembers", true);
- jooConfig.enableGuessingTypeCasts = getBooleanConfigurationValue(mavenProject, "enableGuessingTypeCasts", false);
- // "debug" (boolean; true), "debuglevel" ("none", "lines", "source"; "source")
- jooConfig.outputDirectory = "war".equals(mavenProject.getPackaging())
- ? mavenProject.getBuildDirectory() + File.separator + mavenProject.getMavenModel().getBuild().getFinalName() + File.separator + "scripts" + File.separator + "classes"
- : mavenProject.getBuildDirectory() + File.separator + "joo" + File.separator + "classes";
-
-// ModifiableRootModel moduleRootModel = ModuleRootManager.getInstance(module).getModifiableModel();
-// for (MavenArtifact mavenArtifact : mavenProject.getDependencies()) {
-// if (JANGAROO_PACKAGING_TYPE.equals(mavenArtifact.getType())) {
-// System.out.println("Found 'jangaroo' dependency: " + mavenArtifact.getFile().getAbsolutePath());
-// createModuleLibrary(moduleRootModel, mavenArtifact);
-// }
-// }
-// moduleRootModel.commit();
- }
-
- /*
- public void collectSourceFolders(MavenProjectModel mavenProject, List<String> result) {
- collectSourceOrTestFolders(mavenProject, "compile", "src/main/joo", result);
- }
-
- public void collectTestFolders(MavenProjectModel mavenProject, List<String> result) {
- collectSourceOrTestFolders(mavenProject, "testCompile", "src/test/joo", result);
- }
-
- private void collectSourceOrTestFolders(MavenProjectModel mavenProject, String goal, String defaultDir, List<String> result) {
- Element sourcesElement = findGoalConfigNode(mavenProject, goal, "sources");
- if (sourcesElement == null) {
- result.add((new StringBuilder()).append(mavenProject.getDirectory()).append("/").append(defaultDir).toString());
- return;
- }
- for (Object each : sourcesElement.getChildren("fileset")) {
- String dir = findChildElementValue((Element)each, "directory", null);
- if (dir != null) {
- result.add(dir);
- }
- }
- }
-
- public void collectExcludedFolders(MavenProjectModel mavenProject, List<String> result) {
- String stubsDir = findGoalConfigValue(mavenProject, "generateStubs", "outputDirectory");
- String testStubsDir = findGoalConfigValue(mavenProject, "generateTestStubs", "outputDirectory");
- String defaultStubsDir = (new StringBuilder()).append(mavenProject.getGeneratedSourcesDirectory()).append("/joo").toString();
- result.add(stubsDir != null ? stubsDir : defaultStubsDir);
- result.add(testStubsDir != null ? testStubsDir : defaultStubsDir);
- }
- */
-}
diff --git a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JoocConfigurationBean.java b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JoocConfigurationBean.java
index d7f0e0e76..d0fdd5ab4 100644
--- a/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JoocConfigurationBean.java
+++ b/jangaroo-idea-9/idea-plugin/src/main/java/net/jangaroo/ide/idea/JoocConfigurationBean.java
@@ -44,10 +44,9 @@ public class JoocConfigurationBean {
public static final String IDEA_URL_PREFIX = "file://";
public JoocConfigurationBean() {
- this(null, null);
}
- public JoocConfigurationBean(String outputPrefix, String moduleName) {
+ public void init(String outputPrefix, String moduleName) {
if (outputPrefix!=null) {
outputDirectory = outputPrefix + "/" + outputDirectory;
if (moduleName==null) {
|
872fb98aed24bbfc6a15e7d14f1e2da61487e589
|
Mylyn Reviews
|
Changed versions task bridge feature ids and name
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties
index 1f3b6ab9..f6531426 100644
--- a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties
+++ b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties
@@ -8,7 +8,7 @@
# Contributors:
# Tasktop Technologies - initial API and implementation
###############################################################################
-featureName=Mylyn Versions (Incubation)
+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.
diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml
index c3e2ad93..c39a0b02 100644
--- a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml
+++ b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml
@@ -10,7 +10,7 @@
Tasktop Technologies - initial API and implementation
-->
<feature
- id="org.eclipse.mylyn.versions"
+ id="org.eclipse.mylyn.versions.tasks-feature"
label="%featureName"
version="0.7.0.qualifier"
provider-name="%providerName"
diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml b/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml
index e586b3a1..482366db 100644
--- a/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml
+++ b/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml
@@ -8,7 +8,7 @@
<version>0.7.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.mylyn.versions</groupId>
- <artifactId>org.eclipse.mylyn.versions.tasks</artifactId>
+ <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/feature.xml b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml
index cfe53606..ebfac00f 100644
--- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml
+++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml
@@ -10,7 +10,7 @@
Tasktop Technologies - initial API and implementation
-->
<feature
- id="org.eclipse.mylyn.versions.tasks.sdk"
+ id="org.eclipse.mylyn.versions.tasks-sdk"
label="%featureName"
version="0.7.0.qualifier"
provider-name="%providerName"
@@ -29,7 +29,7 @@
</license>
<includes
- id="org.eclipse.mylyn.tasks.versions"
+ id="org.eclipse.mylyn.versions.tasks-feature"
version="0.0.0"/>
<plugin
diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml
index 492a473c..3955be7d 100644
--- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml
+++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml
@@ -8,7 +8,7 @@
<version>0.7.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.mylyn.versions</groupId>
- <artifactId>org.eclipse.mylyn.versions.tasks.sdk</artifactId>
+ <artifactId>org.eclipse.mylyn.versions.tasks-sdk</artifactId>
<version>0.7.0-SNAPSHOT</version>
<packaging>eclipse-feature</packaging>
</project>
|
3a1f3532a00319879013c4b219255da0991c7959
|
kotlin
|
Reporting real source file paths from K2JS- compiler--
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java
index f3b7f649ecf75..163ab77d5a05e 100644
--- a/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java
+++ b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java
@@ -23,6 +23,7 @@
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import jet.Function0;
import org.jetbrains.annotations.NotNull;
@@ -109,12 +110,11 @@ private static void reportCompiledSourcesList(@NotNull PrintingMessageCollector
@Override
public String apply(@Nullable JetFile file) {
assert file != null;
- String packageName = file.getPackageName();
- if (packageName != null && packageName.length() > 0) {
- return packageName + "." + file.getName();
- } else {
- return file.getName();
+ VirtualFile virtualFile = file.getVirtualFile();
+ if (virtualFile != null) {
+ return virtualFile.getPath();
}
+ return file.getName() + "(no virtual file)";
}
});
messageCollector.report(CompilerMessageSeverity.LOGGING, "Compiling source files: " + Joiner.on(", ").join(fileNames),
|
f88e8f45509c6eb7539bc13be8a500162bbb5cf2
|
Vala
|
vapigen: Add support for array_length_cname for fields
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vala/valacodewriter.vala b/vala/valacodewriter.vala
index d56d984c02..98eee7c7de 100644
--- a/vala/valacodewriter.vala
+++ b/vala/valacodewriter.vala
@@ -627,7 +627,8 @@ public class Vala.CodeWriter : CodeVisitor {
bool custom_cname = (f.get_cname () != f.get_default_cname ());
bool custom_ctype = (f.get_ctype () != null);
bool custom_cheaders = (f.parent_symbol is Namespace);
- if (custom_cname || custom_ctype || custom_cheaders || (f.no_array_length && f.field_type is ArrayType)) {
+ bool custom_array_length_cname = (f.get_array_length_cname () != null);
+ if (custom_cname || custom_ctype || custom_cheaders || custom_array_length_cname || (f.no_array_length && f.field_type is ArrayType)) {
write_indent ();
write_string ("[CCode (");
@@ -651,15 +652,23 @@ public class Vala.CodeWriter : CodeVisitor {
write_string ("cheader_filename = \"%s\"".printf (get_cheaders(f)));
}
- if (f.no_array_length && f.field_type is ArrayType) {
- if (custom_cname || custom_ctype || custom_cheaders) {
- write_string (", ");
- }
+ if (f.field_type is ArrayType) {
+ if (f.no_array_length) {
+ if (custom_cname || custom_ctype || custom_cheaders) {
+ write_string (", ");
+ }
- write_string ("array_length = false");
+ write_string ("array_length = false");
+
+ if (f.array_null_terminated) {
+ write_string (", array_null_terminated = true");
+ }
+ } else if (custom_array_length_cname) {
+ if (custom_cname || custom_ctype || custom_cheaders) {
+ write_string (", ");
+ }
- if (f.array_null_terminated) {
- write_string (", array_null_terminated = true");
+ write_string ("array_length_cname = \"%s\"".printf (f.get_array_length_cname ()));
}
}
diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala
index 5664b416d4..e971ac0920 100644
--- a/vapigen/valagidlparser.vala
+++ b/vapigen/valagidlparser.vala
@@ -1973,6 +1973,7 @@ public class Vala.GIdlParser : CodeVisitor {
string cheader_filename = null;
string ctype = null;
+ string array_length_cname = null;
bool array_null_terminated = false;
var attributes = get_attributes ("%s.%s".printf (current_data_type.get_cname (), node.name));
@@ -2010,6 +2011,8 @@ public class Vala.GIdlParser : CodeVisitor {
if (eval (nv[1]) == "1") {
array_null_terminated = true;
}
+ } else if (nv[0] == "array_length_cname") {
+ array_length_cname = eval (nv[1]);
}
}
}
@@ -2043,11 +2046,16 @@ public class Vala.GIdlParser : CodeVisitor {
field.add_cheader_filename (cheader_filename);
}
- field.no_array_length = true;
if (array_null_terminated) {
field.array_null_terminated = true;
}
+ if (array_length_cname != null) {
+ field.set_array_length_cname (array_length_cname);
+ } else {
+ field.no_array_length = true;
+ }
+
return field;
}
|
cfdb09b7cbb5ea1732416da7ce45c78ac4c0849b
|
hadoop
|
YARN-578. Fixed NM to use SecureIOUtils for reading- and aggregating logs. Contributed by Omkar Vinit Joshi. svn merge- --ignore-ancestry -c 1487672 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1487686 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index ba3068ef40db6..5bd00122d74be 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -348,6 +348,9 @@ Release 2.0.5-beta - UNRELEASED
YARN-715. Fixed unit test failures - TestDistributedShell and
TestUnmanagedAMLauncher. (Vinod Kumar Vavilapalli via sseth)
+ YARN-578. Fixed NM to use SecureIOUtils for reading and aggregating logs.
+ (Omkar Vinit Joshi via vinodkv)
+
BREAKDOWN OF HADOOP-8562 SUBTASKS AND RELATED JIRAS
YARN-158. Yarn creating package-info.java must not depend on sh.
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
index c519f1795957e..185020dc4a3ce 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
@@ -25,8 +25,8 @@
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
-import java.io.InputStreamReader;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Writer;
import java.security.PrivilegedExceptionAction;
@@ -50,6 +50,7 @@
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.SecureIOUtils;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.file.tfile.TFile;
import org.apache.hadoop.security.UserGroupInformation;
@@ -137,12 +138,15 @@ public static class LogValue {
private final List<String> rootLogDirs;
private final ContainerId containerId;
+ private final String user;
// TODO Maybe add a version string here. Instead of changing the version of
// the entire k-v format
- public LogValue(List<String> rootLogDirs, ContainerId containerId) {
+ public LogValue(List<String> rootLogDirs, ContainerId containerId,
+ String user) {
this.rootLogDirs = new ArrayList<String>(rootLogDirs);
this.containerId = containerId;
+ this.user = user;
// Ensure logs are processed in lexical order
Collections.sort(this.rootLogDirs);
@@ -177,18 +181,30 @@ public void write(DataOutputStream out) throws IOException {
// Write the log itself
FileInputStream in = null;
try {
- in = new FileInputStream(logFile);
+ in = SecureIOUtils.openForRead(logFile, getUser(), null);
byte[] buf = new byte[65535];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
+ } catch (IOException e) {
+ String message = "Error aggregating log file. Log file : "
+ + logFile.getAbsolutePath() + e.getMessage();
+ LOG.error(message, e);
+ out.write(message.getBytes());
} finally {
- in.close();
+ if (in != null) {
+ in.close();
+ }
}
}
}
}
+
+ // Added for testing purpose.
+ public String getUser() {
+ return user;
+ }
}
public static class LogWriter {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
index de755a721564e..248ec3145bd75 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
@@ -18,13 +18,21 @@
package org.apache.hadoop.yarn.logaggregation;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
import java.io.Writer;
+import java.util.Arrays;
import java.util.Collections;
import junit.framework.Assert;
@@ -32,11 +40,14 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.nativeio.NativeIO;
import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogReader;
@@ -44,6 +55,7 @@
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter;
import org.apache.hadoop.yarn.util.BuilderUtils;
import org.junit.After;
+import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
@@ -97,7 +109,7 @@ public void testReadAcontainerLogs1() throws Exception {
LogKey logKey = new LogKey(testContainerId);
LogValue logValue =
new LogValue(Collections.singletonList(srcFileRoot.toString()),
- testContainerId);
+ testContainerId, ugi.getShortUserName());
logWriter.append(logKey, logValue);
logWriter.closeWriter();
@@ -131,9 +143,115 @@ public void testReadAcontainerLogs1() throws Exception {
Assert.assertEquals(expectedLength, s.length());
}
+ @Test(timeout=10000)
+ public void testContainerLogsFileAccess() throws IOException {
+ // This test will run only if NativeIO is enabled as SecureIOUtils
+ // require it to be enabled.
+ Assume.assumeTrue(NativeIO.isAvailable());
+ Configuration conf = new Configuration();
+ conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
+ "kerberos");
+ UserGroupInformation.setConfiguration(conf);
+ File workDir = new File(testWorkDir, "testContainerLogsFileAccess1");
+ Path remoteAppLogFile =
+ new Path(workDir.getAbsolutePath(), "aggregatedLogFile");
+ Path srcFileRoot = new Path(workDir.getAbsolutePath(), "srcFiles");
+
+ String data = "Log File content for container : ";
+ // Creating files for container1. Log aggregator will try to read log files
+ // with illegal user.
+ ContainerId testContainerId1 = BuilderUtils.newContainerId(1, 1, 1, 1);
+ Path appDir =
+ new Path(srcFileRoot, testContainerId1.getApplicationAttemptId()
+ .getApplicationId().toString());
+ Path srcFilePath1 = new Path(appDir, testContainerId1.toString());
+ String stdout = "stdout";
+ String stderr = "stderr";
+ writeSrcFile(srcFilePath1, stdout, data + testContainerId1.toString()
+ + stdout);
+ writeSrcFile(srcFilePath1, stderr, data + testContainerId1.toString()
+ + stderr);
+
+ UserGroupInformation ugi =
+ UserGroupInformation.getCurrentUser();
+ LogWriter logWriter = new LogWriter(conf, remoteAppLogFile, ugi);
+
+ LogKey logKey = new LogKey(testContainerId1);
+ String randomUser = "randomUser";
+ LogValue logValue =
+ spy(new LogValue(Collections.singletonList(srcFileRoot.toString()),
+ testContainerId1, randomUser));
+
+ // It is trying simulate a situation where first log file is owned by
+ // different user (probably symlink) and second one by the user itself.
+ when(logValue.getUser()).thenReturn(randomUser).thenReturn(
+ ugi.getShortUserName());
+ logWriter.append(logKey, logValue);
+
+ logWriter.closeWriter();
+
+ BufferedReader in =
+ new BufferedReader(new FileReader(new File(remoteAppLogFile
+ .toUri().getRawPath())));
+ String line;
+ StringBuffer sb = new StringBuffer("");
+ while ((line = in.readLine()) != null) {
+ LOG.info(line);
+ sb.append(line);
+ }
+ line = sb.toString();
+
+ String stdoutFile1 =
+ StringUtils.join(
+ Path.SEPARATOR,
+ Arrays.asList(new String[] {
+ srcFileRoot.toUri().toString(),
+ testContainerId1.getApplicationAttemptId().getApplicationId()
+ .toString(), testContainerId1.toString(), stderr }));
+ String message1 =
+ "Owner '" + ugi.getShortUserName() + "' for path " + stdoutFile1
+ + " did not match expected owner '" + randomUser + "'";
+
+ String stdoutFile2 =
+ StringUtils.join(
+ Path.SEPARATOR,
+ Arrays.asList(new String[] {
+ srcFileRoot.toUri().toString(),
+ testContainerId1.getApplicationAttemptId().getApplicationId()
+ .toString(), testContainerId1.toString(), stdout }));
+ String message2 =
+ "Owner '" + ugi.getShortUserName() + "' for path "
+ + stdoutFile2 + " did not match expected owner '"
+ + ugi.getShortUserName() + "'";
+
+ Assert.assertTrue(line.contains(message1));
+ Assert.assertFalse(line.contains(message2));
+ Assert.assertFalse(line.contains(data + testContainerId1.toString()
+ + stderr));
+ Assert.assertTrue(line.contains(data + testContainerId1.toString()
+ + stdout));
+ }
private void writeSrcFile(Path srcFilePath, String fileName, long length)
throws IOException {
+ OutputStreamWriter osw = getOutputStreamWriter(srcFilePath, fileName);
+ int ch = filler;
+ for (int i = 0; i < length; i++) {
+ osw.write(ch);
+ }
+ osw.close();
+ }
+
+ private void writeSrcFile(Path srcFilePath, String fileName, String data)
+ throws IOException {
+ OutputStreamWriter osw = getOutputStreamWriter(srcFilePath, fileName);
+ osw.write(data);
+ osw.close();
+ }
+
+ private OutputStreamWriter getOutputStreamWriter(Path srcFilePath,
+ String fileName) throws IOException, FileNotFoundException,
+ UnsupportedEncodingException {
File dir = new File(srcFilePath.toString());
if (!dir.exists()) {
if (!dir.mkdirs()) {
@@ -143,10 +261,6 @@ private void writeSrcFile(Path srcFilePath, String fileName, long length)
File outputFile = new File(new File(srcFilePath.toString()), fileName);
FileOutputStream os = new FileOutputStream(outputFile);
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF8");
- int ch = filler;
- for (int i = 0; i < length; i++) {
- osw.write(ch);
- }
- osw.close();
+ return osw;
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/resources/krb5.conf b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/resources/krb5.conf
new file mode 100644
index 0000000000000..121ac6d9b981a
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/resources/krb5.conf
@@ -0,0 +1,28 @@
+#
+# 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.
+#
+[libdefaults]
+ default_realm = APACHE.ORG
+ udp_preference_limit = 1
+ extra_addresses = 127.0.0.1
+[realms]
+ APACHE.ORG = {
+ admin_server = localhost:88
+ kdc = localhost:88
+ }
+[domain_realm]
+ localhost = APACHE.ORG
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
index f9a0558563df4..6ef794442c3e1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
@@ -123,7 +123,9 @@ private void uploadLogsForContainer(ContainerId containerId) {
+ ". Current good log dirs are "
+ StringUtils.join(",", dirsHandler.getLogDirs()));
LogKey logKey = new LogKey(containerId);
- LogValue logValue = new LogValue(dirsHandler.getLogDirs(), containerId);
+ LogValue logValue =
+ new LogValue(dirsHandler.getLogDirs(), containerId,
+ userUgi.getShortUserName());
try {
this.writer.append(logKey, logValue);
} catch (IOException e) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java
index 5fdd9577d0fb0..452a8237cb85e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java
@@ -39,8 +39,8 @@
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.SecureIOUtils;
import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
@@ -52,8 +52,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.ConverterUtils;
-import org.apache.hadoop.yarn.webapp.YarnWebParams;
import org.apache.hadoop.yarn.webapp.SubView;
+import org.apache.hadoop.yarn.webapp.YarnWebParams;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.PRE;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock;
@@ -228,6 +228,27 @@ private void printLogs(Block html, ContainerId containerId,
return;
} else {
FileInputStream logByteStream = null;
+
+ try {
+ logByteStream =
+ SecureIOUtils.openForRead(logFile, application.getUser(), null);
+ } catch (IOException e) {
+ LOG.error(
+ "Exception reading log file " + logFile.getAbsolutePath(), e);
+ if (e.getMessage().contains(
+ "did not match expected owner '" + application.getUser()
+ + "'")) {
+ html.h1("Exception reading log file. Application submitted by '"
+ + application.getUser()
+ + "' doesn't own requested log file : "
+ + logFile.getName());
+ } else {
+ html.h1("Exception reading log file. It might be because log "
+ + "file was aggregated : " + logFile.getName());
+ }
+ return;
+ }
+
try {
long toRead = end - start;
if (toRead < logFile.length()) {
@@ -236,11 +257,8 @@ private void printLogs(Block html, ContainerId containerId,
logFile.getName(), "?start=0"), "here").
_(" for full log")._();
}
- // TODO: Use secure IO Utils to avoid symlink attacks.
// TODO Fix findBugs close warning along with IOUtils change
- logByteStream = new FileInputStream(logFile);
IOUtils.skipFully(logByteStream, start);
-
InputStreamReader reader = new InputStreamReader(logByteStream);
int bufferSize = 65536;
char[] cbuf = new char[bufferSize];
@@ -260,8 +278,10 @@ private void printLogs(Block html, ContainerId containerId,
reader.close();
} catch (IOException e) {
- html.h1("Exception reading log-file. Log file was likely aggregated. "
- + StringUtils.stringifyException(e));
+ LOG.error(
+ "Exception reading log file " + logFile.getAbsolutePath(), e);
+ html.h1("Exception reading log file. It might be because log "
+ + "file was aggregated : " + logFile.getName());
} finally {
if (logByteStream != null) {
try {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java
index 43a5401ab4256..3fa594a889552 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation;
+import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
@@ -126,6 +127,7 @@ public void tearDown() throws IOException, InterruptedException {
@SuppressWarnings("unchecked")
public void testLocalFileDeletionAfterUpload() throws Exception {
this.delSrvc = new DeletionService(createContainerExecutor());
+ delSrvc = spy(delSrvc);
this.delSrvc.init(conf);
this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath());
this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
@@ -169,7 +171,8 @@ public void testLocalFileDeletionAfterUpload() throws Exception {
// ensure filesystems were closed
verify(logAggregationService).closeFileSystems(
any(UserGroupInformation.class));
-
+ verify(delSrvc).delete(eq(user), eq((Path) null),
+ eq(new Path(app1LogDir.getAbsolutePath())));
delSrvc.stop();
String containerIdStr = ConverterUtils.toString(container11);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
index 459493959ade7..76be0a2342303 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
@@ -18,27 +18,48 @@
package org.apache.hadoop.yarn.server.nodemanager.webapp;
+import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.verify;
+import java.io.BufferedOutputStream;
import java.io.File;
+import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.io.nativeio.NativeIO;
+import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
+import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.webapp.ContainerLogsPage.ContainersLogsBlock;
+import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.BuilderUtils;
+import org.apache.hadoop.yarn.webapp.YarnWebParams;
+import org.apache.hadoop.yarn.webapp.test.WebAppTests;
import org.junit.Assert;
import org.junit.Test;
+import com.google.inject.Injector;
+import com.google.inject.Module;
+
public class TestContainerLogsPage {
@Test(timeout=30000)
@@ -69,4 +90,99 @@ public void testContainerLogDirs() throws IOException {
container1, dirsHandler);
Assert.assertTrue(!(files.get(0).toString().contains("file:")));
}
+
+ @Test(timeout = 10000)
+ public void testContainerLogPageAccess() throws IOException {
+ // SecureIOUtils require Native IO to be enabled. This test will run
+ // only if it is enabled.
+ assumeTrue(NativeIO.isAvailable());
+ String user = "randomUser" + System.currentTimeMillis();
+ File absLogDir = null, appDir = null, containerDir = null, syslog = null;
+ try {
+ // target log directory
+ absLogDir =
+ new File("target", TestContainerLogsPage.class.getSimpleName()
+ + "LogDir").getAbsoluteFile();
+ absLogDir.mkdir();
+
+ Configuration conf = new Configuration();
+ conf.set(YarnConfiguration.NM_LOG_DIRS, absLogDir.toURI().toString());
+ conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
+ "kerberos");
+ UserGroupInformation.setConfiguration(conf);
+
+ NodeHealthCheckerService healthChecker = new NodeHealthCheckerService();
+ healthChecker.init(conf);
+ LocalDirsHandlerService dirsHandler = healthChecker.getDiskHandler();
+ // Add an application and the corresponding containers
+ RecordFactory recordFactory =
+ RecordFactoryProvider.getRecordFactory(conf);
+ long clusterTimeStamp = 1234;
+ ApplicationId appId =
+ BuilderUtils.newApplicationId(recordFactory, clusterTimeStamp, 1);
+ Application app = mock(Application.class);
+ when(app.getAppId()).thenReturn(appId);
+
+ // Making sure that application returns a random user. This is required
+ // for SecureIOUtils' file owner check.
+ when(app.getUser()).thenReturn(user);
+
+ ApplicationAttemptId appAttemptId =
+ BuilderUtils.newApplicationAttemptId(appId, 1);
+ ContainerId container1 =
+ BuilderUtils.newContainerId(recordFactory, appId, appAttemptId, 0);
+
+ // Testing secure read access for log files
+
+ // Creating application and container directory and syslog file.
+ appDir = new File(absLogDir, appId.toString());
+ appDir.mkdir();
+ containerDir = new File(appDir, container1.toString());
+ containerDir.mkdir();
+ syslog = new File(containerDir, "syslog");
+ syslog.createNewFile();
+ BufferedOutputStream out =
+ new BufferedOutputStream(new FileOutputStream(syslog));
+ out.write("Log file Content".getBytes());
+ out.close();
+
+ ApplicationACLsManager aclsManager = mock(ApplicationACLsManager.class);
+
+ Context context = mock(Context.class);
+ ConcurrentMap<ApplicationId, Application> appMap =
+ new ConcurrentHashMap<ApplicationId, Application>();
+ appMap.put(appId, app);
+ when(context.getApplications()).thenReturn(appMap);
+ when(context.getContainers()).thenReturn(
+ new ConcurrentHashMap<ContainerId, Container>());
+
+ ContainersLogsBlock cLogsBlock =
+ new ContainersLogsBlock(conf, context, aclsManager, dirsHandler);
+
+ Map<String, String> params = new HashMap<String, String>();
+ params.put(YarnWebParams.CONTAINER_ID, container1.toString());
+ params.put(YarnWebParams.CONTAINER_LOG_TYPE, "syslog");
+
+ Injector injector =
+ WebAppTests.testPage(ContainerLogsPage.class,
+ ContainersLogsBlock.class, cLogsBlock, params, (Module[])null);
+ PrintWriter spyPw = WebAppTests.getPrintWriter(injector);
+ verify(spyPw).write(
+ "Exception reading log file. Application submitted by '" + user
+ + "' doesn't own requested log file : syslog");
+ } finally {
+ if (syslog != null) {
+ syslog.delete();
+ }
+ if (containerDir != null) {
+ containerDir.delete();
+ }
+ if (appDir != null) {
+ appDir.delete();
+ }
+ if (absLogDir != null) {
+ absLogDir.delete();
+ }
+ }
+ }
}
|
8c8ed120a0468c9fcb83930672bd04999bf5b45b
|
chrisvest$stormpot
|
DeallocationRules
The DeallocationRule functionality has been implemented. The docs are still way behind it,
though, and need a lot of work now.
|
p
|
https://github.com/chrisvest/stormpot
|
diff --git a/src/main/java/stormpot/Config.java b/src/main/java/stormpot/Config.java
index cead326d..a8c09373 100644
--- a/src/main/java/stormpot/Config.java
+++ b/src/main/java/stormpot/Config.java
@@ -51,8 +51,6 @@
public class Config<T extends Poolable> {
private int size = 10;
- private long ttl = 600; // 10 minutes
- private TimeUnit ttlUnit = TimeUnit.SECONDS;
private DeallocationRule deallocRule =
new TimeBasedDeallocationRule(600, TimeUnit.SECONDS);
private Allocator<?> allocator;
@@ -113,29 +111,29 @@ public synchronized int getSize() {
* @param unit The unit of the 'ttl' value. Cannot be <code>null</code>.
* @return This Config instance.
*/
- public synchronized Config<T> setTTL(long ttl, TimeUnit unit) {
- this.ttl = ttl;
- this.ttlUnit = unit;
- return this;
- }
+// public synchronized Config<T> setTTL(long ttl, TimeUnit unit) {
+// this.ttl = ttl;
+// this.ttlUnit = unit;
+// return this;
+// }
/**
* Get the scalar value of the time-to-live value that applies to the objects
* in the pools we want to configure. Default TTL is 10 minutes.
* @return The scalar time-to-live.
*/
- public synchronized long getTTL() {
- return ttl;
- }
+// public synchronized long getTTL() {
+// return ttl;
+// }
/**
* Get the time-scale unit of the configured time-to-live that applies to the
* objects in the pools we want to configure. Default TTL is 10 minutes.
* @return The time-scale unit of the configured time-to-live value.
*/
- public synchronized TimeUnit getTTLUnit() {
- return ttlUnit;
- }
+// public synchronized TimeUnit getTTLUnit() {
+// return ttlUnit;
+// }
/**
* Set the {@link Allocator} to use for the pools we want to configure.
diff --git a/src/main/java/stormpot/qpool/QAllocThread.java b/src/main/java/stormpot/qpool/QAllocThread.java
index 6a4a1414..bed86f2b 100644
--- a/src/main/java/stormpot/qpool/QAllocThread.java
+++ b/src/main/java/stormpot/qpool/QAllocThread.java
@@ -68,7 +68,7 @@ private void continuouslyReplenishPool() {
QSlot<T> slot = dead.poll(deadPollTimeout, TimeUnit.MILLISECONDS);
if (size > targetSize) {
slot = slot == null? live.poll() : slot;
- dealloc(slot);
+ dealloc(slot); // TODO live.poll() might return null
} else if (slot != null) {
dealloc(slot);
alloc(slot);
diff --git a/src/main/java/stormpot/qpool/QueuePool.java b/src/main/java/stormpot/qpool/QueuePool.java
index 26c9b30a..6daae7ac 100644
--- a/src/main/java/stormpot/qpool/QueuePool.java
+++ b/src/main/java/stormpot/qpool/QueuePool.java
@@ -20,6 +20,7 @@
import stormpot.Completion;
import stormpot.Config;
+import stormpot.DeallocationRule;
import stormpot.LifecycledPool;
import stormpot.PoolException;
import stormpot.Poolable;
@@ -44,7 +45,7 @@ public final class QueuePool<T extends Poolable>
private final BlockingQueue<QSlot<T>> live;
private final BlockingQueue<QSlot<T>> dead;
private final QAllocThread<T> allocThread;
- private final long maxAge;
+ private final DeallocationRule deallocRule;
private volatile boolean shutdown = false;
/**
@@ -57,7 +58,7 @@ public QueuePool(Config<T> config) {
synchronized (config) {
config.validate();
allocThread = new QAllocThread<T>(live, dead, config);
- maxAge = config.getTTLUnit().toMillis(config.getTTL());
+ deallocRule = config.getDeallocationRule();
}
allocThread.start();
}
@@ -79,7 +80,7 @@ private void checkForPoison(QSlot<T> slot) {
}
private boolean isInvalid(QSlot<T> slot) {
- if (slot.getAgeMillis() > maxAge) {
+ if (deallocRule.isInvalid(slot)) {
// it's invalid - into the dead queue with it and continue looping
dead.offer(slot);
return true;
diff --git a/src/test/java/stormpot/PoolTest.java b/src/test/java/stormpot/PoolTest.java
index 03b4da01..3544b8e1 100644
--- a/src/test/java/stormpot/PoolTest.java
+++ b/src/test/java/stormpot/PoolTest.java
@@ -73,6 +73,10 @@
*/
@RunWith(Theories.class)
public class PoolTest {
+ private static final DeallocationRule oneMsTTL =
+ new TimeBasedDeallocationRule(1, TimeUnit.MILLISECONDS);
+ private static final DeallocationRule fiveMsTTL =
+ new TimeBasedDeallocationRule(5, TimeUnit.MILLISECONDS);
private static final Timeout longTimeout = new Timeout(1, TimeUnit.SECONDS);
private static final Timeout mediumTimeout = new Timeout(10, TimeUnit.MILLISECONDS);
private static final Timeout shortTimeout = new Timeout(1, TimeUnit.MILLISECONDS);
@@ -247,7 +251,6 @@ public class PoolTest {
fixture.initPool(config.setAllocator(null));
}
- @Ignore
@Test(timeout = 300)
@Theory public void
mustUseProvidedDeallocationRule(PoolFixture fixture) throws Exception {
@@ -257,8 +260,6 @@ public class PoolTest {
pool.claim(longTimeout).release();
assertThat(rule.getCount(), is(1));
}
- // TODO must use provided deallocation rule
- // TODO [delete the ttl & unit code in config]
// TODO [re-write bunch of Javadoc]
/**
@@ -301,7 +302,7 @@ public class PoolTest {
@Theory public void
mustReplaceExpiredPoolables(PoolFixture fixture) throws Exception {
Pool<GenericPoolable> pool = fixture.initPool(
- config.setTTL(1, TimeUnit.MILLISECONDS));
+ config.setDeallocationRule(oneMsTTL));
pool.claim(longTimeout).release();
spinwait(2);
pool.claim(longTimeout).release();
@@ -331,7 +332,7 @@ public class PoolTest {
mustDeallocateExpiredPoolablesAndStayWithinSizeLimit(PoolFixture fixture)
throws Exception {
Pool<GenericPoolable> pool = fixture.initPool(
- config.setTTL(1, TimeUnit.MILLISECONDS));
+ config.setDeallocationRule(oneMsTTL));
pool.claim(longTimeout).release();
spinwait(2);
pool.claim(longTimeout).release();
@@ -560,7 +561,7 @@ public class PoolTest {
mustNotDeallocateTheSameObjectMoreThanOnce(PoolFixture fixture)
throws Exception {
Pool<GenericPoolable> pool = fixture.initPool(
- config.setTTL(1, TimeUnit.MILLISECONDS));
+ config.setDeallocationRule(oneMsTTL));
Poolable obj = pool.claim(longTimeout);
spinwait(2);
obj.release();
@@ -607,7 +608,7 @@ public void deallocate(GenericPoolable poolable) {
}
};
Pool<GenericPoolable> pool = fixture.initPool(
- config.setAllocator(allocator).setTTL(1, TimeUnit.MILLISECONDS));
+ config.setAllocator(allocator).setDeallocationRule(oneMsTTL));
pool.claim(longTimeout).release();
shutdown(pool).await(longTimeout);
assertFalse(wasNull.get());
@@ -709,7 +710,7 @@ public void deallocate(GenericPoolable poolable) {
};
config.setAllocator(allocator);
Pool<GenericPoolable> pool = fixture.initPool(
- config.setTTL(1, TimeUnit.MILLISECONDS));
+ config.setDeallocationRule(oneMsTTL));
pool.claim(longTimeout).release();
spinwait(2);
pool.claim(longTimeout).release();
@@ -1007,7 +1008,7 @@ public GenericPoolable allocate(Slot slot) throws Exception {
}
};
config.setAllocator(allocator);
- config.setTTL(5, TimeUnit.MILLISECONDS);
+ config.setDeallocationRule(fiveMsTTL);
config.setSize(objs.length);
Pool<GenericPoolable> pool = fixture.initPool(config);
for (int i = 0; i < objs.length; i++) {
diff --git a/src/test/java/stormpot/ResizablePoolTest.java b/src/test/java/stormpot/ResizablePoolTest.java
index 096ca84d..48a8c0a5 100644
--- a/src/test/java/stormpot/ResizablePoolTest.java
+++ b/src/test/java/stormpot/ResizablePoolTest.java
@@ -155,7 +155,8 @@ private ResizablePool<GenericPoolable> resizable(PoolFixture fixture) {
int startingSize = 5;
int newSize = 1;
CountingAllocator allocator = new CountingAllocator();
- config.setTTL(1, TimeUnit.MILLISECONDS).setAllocator(allocator);
+ DeallocationRule rule = new TimeBasedDeallocationRule(1, TimeUnit.MILLISECONDS);
+ config.setDeallocationRule(rule).setAllocator(allocator);
config.setSize(startingSize);
ResizablePool<GenericPoolable> pool = resizable(fixture);
List<GenericPoolable> objs = new ArrayList<GenericPoolable>();
diff --git a/src/test/java/stormpot/basicpool/BasicPool.java b/src/test/java/stormpot/basicpool/BasicPool.java
index de3342c8..6f63c977 100644
--- a/src/test/java/stormpot/basicpool/BasicPool.java
+++ b/src/test/java/stormpot/basicpool/BasicPool.java
@@ -28,6 +28,7 @@
import stormpot.Allocator;
import stormpot.Completion;
import stormpot.Config;
+import stormpot.DeallocationRule;
import stormpot.LifecycledPool;
import stormpot.PoolException;
import stormpot.Poolable;
@@ -55,7 +56,7 @@ public class BasicPool<T extends Poolable>
private final List<BasicSlot<T>> slots;
private final Lock lock;
private final Condition released;
- private final long ttlMillis;
+ private final DeallocationRule deallocRule;
private boolean shutdown;
private int targetSize;
@@ -68,8 +69,8 @@ public BasicPool(Config<T> config) {
this.pool = new ArrayList<T>();
this.slots = new ArrayList<BasicSlot<T>>();
setTargetSize(config.getSize());
- this.ttlMillis = config.getTTLUnit().toMillis(config.getTTL());
this.allocator = config.getAllocator();
+ this.deallocRule = config.getDeallocationRule();
}
}
@@ -216,7 +217,8 @@ private BasicSlot(int index, BasicPool<T> bpool) {
}
public boolean expired() {
- if (getAgeMillis() > bpool.ttlMillis || index >= bpool.targetSize) {
+// if (getAgeMillis() > bpool.ttlMillis || index >= bpool.targetSize) {
+ if (bpool.deallocRule.isInvalid(this) || index >= bpool.targetSize) {
try {
bpool.allocator.deallocate(bpool.pool.get(index));
} catch (Exception _) {
diff --git a/src/test/java/stormpot/benchmark/PoolSpin.java b/src/test/java/stormpot/benchmark/PoolSpin.java
index 469bf025..4fb0747f 100644
--- a/src/test/java/stormpot/benchmark/PoolSpin.java
+++ b/src/test/java/stormpot/benchmark/PoolSpin.java
@@ -23,11 +23,13 @@
import stormpot.Allocator;
import stormpot.Config;
+import stormpot.DeallocationRule;
import stormpot.GenericPoolable;
import stormpot.LifecycledPool;
import stormpot.Pool;
import stormpot.Poolable;
import stormpot.Slot;
+import stormpot.TimeBasedDeallocationRule;
import stormpot.Timeout;
import stormpot.basicpool.BasicPoolFixture;
import stormpot.qpool.QPoolFixture;
@@ -75,7 +77,9 @@ protected void setUp() throws Exception {
Config<GenericPoolable> config = new Config<GenericPoolable>();
config.setAllocator(new SlowAllocator(work));
config.setSize(size);
- config.setTTL(ttl, TimeUnit.MILLISECONDS);
+ DeallocationRule rule =
+ new TimeBasedDeallocationRule(ttl, TimeUnit.MILLISECONDS);
+ config.setDeallocationRule(rule);
pool = (poolType == 0? new BasicPoolFixture() : new QPoolFixture()).initPool(config);
// Give the pool 500 ms to boot up any threads it might need
LockSupport.parkNanos(500000000);
|
e9dee4fc76caaca231bf10728d4f82bc46581bc5
|
intellij-community
|
fixed PY-2674 Assignment can be replaced with- augmented assignmet breaks context--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/python/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java b/python/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java
index 5a7383a1d72e8..24c3143a1ba4c 100644
--- a/python/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java
+++ b/python/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java
@@ -45,7 +45,7 @@ public void visitPyAssignmentStatement(final PyAssignmentStatement node) {
PyExpression rightExpression = expression.getRightExpression();
if (rightExpression != null) {
boolean changedParts = false;
- if (rightExpression.getText().equals(target.getText())) {
+ if (rightExpression.getText().equals(target.getText()) && leftExpression instanceof PyNumericLiteralExpression) {
PyExpression tmp = rightExpression;
rightExpression = leftExpression;
leftExpression = tmp;
|
0f8ab8e6e1bdac17585abf685efda33d71cbbff1
|
restlet-framework-java
|
- The ServletContextAdapter passed by the- ServerServlet to the Restlet's Application was not given to the- constructor but via the setContext() method. Reported by Tammy Croteau.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java b/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java
index ef4b264e0f..15ed3500f7 100644
--- a/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java
+++ b/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java
@@ -162,7 +162,9 @@ public Application createApplication(Context context) {
// Create a new instance of the application class by
// invoking the constructor with the Context parameter.
application = (Application) targetClass.getConstructor(
- Context.class).newInstance(context);
+ Context.class).newInstance(
+ new ServletContextAdapter(this, application,
+ context));
} catch (NoSuchMethodException e) {
log(
"[Noelios Restlet Engine] - The ServerServlet couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of Context. The empty constructor and the context setter wille used instead. "
@@ -172,6 +174,10 @@ public Application createApplication(Context context) {
// constructor then invoke the setContext method.
application = (Application) targetClass.getConstructor()
.newInstance();
+
+ // Set the context based on the Servlet's context
+ application.setContext(new ServletContextAdapter(this,
+ application, context));
}
} catch (ClassNotFoundException e) {
log(
@@ -195,12 +201,6 @@ public Application createApplication(Context context) {
"[Noelios Restlet Engine] - The ServerServlet couldn't instantiate the target class. An exception was thrown while creating "
+ applicationClassName, e);
}
-
- if (application != null) {
- // Set the context based on the Servlet's context
- application.setContext(new ServletContextAdapter(this,
- application, context));
- }
}
return application;
|
02c7a414e00dc8e79c4cb9ad6c0c436df26c8dd5
|
Vala
|
codegen: Simplify field initialization for struct types
Fixes bug 703996
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala
index 9f399571c4..dae33347f2 100644
--- a/codegen/valaccodebasemodule.vala
+++ b/codegen/valaccodebasemodule.vala
@@ -1101,36 +1101,39 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator {
f.initializer.emit (this);
var rhs = get_cvalue (f.initializer);
-
- ccode.add_assignment (lhs, rhs);
-
- if (f.variable_type is ArrayType && get_ccode_array_length (f)) {
- var array_type = (ArrayType) f.variable_type;
- var field_value = get_field_cvalue (f, load_this_parameter ((TypeSymbol) f.parent_symbol));
-
- var glib_value = (GLibValue) f.initializer.target_value;
- if (glib_value.array_length_cvalues != null) {
- for (int dim = 1; dim <= array_type.rank; dim++) {
- var array_len_lhs = get_array_length_cvalue (field_value, dim);
- ccode.add_assignment (array_len_lhs, get_array_length_cvalue (glib_value, dim));
+ if (!is_simple_struct_creation (f, f.initializer)) {
+ // otherwise handled in visit_object_creation_expression
+
+ ccode.add_assignment (lhs, rhs);
+
+ if (f.variable_type is ArrayType && get_ccode_array_length (f)) {
+ var array_type = (ArrayType) f.variable_type;
+ var field_value = get_field_cvalue (f, load_this_parameter ((TypeSymbol) f.parent_symbol));
+
+ var glib_value = (GLibValue) f.initializer.target_value;
+ if (glib_value.array_length_cvalues != null) {
+ for (int dim = 1; dim <= array_type.rank; dim++) {
+ var array_len_lhs = get_array_length_cvalue (field_value, dim);
+ ccode.add_assignment (array_len_lhs, get_array_length_cvalue (glib_value, dim));
+ }
+ } else if (glib_value.array_null_terminated) {
+ requires_array_length = true;
+ var len_call = new CCodeFunctionCall (new CCodeIdentifier ("_vala_array_length"));
+ len_call.add_argument (get_cvalue_ (glib_value));
+
+ ccode.add_assignment (get_array_length_cvalue (field_value, 1), len_call);
+ } else {
+ for (int dim = 1; dim <= array_type.rank; dim++) {
+ ccode.add_assignment (get_array_length_cvalue (field_value, dim), new CCodeConstant ("-1"));
+ }
}
- } else if (glib_value.array_null_terminated) {
- requires_array_length = true;
- var len_call = new CCodeFunctionCall (new CCodeIdentifier ("_vala_array_length"));
- len_call.add_argument (get_cvalue_ (glib_value));
-
- ccode.add_assignment (get_array_length_cvalue (field_value, 1), len_call);
- } else {
- for (int dim = 1; dim <= array_type.rank; dim++) {
- ccode.add_assignment (get_array_length_cvalue (field_value, dim), new CCodeConstant ("-1"));
+
+ if (array_type.rank == 1 && f.is_internal_symbol ()) {
+ var lhs_array_size = get_array_size_cvalue (field_value);
+ var rhs_array_len = get_array_length_cvalue (field_value, 1);
+ ccode.add_assignment (lhs_array_size, rhs_array_len);
}
}
-
- if (array_type.rank == 1 && f.is_internal_symbol ()) {
- var lhs_array_size = get_array_size_cvalue (field_value);
- var rhs_array_len = get_array_length_cvalue (field_value, 1);
- ccode.add_assignment (lhs_array_size, rhs_array_len);
- }
}
foreach (var value in temp_ref_values) {
@@ -4447,9 +4450,14 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator {
// value-type initialization or object creation expression with object initializer
var local = expr.parent_node as LocalVariable;
+ var field = expr.parent_node as Field;
var a = expr.parent_node as Assignment;
if (local != null && is_simple_struct_creation (local, local.initializer)) {
instance = get_cvalue_ (get_local_cvalue (local));
+ } else if (field != null && is_simple_struct_creation (field, field.initializer)) {
+ // field initialization
+ var thisparam = load_this_parameter ((TypeSymbol) field.parent_symbol);
+ instance = get_cvalue_ (get_field_cvalue (field, thisparam));
} else if (a != null && a.left.symbol_reference is Variable && is_simple_struct_creation ((Variable) a.left.symbol_reference, a.right)) {
if (requires_destroy (a.left.value_type)) {
/* unref old value */
@@ -4457,7 +4465,7 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator {
}
local = a.left.symbol_reference as LocalVariable;
- var field = a.left.symbol_reference as Field;
+ field = a.left.symbol_reference as Field;
var param = a.left.symbol_reference as Parameter;
if (local != null) {
instance = get_cvalue_ (get_local_cvalue (local));
diff --git a/vapi/gobject-2.0.vapi b/vapi/gobject-2.0.vapi
index b0c02299bc..3de08df3a8 100644
--- a/vapi/gobject-2.0.vapi
+++ b/vapi/gobject-2.0.vapi
@@ -385,7 +385,7 @@ namespace GLib {
public unowned GLib.Binding bind_property (string source_property, GLib.Object target, string target_property, GLib.BindingFlags flags = GLib.BindingFlags.DEFAULT, [CCode (type = "GClosure*")] owned GLib.BindingTransformFunc? transform_to = null, [CCode (type = "GClosure*")] owned GLib.BindingTransformFunc? transform_from = null);
}
- [CCode (destroy_function = "g_weak_ref_clear")]
+ [CCode (destroy_function = "g_weak_ref_clear", lvalue_access = false)]
public struct WeakRef {
public WeakRef (GLib.Object? object);
public GLib.Object? get ();
|
44d92d8eb39b176c23209f26a69bb1febae8e812
|
kotlin
|
Support for checking loaded descriptors agains an- expected txt file--
|
a
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInAbstractClass.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInAbstractClass.txt
new file mode 100644
index 0000000000000..6a33d58b255ad
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInAbstractClass.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal abstract class abstract.MyAbstractClass : jet.Any {
+ public final /*constructor*/ fun <init>(): abstract.MyAbstractClass
+ internal final val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal final val a: jet.Int
+ internal final var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal final var b: jet.Int private set
+ internal final var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal final var c: jet.Int
+ internal final val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal final val e: jet.Int
+ internal final fun f(): jet.Tuple0
+ internal final fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal final var i1: jet.Int
+ internal final var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal final var j1: jet.Int
+ internal final var j: jet.Int
+ internal final var k1: jet.Int
+ internal final var k: jet.Int
+ internal final var l1: jet.Int
+ internal final var l: jet.Int
+ internal final var n: jet.Int
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInClass.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInClass.txt
new file mode 100644
index 0000000000000..a80adecf038ff
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInClass.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal final class abstract.MyClass : jet.Any {
+ public final /*constructor*/ fun <init>(): abstract.MyClass
+ internal final val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal final val a: jet.Int
+ internal final var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal final var b: jet.Int private set
+ internal final var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal final var c: jet.Int
+ internal final val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal final val e: jet.Int
+ internal final fun f(): jet.Tuple0
+ internal final fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal final var i1: jet.Int
+ internal final var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal final var j1: jet.Int
+ internal final var j: jet.Int
+ internal final var k1: jet.Int
+ internal final var k: jet.Int
+ internal final var l1: jet.Int
+ internal final var l: jet.Int
+ internal final var n: jet.Int
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInEnum.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInEnum.txt
new file mode 100644
index 0000000000000..bfb4e84b3dee2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInEnum.txt
@@ -0,0 +1,41 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal final enum class abstract.MyEnum : jet.Any {
+ public final /*constructor*/ fun <init>(): abstract.MyEnum
+ internal final val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal final val a: jet.Int
+ internal final var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal final var b: jet.Int private set
+ internal final var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal final var c: jet.Int
+ internal final val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal final val e: jet.Int
+ internal final fun f(): jet.Tuple0
+ internal final fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal final var i1: jet.Int
+ internal final var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal final var j1: jet.Int
+ internal final var j: jet.Int
+ internal final var k1: jet.Int
+ internal final var k: jet.Int
+ internal final var l1: jet.Int
+ internal final var l: jet.Int
+ internal final var n: jet.Int
+ internal final object abstract.MyEnum.<class-object-for-MyEnum> {
+ internal final /*constructor*/ fun <init>(): abstract.MyEnum.<class-object-for-MyEnum>
+ }
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInTrait.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInTrait.txt
new file mode 100644
index 0000000000000..29cd19e059ff0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInTrait.txt
@@ -0,0 +1,37 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal abstract trait abstract.MyTrait : jet.Any {
+ internal open val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal abstract val a: jet.Int
+ internal open var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal abstract var b: jet.Int private set
+ internal open var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal open var c: jet.Int
+ internal open val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal open val e: jet.Int
+ internal abstract fun f(): jet.Tuple0
+ internal open fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal open var i1: jet.Int
+ internal abstract var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal open var j1: jet.Int
+ internal open var j: jet.Int
+ internal open var k1: jet.Int
+ internal abstract var k: jet.Int
+ internal open var l1: jet.Int
+ internal abstract var l: jet.Int
+ internal open var n: jet.Int
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AnonymousInitializerVarAndConstructor.txt b/compiler/testData/lazyResolve/diagnostics/AnonymousInitializerVarAndConstructor.txt
new file mode 100644
index 0000000000000..07b40dc4936a3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AnonymousInitializerVarAndConstructor.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ w: jet.Int): A
+ internal final var c: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/AutoCreatedIt.txt b/compiler/testData/lazyResolve/diagnostics/AutoCreatedIt.txt
new file mode 100644
index 0000000000000..4a777dce0acf5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AutoCreatedIt.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final class URI : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ body: jet.Any): URI
+ internal final val body: jet.Any
+ internal final fun to(/*0*/ dest: jet.String): jet.Tuple0
+}
+internal final fun bar(/*0*/ f: jet.Function2<jet.Int, jet.Int, jet.Int>): jet.Tuple0
+internal final fun bar1(/*0*/ f: jet.Function1<jet.Int, jet.Int>): jet.Tuple0
+internal final fun bar2(/*0*/ f: jet.Function0<jet.Int>): jet.Tuple0
+internal final fun jet.String.on(/*0*/ predicate: jet.Function1<URI, jet.Boolean>): URI
+internal final fun text(): jet.Tuple0
+internal final fun jet.String.to(/*0*/ dest: jet.String): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/AutocastAmbiguitites.txt b/compiler/testData/lazyResolve/diagnostics/AutocastAmbiguitites.txt
new file mode 100644
index 0000000000000..3994283420339
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AutocastAmbiguitites.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract trait B : jet.Any {
+ internal open fun bar(): jet.Tuple0
+}
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun bar(): jet.Tuple0
+}
+internal final fun test(/*0*/ a: jet.Any?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/AutocastsForStableIdentifiers.txt b/compiler/testData/lazyResolve/diagnostics/AutocastsForStableIdentifiers.txt
new file mode 100644
index 0000000000000..70a42c9ba6ced
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AutocastsForStableIdentifiers.txt
@@ -0,0 +1,28 @@
+namespace <root>
+
+// <namespace name="example">
+namespace example
+
+// <namespace name="ns">
+namespace ns
+
+internal final val y: jet.Any?
+// </namespace name="ns">
+internal final class example.AClass : jet.Any {
+ public final /*constructor*/ fun <init>(): example.AClass
+ internal final object example.AClass.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): example.AClass.<no name provided>
+ internal final val y: jet.Any?
+ }
+}
+internal open class example.C : jet.Any {
+ public final /*constructor*/ fun <init>(): example.C
+ internal final fun foo(): jet.Tuple0
+}
+internal abstract trait example.T : jet.Any {
+}
+internal final val Obj: example.Obj
+internal final val x: jet.Any?
+internal final fun jet.Any?.foo(): jet.Int
+internal final fun jet.Any?.vars(/*0*/ a: jet.Any?): jet.Int
+// </namespace name="example">
diff --git a/compiler/testData/lazyResolve/diagnostics/Basic.txt b/compiler/testData/lazyResolve/diagnostics/Basic.txt
new file mode 100644
index 0000000000000..9462dd9d5a717
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Basic.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val x: jet.Int
+}
+internal final fun foo(/*0*/ u: jet.Tuple0): jet.Int
+internal final fun foo1(): jet.Tuple0
+internal final fun test(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/BinaryCallsOnNullableValues.txt b/compiler/testData/lazyResolve/diagnostics/BinaryCallsOnNullableValues.txt
new file mode 100644
index 0000000000000..c2ce323156deb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/BinaryCallsOnNullableValues.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal final class B : jet.Any {
+ public final /*constructor*/ fun <init>(): B
+}
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+}
+internal final fun f(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Bounds.txt b/compiler/testData/lazyResolve/diagnostics/Bounds.txt
new file mode 100644
index 0000000000000..83f61dc32506a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Bounds.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="boundsWithSubstitutors">
+namespace boundsWithSubstitutors
+
+internal open class boundsWithSubstitutors.A</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): boundsWithSubstitutors.A<T>
+}
+internal final class boundsWithSubstitutors.B</*0*/ X : boundsWithSubstitutors.A<X>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ X : boundsWithSubstitutors.A<X>><init>(): boundsWithSubstitutors.B<X>
+}
+internal final class boundsWithSubstitutors.C : boundsWithSubstitutors.A<boundsWithSubstitutors.C> {
+ public final /*constructor*/ fun <init>(): boundsWithSubstitutors.C
+}
+internal final class boundsWithSubstitutors.X</*0*/ A : jet.Any?, /*1*/ B : A> : jet.Any {
+ public final /*constructor*/ fun </*0*/ A : jet.Any?, /*1*/ B : A><init>(): boundsWithSubstitutors.X<A, B>
+}
+internal final val a: boundsWithSubstitutors.B<boundsWithSubstitutors.C>
+internal final val a1: boundsWithSubstitutors.B<jet.Int>
+internal final val b: boundsWithSubstitutors.X<jet.Any, boundsWithSubstitutors.X<boundsWithSubstitutors.A<boundsWithSubstitutors.C>, boundsWithSubstitutors.C>>
+internal final val b0: boundsWithSubstitutors.X<jet.Any, jet.Any?>
+internal final val b1: boundsWithSubstitutors.X<jet.Any, boundsWithSubstitutors.X<boundsWithSubstitutors.A<boundsWithSubstitutors.C>, jet.String>>
+// </namespace name="boundsWithSubstitutors">
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal open class B</*0*/ T : A> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : A><init>(): B<T>
+}
+internal abstract class C</*0*/ T : B<jet.Int>, /*1*/ X : jet.Function1<B<jet.Char>, jet.Tuple2<out B<jet.Any>, out B<A>>>> : B<jet.Any> {
+ public final /*constructor*/ fun </*0*/ T : B<jet.Int>, /*1*/ X : jet.Function1<B<jet.Char>, jet.Tuple2<out B<jet.Any>, out B<A>>>><init>(): C<T, X>
+ internal final val a: B<jet.Char>
+ internal abstract val x: jet.Function1<B<jet.Char>, B<jet.Any>>
+}
+internal final fun </*0*/ T : jet.Int?>bar(): jet.Tuple0
+internal final fun </*0*/ T : jet.Int>jet.Int.buzz(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any>foo(): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/BreakContinue.txt b/compiler/testData/lazyResolve/diagnostics/BreakContinue.txt
new file mode 100644
index 0000000000000..fa81ecd84b4c1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/BreakContinue.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun containsBreak(/*0*/ a: jet.String?, /*1*/ b: jet.String?): jet.Tuple0
+ internal final fun containsBreakInsideLoopWithLabel(/*0*/ a: jet.String?, /*1*/ array: jet.Array<jet.Int>): jet.Tuple0
+ internal final fun containsBreakToOuterLoop(/*0*/ a: jet.String?, /*1*/ b: jet.String?): jet.Tuple0
+ internal final fun containsBreakWithLabel(/*0*/ a: jet.String?): jet.Tuple0
+ internal final fun containsIllegalBreak(/*0*/ a: jet.String?): jet.Tuple0
+ internal final fun f(/*0*/ a: jet.Boolean, /*1*/ b: jet.Boolean): jet.Tuple0
+ internal final fun notContainsBreak(/*0*/ a: jet.String?, /*1*/ b: jet.String?): jet.Tuple0
+ internal final fun unresolvedBreak(/*0*/ a: jet.String?, /*1*/ array: jet.Array<jet.Int>): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/Builders.txt b/compiler/testData/lazyResolve/diagnostics/Builders.txt
new file mode 100644
index 0000000000000..0644ee99f958a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Builders.txt
@@ -0,0 +1,193 @@
+namespace <root>
+
+// <namespace name="html">
+namespace html
+
+internal final class html.A : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.A
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ public final var href: jet.String?
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.B : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.B
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.Body : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.Body
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal abstract class html.BodyTag : html.TagWithText {
+ public final /*constructor*/ fun <init>(/*0*/ name: jet.String): html.BodyTag
+ internal final fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal abstract trait html.Element : jet.Any {
+ internal abstract fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.H1 : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.H1
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.HTML : html.TagWithText {
+ public final /*constructor*/ fun <init>(): html.HTML
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final fun body(/*0*/ init: jet.ExtensionFunction0<html.Body, jet.Tuple0>): html.Body
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final fun head(/*0*/ init: jet.ExtensionFunction0<html.Head, jet.Tuple0>): html.Head
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.Head : html.TagWithText {
+ public final /*constructor*/ fun <init>(): html.Head
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final fun title(/*0*/ init: jet.ExtensionFunction0<html.Title, jet.Tuple0>): html.Title
+}
+internal final class html.LI : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.LI
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.P : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.P
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal abstract class html.Tag : html.Element {
+ public final /*constructor*/ fun <init>(/*0*/ name: jet.String): html.Tag
+ internal final val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final val children: java.util.ArrayList<html.Element>
+ protected final fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ internal final val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ private final fun renderAttributes(): jet.String?
+}
+internal abstract class html.TagWithText : html.Tag {
+ public final /*constructor*/ fun <init>(/*0*/ name: jet.String): html.TagWithText
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.TextElement : html.Element {
+ public final /*constructor*/ fun <init>(/*0*/ text: jet.String): html.TextElement
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final val text: jet.String
+}
+internal final class html.Title : html.TagWithText {
+ public final /*constructor*/ fun <init>(): html.Title
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.UL : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.UL
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final fun li(/*0*/ init: jet.ExtensionFunction0<html.LI, jet.Tuple0>): html.LI
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final fun html(/*0*/ init: jet.ExtensionFunction0<html.HTML, jet.Tuple0>): html.HTML
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun print(/*0*/ message: jet.Any?): jet.Tuple0
+internal final fun println(/*0*/ message: jet.Any?): jet.Tuple0
+internal final fun </*0*/ K : jet.Any?, /*1*/ V : jet.Any?>java.util.Map<K, V>.set(/*0*/ key: K, /*1*/ value: V): V?
+// </namespace name="html">
diff --git a/compiler/testData/lazyResolve/diagnostics/Casts.txt b/compiler/testData/lazyResolve/diagnostics/Casts.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Casts.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/CharacterLiterals.txt b/compiler/testData/lazyResolve/diagnostics/CharacterLiterals.txt
new file mode 100644
index 0000000000000..e35be5298b9a3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/CharacterLiterals.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(/*0*/ c: jet.Char): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/ClassObjectCannotAccessClassFields.txt b/compiler/testData/lazyResolve/diagnostics/ClassObjectCannotAccessClassFields.txt
new file mode 100644
index 0000000000000..74e6380542bfd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ClassObjectCannotAccessClassFields.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val x: jet.Int
+ internal final object A.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): A.<no name provided>
+ internal final val y: [ERROR : Type for x]
+ }
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/ClassObjects.txt b/compiler/testData/lazyResolve/diagnostics/ClassObjects.txt
new file mode 100644
index 0000000000000..0c27cc88be657
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ClassObjects.txt
@@ -0,0 +1,23 @@
+namespace <root>
+
+// <namespace name="Jet86">
+namespace Jet86
+
+internal final class Jet86.A : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet86.A
+ internal final object Jet86.A.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Jet86.A.<no name provided>
+ internal final val x: jet.Int
+ }
+}
+internal final class Jet86.B : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet86.B
+ internal final val x: jet.Int
+}
+internal final val a: jet.Int
+internal final val b: Jet86.b
+internal final val c: jet.Int
+internal final val d: [ERROR : Type for b.x]
+internal final val s: java.lang.System
+internal final fun test(): jet.Tuple0
+// </namespace name="Jet86">
diff --git a/compiler/testData/lazyResolve/diagnostics/Constants.txt b/compiler/testData/lazyResolve/diagnostics/Constants.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Constants.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/CovariantOverrideType.txt b/compiler/testData/lazyResolve/diagnostics/CovariantOverrideType.txt
new file mode 100644
index 0000000000000..a8b2c6cd8ada9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/CovariantOverrideType.txt
@@ -0,0 +1,23 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal abstract val a1: jet.Int
+ internal abstract val a: jet.Int
+ internal open fun foo(): jet.Int
+ internal open fun foo1(): jet.Int
+ internal open fun foo2(): jet.Int
+ internal abstract fun </*0*/ T : jet.Any?>g(): T
+ internal abstract fun </*0*/ T : jet.Any?>g1(): T
+ internal abstract val </*0*/ T : jet.Any?> g: jet.Iterator<T>
+}
+internal abstract class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ val a1: jet.Double
+ internal open override /*1*/ val a: jet.Double
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ fun foo1(): jet.Int
+ internal open override /*1*/ fun foo2(): jet.Tuple0
+ internal abstract override /*1*/ fun </*0*/ X : jet.Any?>g(): jet.Int
+ internal abstract override /*1*/ fun </*0*/ X : jet.Any?>g1(): java.util.List<X>
+ internal abstract override /*1*/ val </*0*/ X : jet.Any?> g: jet.Iterator<jet.Int>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DanglingFunctionLiteral.txt b/compiler/testData/lazyResolve/diagnostics/DanglingFunctionLiteral.txt
new file mode 100644
index 0000000000000..1903119e88998
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DanglingFunctionLiteral.txt
@@ -0,0 +1,18 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ private final val builder: java.lang.StringBuilder
+}
+internal final class Foo1 : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo1
+ private final val builder: [ERROR : Type for StringBuilder("sdfsd")
+
+ {
+ }]
+}
+internal final fun foo(): jet.Function0<[ERROR : <return type>]>
+internal final fun foo1(): jet.Function0<jet.Function0<jet.Tuple0>>
+internal final fun println(): jet.Tuple0
+internal final fun println(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun println(/*0*/ s: jet.Byte): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/DeferredTypes.txt b/compiler/testData/lazyResolve/diagnostics/DeferredTypes.txt
new file mode 100644
index 0000000000000..ebfff80bc3a1b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DeferredTypes.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal abstract trait T : jet.Any {
+ internal open val a: [ERROR : <ERROR FUNCTION RETURN TYPE>]
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DiamondFunction.txt b/compiler/testData/lazyResolve/diagnostics/DiamondFunction.txt
new file mode 100644
index 0000000000000..8dbb888ad89b3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DiamondFunction.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Base : jet.Any {
+ public final /*constructor*/ fun <init>(): Base
+ internal final fun f(): jet.Int
+}
+internal final class Diamond : Left, Right {
+ public final /*constructor*/ fun <init>(): Diamond
+ internal final override /*2*/ fun f(): jet.Int
+}
+internal open class Left : Base {
+ public final /*constructor*/ fun <init>(): Left
+ internal final override /*1*/ fun f(): jet.Int
+}
+internal abstract trait Right : Base {
+ internal final override /*1*/ fun f(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DiamondFunctionGeneric.txt b/compiler/testData/lazyResolve/diagnostics/DiamondFunctionGeneric.txt
new file mode 100644
index 0000000000000..7bc103a2e3a57
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DiamondFunctionGeneric.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Base</*0*/ P : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ P : jet.Any?><init>(): Base<P>
+ internal final fun f(): jet.Int
+}
+internal final class Diamond</*0*/ P : jet.Any?> : Left<P>, Right<P> {
+ public final /*constructor*/ fun </*0*/ P : jet.Any?><init>(): Diamond<P>
+ internal final override /*2*/ fun f(): jet.Int
+}
+internal open class Left</*0*/ P : jet.Any?> : Base<P> {
+ public final /*constructor*/ fun </*0*/ P : jet.Any?><init>(): Left<P>
+ internal final override /*1*/ fun f(): jet.Int
+}
+internal abstract trait Right</*0*/ P : jet.Any?> : Base<P> {
+ internal final override /*1*/ fun f(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DiamondProperty.txt b/compiler/testData/lazyResolve/diagnostics/DiamondProperty.txt
new file mode 100644
index 0000000000000..9481d4cb5c354
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DiamondProperty.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Base : jet.Any {
+ public final /*constructor*/ fun <init>(): Base
+ internal final var v: jet.Int
+}
+internal final class Diamond : Left, Right {
+ public final /*constructor*/ fun <init>(): Diamond
+ internal final override /*2*/ var v: jet.Int
+}
+internal open class Left : Base {
+ public final /*constructor*/ fun <init>(): Left
+ internal final override /*1*/ var v: jet.Int
+}
+internal abstract trait Right : Base {
+ internal final override /*1*/ var v: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/Dollar.txt b/compiler/testData/lazyResolve/diagnostics/Dollar.txt
new file mode 100644
index 0000000000000..4cd12fc808be5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Dollar.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="dollar">
+namespace dollar
+
+internal open class dollar.$ : jet.Any {
+ public final /*constructor*/ fun <init>(): dollar.$
+}
+internal open class dollar.$$ : dollar.$ {
+ public open fun $$$$$$(): dollar.$$$$$?
+ internal final val $$$: dollar.$$$$$?
+ public final /*constructor*/ fun <init>(/*0*/ $$$$: dollar.$$$$$?): dollar.$$
+}
+internal open class dollar.$$$$$ : jet.Any {
+ public final /*constructor*/ fun <init>(): dollar.$$$$$
+}
+// </namespace name="dollar">
diff --git a/compiler/testData/lazyResolve/diagnostics/ForRangeConventions.txt b/compiler/testData/lazyResolve/diagnostics/ForRangeConventions.txt
new file mode 100644
index 0000000000000..e159db65aeb05
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ForRangeConventions.txt
@@ -0,0 +1,76 @@
+namespace <root>
+
+internal abstract class AmbiguousHasNextIterator : jet.Any {
+ public final /*constructor*/ fun <init>(): AmbiguousHasNextIterator
+ internal abstract fun hasNext(): jet.Boolean
+ internal final val hasNext: jet.Boolean
+ internal abstract fun next(): jet.Int
+}
+internal abstract class GoodIterator : jet.Any {
+ public final /*constructor*/ fun <init>(): GoodIterator
+ internal abstract fun hasNext(): jet.Boolean
+ internal abstract fun next(): jet.Int
+}
+internal abstract class ImproperIterator1 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator1
+ internal abstract fun hasNext(): jet.Boolean
+}
+internal abstract class ImproperIterator2 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator2
+ internal abstract fun next(): jet.Boolean
+}
+internal abstract class ImproperIterator3 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator3
+ internal abstract fun hasNext(): jet.Int
+ internal abstract fun next(): jet.Int
+}
+internal abstract class ImproperIterator4 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator4
+ internal final val hasNext: jet.Int
+ internal abstract fun next(): jet.Int
+}
+internal abstract class ImproperIterator5 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator5
+ internal abstract val jet.String.hasNext: jet.Boolean
+ internal abstract fun next(): jet.Int
+}
+internal final class NotRange1 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange1
+}
+internal abstract class NotRange2 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange2
+ internal abstract fun iterator(): jet.Tuple0
+}
+internal abstract class NotRange3 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange3
+ internal abstract fun iterator(): ImproperIterator1
+}
+internal abstract class NotRange4 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange4
+ internal abstract fun iterator(): ImproperIterator2
+}
+internal abstract class NotRange5 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange5
+ internal abstract fun iterator(): ImproperIterator3
+}
+internal abstract class NotRange6 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange6
+ internal abstract fun iterator(): AmbiguousHasNextIterator
+}
+internal abstract class NotRange7 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange7
+ internal abstract fun iterator(): ImproperIterator3
+}
+internal abstract class NotRange8 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange8
+ internal abstract fun iterator(): ImproperIterator5
+}
+internal abstract class Range0 : jet.Any {
+ public final /*constructor*/ fun <init>(): Range0
+ internal abstract fun iterator(): GoodIterator
+}
+internal abstract class Range1 : jet.Any {
+ public final /*constructor*/ fun <init>(): Range1
+ internal abstract fun iterator(): java.util.Iterator<jet.Int>
+}
+internal final fun test(/*0*/ notRange1: NotRange1, /*1*/ notRange2: NotRange2, /*2*/ notRange3: NotRange3, /*3*/ notRange4: NotRange4, /*4*/ notRange5: NotRange5, /*5*/ notRange6: NotRange6, /*6*/ notRange7: NotRange7, /*7*/ notRange8: NotRange8, /*8*/ range0: Range0, /*9*/ range1: Range1): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/FunctionCalleeExpressions.txt b/compiler/testData/lazyResolve/diagnostics/FunctionCalleeExpressions.txt
new file mode 100644
index 0000000000000..b053169382ca2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/FunctionCalleeExpressions.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+internal final fun f(): jet.ExtensionFunction0<jet.Int, jet.Tuple0>
+internal final fun jet.Any.foo(): jet.Function0<jet.Tuple0>
+internal final fun jet.Any.foo1(): jet.Function1<jet.Int, jet.Tuple0>
+internal final fun foo2(): jet.Function1<jet.Function0<jet.Tuple0>, jet.Tuple0>
+internal final fun </*0*/ T : jet.Any?>fooT1(/*0*/ t: T): jet.Function0<T>
+internal final fun </*0*/ T : jet.Any?>fooT2(): jet.Function1<T, T>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun main1(): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/GenericArgumentConsistency.txt b/compiler/testData/lazyResolve/diagnostics/GenericArgumentConsistency.txt
new file mode 100644
index 0000000000000..d7b4f71d64177
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/GenericArgumentConsistency.txt
@@ -0,0 +1,72 @@
+namespace <root>
+
+// <namespace name="x">
+namespace x
+
+internal abstract trait x.AA1</*0*/ out T : jet.Any?> : jet.Any {
+}
+internal abstract trait x.AB1 : x.AA1<jet.Int> {
+}
+internal abstract trait x.AB2 : x.AA1<jet.Number>, x.AB1, x.AB3 {
+}
+internal abstract trait x.AB3 : x.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="x">
+// <namespace name="x2">
+namespace x2
+
+internal abstract trait x2.AA1</*0*/ out T : jet.Any?> : jet.Any {
+}
+internal abstract trait x2.AB1 : x2.AA1<jet.Any> {
+}
+internal abstract trait x2.AB2 : x2.AA1<jet.Number>, x2.AB1, x2.AB3 {
+}
+internal abstract trait x2.AB3 : x2.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="x2">
+// <namespace name="x3">
+namespace x3
+
+internal abstract trait x3.AA1</*0*/ in T : jet.Any?> : jet.Any {
+}
+internal abstract trait x3.AB1 : x3.AA1<jet.Any> {
+}
+internal abstract trait x3.AB2 : x3.AA1<jet.Number>, x3.AB1, x3.AB3 {
+}
+internal abstract trait x3.AB3 : x3.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="x3">
+// <namespace name="sx2">
+namespace sx2
+
+internal abstract trait sx2.AA1</*0*/ in T : jet.Any?> : jet.Any {
+}
+internal abstract trait sx2.AB1 : sx2.AA1<jet.Int> {
+}
+internal abstract trait sx2.AB2 : sx2.AA1<jet.Number>, sx2.AB1, sx2.AB3 {
+}
+internal abstract trait sx2.AB3 : sx2.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="sx2">
+internal abstract trait A</*0*/ in T : jet.Any?> : jet.Any {
+}
+internal abstract trait A1</*0*/ out T : jet.Any?> : jet.Any {
+}
+internal abstract trait B</*0*/ T : jet.Any?> : A<jet.Int> {
+}
+internal abstract trait B1 : A1<jet.Int> {
+}
+internal abstract trait B2 : A1<jet.Any>, B1 {
+}
+internal abstract trait BA1</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait BB1 : BA1<jet.Int> {
+}
+internal abstract trait BB2 : BA1<jet.Any>, BB1 {
+}
+internal abstract trait C</*0*/ T : jet.Any?> : B<T>, A<T> {
+}
+internal abstract trait C1</*0*/ T : jet.Any?> : B<T>, A<jet.Any> {
+}
+internal abstract trait D : C<jet.Boolean>, B<jet.Double> {
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/GenericFunctionIsLessSpecific.txt b/compiler/testData/lazyResolve/diagnostics/GenericFunctionIsLessSpecific.txt
new file mode 100644
index 0000000000000..e33defc249c35
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/GenericFunctionIsLessSpecific.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo(/*0*/ i: jet.Int): jet.Int
+internal final fun </*0*/ T : jet.Any?>foo(/*0*/ t: T): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/IllegalModifiers.txt b/compiler/testData/lazyResolve/diagnostics/IllegalModifiers.txt
new file mode 100644
index 0000000000000..cb266716a9b64
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IllegalModifiers.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="illegal_modifiers">
+namespace illegal_modifiers
+
+internal abstract class illegal_modifiers.A : jet.Any {
+ public final /*constructor*/ fun <init>(): illegal_modifiers.A
+ internal abstract fun f(): jet.Tuple0
+ internal abstract fun g(): jet.Tuple0
+ internal open fun h(): jet.Tuple0
+ internal open var r: jet.String protected set
+}
+internal final class illegal_modifiers.FinalClass : jet.Any {
+ public final /*constructor*/ fun <init>(): illegal_modifiers.FinalClass
+ internal open fun foo(): jet.Tuple0
+ internal final val i: jet.Int
+ internal final var j: jet.Int
+}
+internal final trait illegal_modifiers.T : jet.Any {
+}
+// </namespace name="illegal_modifiers">
diff --git a/compiler/testData/lazyResolve/diagnostics/ImportResolutionOrder.txt b/compiler/testData/lazyResolve/diagnostics/ImportResolutionOrder.txt
new file mode 100644
index 0000000000000..0619174a86c54
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ImportResolutionOrder.txt
@@ -0,0 +1,26 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final val x: b.X
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final class b.X : jet.Any {
+ public final /*constructor*/ fun <init>(): b.X
+}
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final val x: d.X
+// </namespace name="c">
+// <namespace name="d">
+namespace d
+
+internal final class d.X : jet.Any {
+ public final /*constructor*/ fun <init>(): d.X
+}
+// </namespace name="d">
diff --git a/compiler/testData/lazyResolve/diagnostics/IncDec.txt b/compiler/testData/lazyResolve/diagnostics/IncDec.txt
new file mode 100644
index 0000000000000..248cb16f4fd0d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IncDec.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+internal final class IncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): IncDec
+ internal final fun dec(): IncDec
+ internal final fun inc(): IncDec
+}
+internal final class UnitIncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): UnitIncDec
+ internal final fun dec(): jet.Tuple0
+ internal final fun inc(): jet.Tuple0
+}
+internal final class WrongIncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): WrongIncDec
+ internal final fun dec(): jet.Int
+ internal final fun inc(): jet.Int
+}
+internal final fun testIncDec(): jet.Tuple0
+internal final fun testUnitIncDec(): jet.Tuple0
+internal final fun testWrongIncDec(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/IncorrectCharacterLiterals.txt b/compiler/testData/lazyResolve/diagnostics/IncorrectCharacterLiterals.txt
new file mode 100644
index 0000000000000..a951870ff4ce0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IncorrectCharacterLiterals.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/InferNullabilityInThenBlock.txt b/compiler/testData/lazyResolve/diagnostics/InferNullabilityInThenBlock.txt
new file mode 100644
index 0000000000000..0c15629d47ff7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/InferNullabilityInThenBlock.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun ff(/*0*/ a: jet.String): jet.Int
+internal final fun gg(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/IsExpressions.txt b/compiler/testData/lazyResolve/diagnostics/IsExpressions.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IsExpressions.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/LValueAssignment.txt b/compiler/testData/lazyResolve/diagnostics/LValueAssignment.txt
new file mode 100644
index 0000000000000..8632f0617bc51
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/LValueAssignment.txt
@@ -0,0 +1,47 @@
+namespace <root>
+
+// <namespace name="lvalue_assignment">
+namespace lvalue_assignment
+
+internal final class lvalue_assignment.A : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.A
+ internal final var a: jet.Int
+}
+internal abstract class lvalue_assignment.Ab : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.Ab
+ internal abstract fun getArray(): jet.Array<jet.Int>
+}
+internal open class lvalue_assignment.B : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.B
+ internal final var b: jet.Int
+ internal final val c: jet.Int
+}
+internal final class lvalue_assignment.C : lvalue_assignment.B {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.C
+ internal final override /*1*/ var b: jet.Int
+ internal final fun bar(/*0*/ c: lvalue_assignment.C): jet.Tuple0
+ internal final override /*1*/ val c: jet.Int
+ internal final fun foo(/*0*/ c: lvalue_assignment.C): jet.Tuple0
+ internal final fun foo1(/*0*/ c: lvalue_assignment.C): jet.Tuple0
+ internal final var x: jet.Int
+}
+internal final class lvalue_assignment.D : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.D
+ internal final class lvalue_assignment.D.B : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.D.B
+ internal final fun foo(): jet.Tuple0
+ }
+}
+internal final class lvalue_assignment.Test : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.Test
+ internal final fun testArrays(/*0*/ a: jet.Array<jet.Int>, /*1*/ ab: lvalue_assignment.Ab): jet.Tuple0
+ internal final fun testIllegalValues(): jet.Tuple0
+ internal final fun testVariables(): jet.Tuple0
+ internal final fun testVariables1(): jet.Tuple0
+}
+internal final fun canBe(/*0*/ i: jet.Int, /*1*/ j: jet.Int): jet.Tuple0
+internal final fun canBe2(/*0*/ j: jet.Int): jet.Tuple0
+internal final fun cannotBe(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun jet.Array<jet.Int>.checkThis(): jet.Tuple0
+internal final fun getInt(): jet.Int
+// </namespace name="lvalue_assignment">
diff --git a/compiler/testData/lazyResolve/diagnostics/MergePackagesWithJava.txt b/compiler/testData/lazyResolve/diagnostics/MergePackagesWithJava.txt
new file mode 100644
index 0000000000000..3c0a25e9c0e45
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/MergePackagesWithJava.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="java">
+namespace java
+
+internal final val c: java.lang.Class<out jet.Any?>?
+internal final val </*0*/ T : jet.Any?> jet.Array<T>?.length: jet.Int
+// </namespace name="java">
diff --git a/compiler/testData/lazyResolve/diagnostics/MultilineStringTemplates.txt b/compiler/testData/lazyResolve/diagnostics/MultilineStringTemplates.txt
new file mode 100644
index 0000000000000..00b44512421d5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/MultilineStringTemplates.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun new(): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/MultipleBounds.txt b/compiler/testData/lazyResolve/diagnostics/MultipleBounds.txt
new file mode 100644
index 0000000000000..cce7292b9c8e3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/MultipleBounds.txt
@@ -0,0 +1,54 @@
+namespace <root>
+
+// <namespace name="Jet87">
+namespace Jet87
+
+internal open class Jet87.A : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet87.A
+ internal final fun foo(): jet.Int
+}
+internal abstract trait Jet87.B : jet.Any {
+ internal open fun bar(): jet.Double
+}
+internal final class Jet87.Bar</*0*/ T : Jet87.Foo> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Foo><init>(): Jet87.Bar<T>
+}
+internal final class Jet87.Buzz</*0*/ T : Jet87.Bar<jet.Int> & [ERROR : nioho]> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Bar<jet.Int> & [ERROR : nioho]><init>(): Jet87.Buzz<T>
+}
+internal final class Jet87.C : Jet87.A, Jet87.B {
+ public final /*constructor*/ fun <init>(): Jet87.C
+ internal open override /*1*/ fun bar(): jet.Double
+ internal final override /*1*/ fun foo(): jet.Int
+}
+internal final class Jet87.D : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet87.D
+ internal final object Jet87.D.<no name provided> : Jet87.A, Jet87.B {
+ internal final /*constructor*/ fun <init>(): Jet87.D.<no name provided>
+ internal open override /*1*/ fun bar(): jet.Double
+ internal final override /*1*/ fun foo(): jet.Int
+ }
+}
+internal final class Jet87.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet87.Foo
+}
+internal final class Jet87.Test</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): Jet87.Test<T>
+}
+internal final class Jet87.Test1</*0*/ T : Jet87.A & Jet87.B> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.A & Jet87.B><init>(): Jet87.Test1<T>
+ internal final fun test(/*0*/ t: T): jet.Tuple0
+}
+internal final class Jet87.X</*0*/ T : Jet87.Foo> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Foo><init>(): Jet87.X<T>
+}
+internal final class Jet87.Y</*0*/ T : Jet87.Bar<Jet87.Foo> & Jet87.Foo> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Bar<Jet87.Foo> & Jet87.Foo><init>(): Jet87.Y<T>
+}
+internal final val t1: jet.Tuple0
+internal final val t2: jet.Tuple0
+internal final val t3: jet.Tuple0
+internal final val </*0*/ T : jet.Any?, /*1*/ B : T> x: jet.Int
+internal final fun test(): jet.Tuple0
+internal final fun </*0*/ T : Jet87.A & Jet87.B>test2(/*0*/ t: T): jet.Tuple0
+// </namespace name="Jet87">
diff --git a/compiler/testData/lazyResolve/diagnostics/NamedArgumentsAndDefaultValues.txt b/compiler/testData/lazyResolve/diagnostics/NamedArgumentsAndDefaultValues.txt
new file mode 100644
index 0000000000000..a69eda6ffd427
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/NamedArgumentsAndDefaultValues.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int = ?, /*1*/ y: jet.Int = ?, /*2*/ z: jet.String): jet.Tuple0
+internal final fun foo(/*0*/ a: jet.Int = ?, /*1*/ b: jet.String = ?): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/NamespaceInExpressionPosition.txt b/compiler/testData/lazyResolve/diagnostics/NamespaceInExpressionPosition.txt
new file mode 100644
index 0000000000000..a4f7602345f66
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/NamespaceInExpressionPosition.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+internal final class foo.X : jet.Any {
+ public final /*constructor*/ fun <init>(): foo.X
+}
+internal final val s: [ERROR : Type for java]
+internal final val ss: java.lang.System
+internal final val sss: foo.X
+internal final val xs: [ERROR : Type for lang]
+internal final val xss: java.lang.System
+internal final val xsss: foo.X
+internal final val xssss: [ERROR : Type for foo]
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/NamespaceQualified.txt b/compiler/testData/lazyResolve/diagnostics/NamespaceQualified.txt
new file mode 100644
index 0000000000000..933451333f87c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/NamespaceQualified.txt
@@ -0,0 +1,48 @@
+namespace <root>
+
+// <namespace name="foobar">
+namespace foobar
+
+// <namespace name="a">
+namespace a
+
+internal final val a: java.util.List<jet.Int>?
+internal final val a1: [ERROR : List<Int>]
+internal final val b: java.util.List<jet.Int>?
+internal final val b1: [ERROR : util.List<Int>]
+// </namespace name="a">
+internal abstract class foobar.Collection</*0*/ E : jet.Any?> : jet.Iterable<E> {
+ public final /*constructor*/ fun </*0*/ E : jet.Any?><init>(): foobar.Collection<E>
+ internal final fun </*0*/ O : jet.Any?>iterate(/*0*/ iteratee: foobar.Iteratee<E, O>): O
+ public abstract override /*1*/ fun iterator(): jet.Iterator<E>
+}
+internal abstract class foobar.Foo</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): foobar.Foo<T>
+ internal abstract val x: T
+}
+internal abstract class foobar.Iteratee</*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?><init>(): foobar.Iteratee<I, O>
+ internal abstract fun done(): O
+ internal abstract val isDone: jet.Boolean
+ internal abstract fun process(/*0*/ item: I): foobar.Iteratee<I, O>
+ internal abstract val result: O
+}
+internal final class foobar.StrangeIterateeImpl</*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?> : foobar.Iteratee<I, O> {
+ public final /*constructor*/ fun </*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?><init>(/*0*/ obj: O): foobar.StrangeIterateeImpl<I, O>
+ internal open override /*1*/ fun done(): O
+ internal open override /*1*/ val isDone: jet.Boolean
+ internal final val obj: O
+ internal open override /*1*/ fun process(/*0*/ item: I): foobar.Iteratee<I, O>
+ internal open override /*1*/ val result: O
+}
+internal abstract class foobar.Sum : foobar.Iteratee<jet.Int, jet.Int> {
+ public final /*constructor*/ fun <init>(): foobar.Sum
+ internal abstract override /*1*/ fun done(): jet.Int
+ internal abstract override /*1*/ val isDone: jet.Boolean
+ internal open override /*1*/ fun process(/*0*/ item: jet.Int): foobar.Iteratee<jet.Int, jet.Int>
+ internal abstract override /*1*/ val result: jet.Int
+}
+internal final val x1: java.util.List<jet.Int>?
+internal final val y1: java.util.List<jet.Int>?
+internal final fun </*0*/ O : jet.Any?>done(/*0*/ result: O): foobar.Iteratee<jet.Any?, O>
+// </namespace name="foobar">
diff --git a/compiler/testData/lazyResolve/diagnostics/Nullability.txt b/compiler/testData/lazyResolve/diagnostics/Nullability.txt
new file mode 100644
index 0000000000000..3b056c1c63314
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Nullability.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final fun f(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f1(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f2(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f3(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f4(/*0*/ s: jet.String?): jet.Tuple0
+internal final fun f5(/*0*/ s: jet.String?): jet.Tuple0
+internal final fun f6(/*0*/ s: jet.String?): jet.Tuple0
+internal final fun f7(/*0*/ s: jet.String?, /*1*/ t: jet.String?): jet.Tuple0
+internal final fun f8(/*0*/ b: jet.String?, /*1*/ a: jet.String): jet.Tuple0
+internal final fun f9(/*0*/ a: jet.Int?): jet.Int
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/OverrideFunctionWithParamDefaultValue.txt b/compiler/testData/lazyResolve/diagnostics/OverrideFunctionWithParamDefaultValue.txt
new file mode 100644
index 0000000000000..913fa03a2342b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/OverrideFunctionWithParamDefaultValue.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal abstract class B : jet.Any {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract fun foo2(/*0*/ arg: jet.Int = ?): jet.Int
+}
+internal final class C : B {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun foo2(/*0*/ arg: jet.Int = ?): jet.Int
+}
+internal final fun invokeIt(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/OverridenFunctionAndSpecifiedTypeParameter.txt b/compiler/testData/lazyResolve/diagnostics/OverridenFunctionAndSpecifiedTypeParameter.txt
new file mode 100644
index 0000000000000..92342e417610d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/OverridenFunctionAndSpecifiedTypeParameter.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract trait Aaa</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract fun zzz(/*0*/ value: T): jet.Tuple0
+}
+internal final class Bbb</*0*/ T : jet.Any?> : Aaa<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): Bbb<T>
+ internal open override /*1*/ fun zzz(/*0*/ value: T): jet.Tuple0
+}
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/OverridingVarByVal.txt b/compiler/testData/lazyResolve/diagnostics/OverridingVarByVal.txt
new file mode 100644
index 0000000000000..0c5baea4d586e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/OverridingVarByVal.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal final class Val : Var, VarT {
+ public final /*constructor*/ fun <init>(): Val
+ internal open override /*2*/ val v: jet.Int
+}
+internal open class Var : jet.Any {
+ public final /*constructor*/ fun <init>(): Var
+ internal open var v: jet.Int
+}
+internal final class Var2 : Var {
+ public final /*constructor*/ fun <init>(): Var2
+ internal open override /*1*/ var v: jet.Int
+}
+internal abstract trait VarT : jet.Any {
+ internal abstract var v: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/PrimaryConstructors.txt b/compiler/testData/lazyResolve/diagnostics/PrimaryConstructors.txt
new file mode 100644
index 0000000000000..2b0d8518cc1c0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/PrimaryConstructors.txt
@@ -0,0 +1,27 @@
+namespace <root>
+
+internal final class MyIterable</*0*/ T : jet.Any?> : jet.Iterable<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): MyIterable<T>
+ internal final class MyIterable.MyIterator : jet.Iterator<T> {
+ public final /*constructor*/ fun <init>(): MyIterable.MyIterator
+ public open override /*1*/ val hasNext: jet.Boolean
+ public open override /*1*/ fun next(): T
+ }
+ public open override /*1*/ fun iterator(): jet.Iterator<T>
+}
+internal final class X : jet.Any {
+ public final /*constructor*/ fun <init>(): X
+ internal final val x: jet.Int
+}
+internal open class Y : jet.Any {
+ public final /*constructor*/ fun <init>(): Y
+ internal final val x: jet.Int
+}
+internal final class Y1 : jet.Any {
+ public final /*constructor*/ fun <init>(): Y1
+ internal final val x: jet.Int
+}
+internal final class Z : Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal final override /*1*/ val x: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/ProcessingEmptyImport.txt b/compiler/testData/lazyResolve/diagnostics/ProcessingEmptyImport.txt
new file mode 100644
index 0000000000000..e6dce1f6909d2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ProcessingEmptyImport.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun firstFun(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/ProjectionOnFunctionArgumentErrror.txt b/compiler/testData/lazyResolve/diagnostics/ProjectionOnFunctionArgumentErrror.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ProjectionOnFunctionArgumentErrror.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/ProjectionsInSupertypes.txt b/compiler/testData/lazyResolve/diagnostics/ProjectionsInSupertypes.txt
new file mode 100644
index 0000000000000..9c693405742dd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ProjectionsInSupertypes.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal abstract trait A</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait B</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait C</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait D</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait Test : A<in jet.Int>, B<out jet.Int>, C<out jet.Any?>?, D<jet.Int> {
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/QualifiedExpressions.txt b/compiler/testData/lazyResolve/diagnostics/QualifiedExpressions.txt
new file mode 100644
index 0000000000000..d2f0498cb2632
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/QualifiedExpressions.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="qualified_expressions">
+namespace qualified_expressions
+
+internal final fun jet.String.startsWith(/*0*/ s: jet.String): jet.Boolean
+internal final fun test(/*0*/ s: jet.String?): jet.Tuple0
+// </namespace name="qualified_expressions">
diff --git a/compiler/testData/lazyResolve/diagnostics/RecursiveTypeInference.txt b/compiler/testData/lazyResolve/diagnostics/RecursiveTypeInference.txt
new file mode 100644
index 0000000000000..1553f6e4d5261
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/RecursiveTypeInference.txt
@@ -0,0 +1,44 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final val foo: [ERROR : Error function type]
+internal final fun bar(): [ERROR : Error function type]
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final fun bar(): [ERROR : Error function type]
+internal final fun foo(): [ERROR : Error function type]
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final fun bar(): [ERROR : Error function type]
+internal final fun bazz(): [ERROR : Error function type]
+internal final fun foo(): [ERROR : Error function type]
+// </namespace name="c">
+// <namespace name="ok">
+namespace ok
+
+// <namespace name="a">
+namespace a
+
+internal final val foo: jet.Int
+internal final fun bar(): jet.Int
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final fun bar(): jet.Int
+internal final fun foo(): jet.Int
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final fun bar(): jet.Int
+internal final fun bazz(): jet.Int
+internal final fun foo(): jet.Int
+// </namespace name="c">
+// </namespace name="ok">
diff --git a/compiler/testData/lazyResolve/diagnostics/ResolveOfJavaGenerics.txt b/compiler/testData/lazyResolve/diagnostics/ResolveOfJavaGenerics.txt
new file mode 100644
index 0000000000000..bed0e4ddbd870
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ResolveOfJavaGenerics.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
+internal final fun test(/*0*/ a: java.lang.Class<jet.Int>): jet.Tuple0
+internal final fun test(/*0*/ a: java.lang.Comparable<jet.Int>): jet.Tuple0
+internal final fun test(/*0*/ a: java.lang.annotation.RetentionPolicy): jet.Tuple0
+internal final fun test(/*0*/ a: java.util.ArrayList<jet.Int>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Return.txt b/compiler/testData/lazyResolve/diagnostics/Return.txt
new file mode 100644
index 0000000000000..efed81cc38cf1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Return.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun outer(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiver.txt b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiver.txt
new file mode 100644
index 0000000000000..4b34c64649ab4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiver.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiverReturnNull.txt b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiverReturnNull.txt
new file mode 100644
index 0000000000000..110b47cb0c189
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiverReturnNull.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
+internal final fun jet.Int.gg(): jet.Nothing?
diff --git a/compiler/testData/lazyResolve/diagnostics/ShiftFunctionTypes.txt b/compiler/testData/lazyResolve/diagnostics/ShiftFunctionTypes.txt
new file mode 100644
index 0000000000000..581d4dbd0e762
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ShiftFunctionTypes.txt
@@ -0,0 +1,50 @@
+namespace <root>
+
+// <namespace name="n">
+namespace n
+
+internal final class n.B : jet.Any {
+ public final /*constructor*/ fun <init>(): n.B
+}
+// </namespace name="n">
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal abstract class XXX : jet.Any {
+ public final /*constructor*/ fun <init>(): XXX
+ internal final val a11: jet.Function1<jet.Int, jet.Int>?
+ internal final val a12: jet.Function1<jet.Int, jet.Int>?
+ internal abstract val a13: jet.ExtensionFunction1<jet.Int, jet.Int, jet.Int>
+ internal abstract val a14: jet.ExtensionFunction1<n.B, jet.Int, jet.Int>
+ internal abstract val a152: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a15: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a16: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a17: jet.ExtensionFunction1<jet.Function1<jet.Int, jet.Int>, jet.Int, jet.Int>
+ internal abstract val a18: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a19: jet.Function1<jet.Function1<jet.Int, jet.Int>, jet.Int>
+ internal abstract val a1: [ERROR : package.Int]
+ internal abstract val a2: n.B
+ internal abstract val a31: n.B
+ internal abstract val a3: A
+ internal abstract val a4: A?
+ internal abstract val a5: A?
+ internal abstract val a6: A?
+ internal abstract val a7: jet.Function1<A, n.B>
+ internal abstract val a8: jet.Function2<A, n.B, n.B>
+ internal abstract val a: jet.Int
+}
+internal abstract class YYY : jet.Any {
+ public final /*constructor*/ fun <init>(): YYY
+ internal final val a11: jet.Function1<jet.Int, jet.Int>?
+ internal final val a12: jet.Function1<jet.Int, jet.Int>?
+ internal abstract val a13: jet.ExtensionFunction1<jet.Int, jet.Int, jet.Int>
+ internal abstract val a14: jet.ExtensionFunction1<n.B, jet.Int, jet.Int>
+ internal abstract val a152: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a15: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a16: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a17: jet.ExtensionFunction1<jet.Function1<jet.Int, jet.Int>, jet.Int, jet.Int>
+ internal abstract val a18: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a19: jet.Function1<jet.Function1<jet.Int, jet.Int>, jet.Int>
+ internal abstract val a7: jet.Function1<A, n.B>
+ internal abstract val a8: jet.Function2<A, n.B, n.B>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/StarsInFunctionCalls.txt b/compiler/testData/lazyResolve/diagnostics/StarsInFunctionCalls.txt
new file mode 100644
index 0000000000000..4d09b4d1d98bc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/StarsInFunctionCalls.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun foo(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>getT(): jet.Tuple0
+internal final fun </*0*/ A : jet.Any?, /*1*/ B : jet.Any?>getTT(): jet.Tuple0
+internal final fun </*0*/ A : jet.Any?, /*1*/ B : jet.Any?, /*2*/ C : jet.Any?>getTTT(/*0*/ x: jet.Any): jet.Tuple0
+internal open fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/StringTemplates.txt b/compiler/testData/lazyResolve/diagnostics/StringTemplates.txt
new file mode 100644
index 0000000000000..9649148c965fc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/StringTemplates.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun demo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Super.txt b/compiler/testData/lazyResolve/diagnostics/Super.txt
new file mode 100644
index 0000000000000..df3fcb4d8eb77
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Super.txt
@@ -0,0 +1,43 @@
+namespace <root>
+
+// <namespace name="example">
+namespace example
+
+internal final class example.A</*0*/ E : jet.Any?> : example.C, example.T {
+ public final /*constructor*/ fun </*0*/ E : jet.Any?><init>(): example.A<E>
+ internal final override /*1*/ fun bar(): jet.Tuple0
+ internal final class example.A.B : example.T {
+ public final /*constructor*/ fun <init>(): example.A.B
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+ }
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+}
+internal final class example.A1 : jet.Any {
+ public final /*constructor*/ fun <init>(): example.A1
+ internal final fun test(): jet.Tuple0
+}
+internal open class example.C : jet.Any {
+ public final /*constructor*/ fun <init>(): example.C
+ internal final fun bar(): jet.Tuple0
+}
+internal final class example.CG : example.G<jet.Int> {
+ public final /*constructor*/ fun <init>(): example.CG
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+}
+internal final class example.ERROR</*0*/ E : jet.Any?> {
+ public final /*constructor*/ fun </*0*/ E : jet.Any?><init>(): example.ERROR<E>
+ internal final fun test(): jet.Tuple0
+}
+internal abstract trait example.G</*0*/ T : jet.Any?> : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait example.T : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal final fun any(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun notAnExpression(): jet.Tuple0
+// </namespace name="example">
diff --git a/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlighting.txt b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlighting.txt
new file mode 100644
index 0000000000000..9e5beb4ac5740
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlighting.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun get(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlightingEof.txt b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlightingEof.txt
new file mode 100644
index 0000000000000..1604dc621422a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlightingEof.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/TypeInference.txt b/compiler/testData/lazyResolve/diagnostics/TypeInference.txt
new file mode 100644
index 0000000000000..14c7a9d2f8986
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/TypeInference.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class C</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): C<T>
+ internal final fun foo(): T
+}
+internal final fun </*0*/ T : jet.Any?>bar(): C<T>
+internal final fun foo(/*0*/ c: C<jet.Int>): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/UnitByDefaultForFunctionTypes.txt b/compiler/testData/lazyResolve/diagnostics/UnitByDefaultForFunctionTypes.txt
new file mode 100644
index 0000000000000..bf498336f240c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/UnitByDefaultForFunctionTypes.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(/*0*/ f: jet.Function0<jet.Tuple0>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/UnreachableCode.txt b/compiler/testData/lazyResolve/diagnostics/UnreachableCode.txt
new file mode 100644
index 0000000000000..75755fdd9b953
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/UnreachableCode.txt
@@ -0,0 +1,25 @@
+namespace <root>
+
+internal final fun blockAndAndMismatch(): jet.Boolean
+internal final fun fail(): jet.Nothing
+internal final fun failtest(/*0*/ a: jet.Int): jet.Int
+internal final fun foo(/*0*/ a: jet.Nothing): jet.Tuple0
+internal final fun nullIsNotNothing(): jet.Tuple0
+internal final fun returnInWhile(/*0*/ a: jet.Int): jet.Tuple0
+internal final fun t1(): jet.Int
+internal final fun t1a(): jet.Int
+internal final fun t1b(): jet.Int
+internal final fun t1c(): jet.Int
+internal final fun t2(): jet.Int
+internal final fun t2a(): jet.Int
+internal final fun t3(): jet.Any
+internal final fun t4(/*0*/ a: jet.Boolean): jet.Int
+internal final fun t4break(/*0*/ a: jet.Boolean): jet.Int
+internal final fun t5(): jet.Int
+internal final fun t6(): jet.Int
+internal final fun t6break(): jet.Int
+internal final fun t7(): jet.Int
+internal final fun t7(/*0*/ b: jet.Int): jet.Int
+internal final fun t7break(/*0*/ b: jet.Int): jet.Int
+internal final fun t8(): jet.Int
+internal final fun tf(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/Unresolved.txt b/compiler/testData/lazyResolve/diagnostics/Unresolved.txt
new file mode 100644
index 0000000000000..321166bec2707
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Unresolved.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="unresolved">
+namespace unresolved
+
+internal final fun foo1(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun testGenericArgumentsCount(): jet.Tuple0
+internal final fun testUnresolved(): jet.Tuple0
+// </namespace name="unresolved">
diff --git a/compiler/testData/lazyResolve/diagnostics/UnusedVariables.txt b/compiler/testData/lazyResolve/diagnostics/UnusedVariables.txt
new file mode 100644
index 0000000000000..3a8d49385e4a3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/UnusedVariables.txt
@@ -0,0 +1,31 @@
+namespace <root>
+
+// <namespace name="unused_variables">
+namespace unused_variables
+
+internal final class unused_variables.IncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): unused_variables.IncDec
+ internal final fun dec(): unused_variables.IncDec
+ internal final fun inc(): unused_variables.IncDec
+}
+internal final class unused_variables.MyTest : jet.Any {
+ public final /*constructor*/ fun <init>(): unused_variables.MyTest
+ internal final var a: jet.String
+ internal final fun doSmth(/*0*/ a: jet.Any): jet.Tuple0
+ internal final fun doSmth(/*0*/ s: jet.String): jet.Tuple0
+ internal final fun testFor(): jet.Tuple0
+ internal final fun testIf(): jet.Tuple0
+ internal final fun testIncDec(): jet.Tuple0
+ internal final fun testSimple(): jet.Tuple0
+ internal final fun testWhile(): jet.Tuple0
+}
+internal abstract trait unused_variables.Trait : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun testBackingFieldsNotMarked(): jet.Tuple0
+internal final fun testFunctionLiterals(): jet.Tuple0
+internal final fun testInnerFunctions(): jet.Tuple0
+internal final fun testObject(): unused_variables.Trait
+internal final fun testSimpleCases(): jet.Tuple0
+// </namespace name="unused_variables">
diff --git a/compiler/testData/lazyResolve/diagnostics/ValAndFunOverrideCompatibilityClash.txt b/compiler/testData/lazyResolve/diagnostics/ValAndFunOverrideCompatibilityClash.txt
new file mode 100644
index 0000000000000..fee77e3333484
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ValAndFunOverrideCompatibilityClash.txt
@@ -0,0 +1,42 @@
+namespace <root>
+
+internal open class Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): Bar
+ internal final fun v(): jet.Int
+ internal final val v: jet.Int
+}
+internal final class Barr : Bar {
+ public final /*constructor*/ fun <init>(): Barr
+ internal final override /*1*/ fun v(): jet.Int
+ internal final override /*1*/ val v: jet.Int
+}
+internal final class Foo1 : java.util.ArrayList<jet.Int> {
+ public final /*constructor*/ fun <init>(): Foo1
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int): jet.Boolean
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun addAll(/*0*/ p0: java.util.Collection<out jet.Int>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: jet.Int, /*1*/ p1: java.util.Collection<out jet.Int>): jet.Boolean
+ public open override /*1*/ fun clear(): jet.Tuple0
+ public open override /*1*/ fun contains(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun containsAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun ensureCapacity(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun get(/*0*/ p0: jet.Int): jet.Int
+ public open override /*1*/ fun indexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun isEmpty(): jet.Boolean
+ public open override /*1*/ fun iterator(): java.util.Iterator<jet.Int>
+ public open override /*1*/ fun lastIndexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun listIterator(): java.util.ListIterator<jet.Int>
+ public open override /*1*/ fun listIterator(/*0*/ p0: jet.Int): java.util.ListIterator<jet.Int>
+ protected final override /*1*/ var modCount: jet.Int
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Int): jet.Int
+ public open override /*1*/ fun removeAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ protected open override /*1*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun retainAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun set(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Int
+ public open override /*1*/ fun size(): jet.Int
+ public open override /*1*/ fun subList(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): java.util.List<jet.Int>
+ public open override /*1*/ fun toArray(): jet.Array<jet.Any?>
+ public open override /*1*/ fun </*0*/ T : jet.Any?>toArray(/*0*/ p0: jet.Array<T>): jet.Array<T>
+ public open override /*1*/ fun trimToSize(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/VarargTypes.txt b/compiler/testData/lazyResolve/diagnostics/VarargTypes.txt
new file mode 100644
index 0000000000000..d90e2180771ec
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/VarargTypes.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final fun foob(/*0*/ vararg a: jet.Boolean /*jet.BooleanArray*/): jet.BooleanArray
+internal final fun foob(/*0*/ vararg a: jet.Byte /*jet.ByteArray*/): jet.ByteArray
+internal final fun fooc(/*0*/ vararg a: jet.Char /*jet.CharArray*/): jet.CharArray
+internal final fun food(/*0*/ vararg a: jet.Double /*jet.DoubleArray*/): jet.DoubleArray
+internal final fun foof(/*0*/ vararg a: jet.Float /*jet.FloatArray*/): jet.FloatArray
+internal final fun fooi(/*0*/ vararg a: jet.Int /*jet.IntArray*/): jet.IntArray
+internal final fun fool(/*0*/ vararg a: jet.Long /*jet.LongArray*/): jet.LongArray
+internal final fun foos(/*0*/ vararg a: jet.Short /*jet.ShortArray*/): jet.ShortArray
+internal final fun foos(/*0*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.Array<jet.String>
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Varargs.txt b/compiler/testData/lazyResolve/diagnostics/Varargs.txt
new file mode 100644
index 0000000000000..457d4575615d9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Varargs.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
+internal final fun v(/*0*/ x: jet.Int, /*1*/ y: jet.String, /*2*/ vararg f: jet.Long /*jet.LongArray*/): jet.Tuple0
+internal final fun v1(/*0*/ vararg f: jet.Function1<jet.Int, jet.Tuple0> /*jet.Array<jet.Function1<jet.Int, jet.Tuple0>>*/): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Variance.txt b/compiler/testData/lazyResolve/diagnostics/Variance.txt
new file mode 100644
index 0000000000000..95659be921597
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Variance.txt
@@ -0,0 +1,28 @@
+namespace <root>
+
+// <namespace name="variance">
+namespace variance
+
+internal final class variance.Array</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ length: jet.Int, /*1*/ t: T): variance.Array<T>
+ internal final fun get(/*0*/ index: jet.Int): T
+ internal final val length: jet.Int
+ internal final fun set(/*0*/ index: jet.Int, /*1*/ value: T): jet.Tuple0
+ internal final val t: T
+}
+internal abstract class variance.Consumer</*0*/ in T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ in T : jet.Any?><init>(): variance.Consumer<T>
+}
+internal abstract class variance.Producer</*0*/ out T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ out T : jet.Any?><init>(): variance.Producer<T>
+}
+internal abstract class variance.Usual</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): variance.Usual<T>
+}
+internal final fun copy1(/*0*/ from: variance.Array<jet.Any>, /*1*/ to: variance.Array<jet.Any>): jet.Tuple0
+internal final fun copy2(/*0*/ from: variance.Array<out jet.Any>, /*1*/ to: variance.Array<in jet.Any>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>copy3(/*0*/ from: variance.Array<out T>, /*1*/ to: variance.Array<in T>): jet.Tuple0
+internal final fun copy4(/*0*/ from: variance.Array<out jet.Number>, /*1*/ to: variance.Array<in jet.Int>): jet.Tuple0
+internal final fun f(/*0*/ ints: variance.Array<jet.Int>, /*1*/ any: variance.Array<jet.Any>, /*2*/ numbers: variance.Array<jet.Number>): jet.Tuple0
+internal final fun foo(/*0*/ c: variance.Consumer<jet.Int>, /*1*/ p: variance.Producer<jet.Int>, /*2*/ u: variance.Usual<jet.Int>): jet.Tuple0
+// </namespace name="variance">
diff --git a/compiler/testData/lazyResolve/diagnostics/When.txt b/compiler/testData/lazyResolve/diagnostics/When.txt
new file mode 100644
index 0000000000000..a1ad99df2f40c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/When.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final val _type_test: jet.Int
+internal final val jet.Tuple2<out jet.Int, out jet.Int>.boo: jet.Tuple3<out jet.Int, out jet.Int, out jet.Int>
+internal final fun foo(): jet.Int
+internal final fun jet.Int.foo(): jet.Boolean
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/AnnotatedConstructorParams.txt b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotatedConstructorParams.txt
new file mode 100644
index 0000000000000..83c777808a905
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotatedConstructorParams.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.Test : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ s: jet.String, /*1*/ x: jet.Int): a.Test
+ internal final java.lang.Deprecated() val s: jet.String
+ internal final java.lang.SuppressWarnings() val x: jet.Int
+}
+internal final java.lang.Deprecated() java.lang.SuppressWarnings() val s: jet.String
+internal final java.lang.Deprecated() java.lang.SuppressWarnings() fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/AnnotationsForClasses.txt b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotationsForClasses.txt
new file mode 100644
index 0000000000000..18ad41ac19506
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotationsForClasses.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+java.lang.Deprecated() internal final annotation class my : jet.Any {
+ public final /*constructor*/ fun <init>(): my
+}
+java.lang.Deprecated() internal final annotation class my1 : jet.Any {
+ public final /*constructor*/ fun <init>(): my1
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/Deprecated.txt b/compiler/testData/lazyResolve/diagnostics/annotations/Deprecated.txt
new file mode 100644
index 0000000000000..24000a5e05586
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/Deprecated.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final java.lang.Deprecated() fun foo(): jet.Tuple0
+internal final java.lang.Deprecated() fun foo1(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/NonAnnotationClass.txt b/compiler/testData/lazyResolve/diagnostics/annotations/NonAnnotationClass.txt
new file mode 100644
index 0000000000000..8bca4d4d609c5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/NonAnnotationClass.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+Foo() internal final class Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): Bar
+}
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-negative.txt b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-negative.txt
new file mode 100644
index 0000000000000..d2076c739d397
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-negative.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Hello : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ args: jet.Any): Hello
+}
+internal final var bar: jet.Int
+internal final val x: jet.Function1<jet.Int, jet.Int>
+internal final fun foo(/*0*/ f: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-positive.txt b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-positive.txt
new file mode 100644
index 0000000000000..dddd8b16fdfcb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-positive.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class Hello : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ args: jet.Any): Hello
+}
+internal final annotation class test : jet.Any {
+ public final /*constructor*/ fun <init>(): test
+}
+internal final var bar: jet.Int
+internal final val x: jet.Function1<jet.Int, jet.Int>
+internal final fun foo(/*0*/ f: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetSet.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetSet.txt
new file mode 100644
index 0000000000000..025b5c5673870
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetSet.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Flower : jet.Any {
+ public final /*constructor*/ fun <init>(): Flower
+ internal final var minusOne: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVal.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVal.txt
new file mode 100644
index 0000000000000..52d4a9fa35e3c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVal.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class CustomGetVal : jet.Any {
+ public final /*constructor*/ fun <init>(): CustomGetVal
+ internal final val zz: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetValGlobal.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetValGlobal.txt
new file mode 100644
index 0000000000000..8ad18bb2c26ab
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetValGlobal.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="customGetValGlobal">
+namespace customGetValGlobal
+
+internal final val zz: jet.Int
+// </namespace name="customGetValGlobal">
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVar.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVar.txt
new file mode 100644
index 0000000000000..17212ccffec56
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVar.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Raise : jet.Any {
+ public final /*constructor*/ fun <init>(): Raise
+ internal final var zz: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomSet.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomSet.txt
new file mode 100644
index 0000000000000..17212ccffec56
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomSet.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Raise : jet.Any {
+ public final /*constructor*/ fun <init>(): Raise
+ internal final var zz: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CyclicReferenceInitializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CyclicReferenceInitializer.txt
new file mode 100644
index 0000000000000..cb1b1edaa39fd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CyclicReferenceInitializer.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Cyclic : jet.Any {
+ public final /*constructor*/ fun <init>(): Cyclic
+ internal final val a: [ERROR : Type for $a]
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInAnonymous.txt
new file mode 100644
index 0000000000000..9c76cad0dbf21
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class ReadForward : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadForward
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInPropertyInitializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInPropertyInitializer.txt
new file mode 100644
index 0000000000000..65e929a806352
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInPropertyInitializer.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class ReadForward : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadForward
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnonymous.txt
new file mode 100644
index 0000000000000..a2ed75745f0ca
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class ReadByAnotherPropertyInitializer : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadByAnotherPropertyInitializer
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnotherPropertyIntializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnotherPropertyIntializer.txt
new file mode 100644
index 0000000000000..4b1223d1f7f9b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnotherPropertyIntializer.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class ReadByAnotherPropertyInitializer : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadByAnotherPropertyInitializer
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadInFunction.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInFunction.txt
new file mode 100644
index 0000000000000..f87e66d9ed7fe
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class ReadByAnotherPropertyInitializer : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadByAnotherPropertyInitializer
+ internal final val a: jet.Int
+ internal final fun ff(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInAnonymous.txt
new file mode 100644
index 0000000000000..c10d13a95d7c2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal abstract class ReadNonexistent : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadNonexistent
+ internal abstract val aa: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInFunction.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInFunction.txt
new file mode 100644
index 0000000000000..7e0c411af0c12
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal abstract class ReadNonexistent : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadNonexistent
+ internal abstract val aa: jet.Int
+ internal final fun ff(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnonymous.txt
new file mode 100644
index 0000000000000..05b6b85d81656
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class ReadNonexistent : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadNonexistent
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnotherInitializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnotherInitializer.txt
new file mode 100644
index 0000000000000..5ef8889422ca3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnotherInitializer.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class CustomValNoBackingField : jet.Any {
+ public final /*constructor*/ fun <init>(): CustomValNoBackingField
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentDeclaredInHigher.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentDeclaredInHigher.txt
new file mode 100644
index 0000000000000..5ef8889422ca3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentDeclaredInHigher.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class CustomValNoBackingField : jet.Any {
+ public final /*constructor*/ fun <init>(): CustomValNoBackingField
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentPropertyInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentPropertyInAnonymous.txt
new file mode 100644
index 0000000000000..f5e51236dd169
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentPropertyInAnonymous.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class Cl : jet.Any {
+ public final /*constructor*/ fun <init>(): Cl
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/WriteNonexistentDeclaredInHigher.txt b/compiler/testData/lazyResolve/diagnostics/backingField/WriteNonexistentDeclaredInHigher.txt
new file mode 100644
index 0000000000000..a6ff6ca2ea4f7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/WriteNonexistentDeclaredInHigher.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal final val y: jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/kt782namespaceLevel.txt b/compiler/testData/lazyResolve/diagnostics/backingField/kt782namespaceLevel.txt
new file mode 100644
index 0000000000000..d9515e7f06817
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/kt782namespaceLevel.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt782">
+namespace kt782
+
+internal final val w: jet.Int
+internal final val x: jet.Int
+internal final val y: jet.Int
+internal final val z: jet.Int
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt782">
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedError.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedError.txt
new file mode 100644
index 0000000000000..e233c5d10460f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedError.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ c: java.util.Collection<jet.String>): java.util.List<jet.Int>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedFine.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedFine.txt
new file mode 100644
index 0000000000000..ee02aa3c317ba
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedFine.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ c: java.util.Collection<jet.String>): java.util.List<jet.String>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedStar.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedStar.txt
new file mode 100644
index 0000000000000..d874bb393cb18
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedStar.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): java.util.List<out jet.Any?>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedWarning.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedWarning.txt
new file mode 100644
index 0000000000000..1e2d05dd9b65e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedWarning.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ a: jet.Any): java.util.List<jet.String>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowParameterSubtype.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowParameterSubtype.txt
new file mode 100644
index 0000000000000..f1bdab4041f12
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowParameterSubtype.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+}
+internal final fun ff(/*0*/ l: java.util.Collection<B>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameClassParameter.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameClassParameter.txt
new file mode 100644
index 0000000000000..7b4c0b36f09ee
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameClassParameter.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: java.util.Collection<jet.String>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameParameterParameter.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameParameterParameter.txt
new file mode 100644
index 0000000000000..ba3c7fcfdbb4f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameParameterParameter.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>ff(/*0*/ l: java.util.Collection<T>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromAny.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromAny.txt
new file mode 100644
index 0000000000000..4341165e10b6e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromAny.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromOut.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromOut.txt
new file mode 100644
index 0000000000000..3f948ac78062c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromOut.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(/*0*/ a: java.util.List<out jet.Any>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedStar.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedStar.txt
new file mode 100644
index 0000000000000..4341165e10b6e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedStar.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsReified.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsReified.txt
new file mode 100644
index 0000000000000..2eb32c27524e9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsReified.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class MyList</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): MyList<T>
+}
+internal final fun ff(/*0*/ a: jet.Any): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsTraits.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsTraits.txt
new file mode 100644
index 0000000000000..cfc744366f722
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsTraits.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal abstract trait Aaa : jet.Any {
+}
+internal abstract trait Bbb : jet.Any {
+}
+internal final fun f(/*0*/ a: Aaa): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/WhenErasedDisallowFromAny.txt b/compiler/testData/lazyResolve/diagnostics/cast/WhenErasedDisallowFromAny.txt
new file mode 100644
index 0000000000000..41ac5a9791844
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/WhenErasedDisallowFromAny.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/checkArguments/SpreadVarargs.txt b/compiler/testData/lazyResolve/diagnostics/checkArguments/SpreadVarargs.txt
new file mode 100644
index 0000000000000..2aede08d6c1eb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/checkArguments/SpreadVarargs.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>array1(/*0*/ vararg a: T /*jet.Array<T>*/): jet.Array<T>
+internal final fun join(/*0*/ x: jet.Int, /*1*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.String
+internal final fun </*0*/ T : jet.Any?>joinG(/*0*/ x: jet.Int, /*1*/ vararg a: T /*jet.Array<T>*/): jet.String
+internal final fun </*0*/ T : jet.Any?>joinT(/*0*/ x: jet.Int, /*1*/ vararg a: T /*jet.Array<T>*/): T?
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1897_diagnostic_part.txt b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1897_diagnostic_part.txt
new file mode 100644
index 0000000000000..4dfebf0a558c1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1897_diagnostic_part.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun bar(): jet.Tuple0
+internal final fun foo(/*0*/ i: jet.Int, /*1*/ s: jet.String): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1940.txt b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1940.txt
new file mode 100644
index 0000000000000..15fdda13490c4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1940.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1940">
+namespace kt1940
+
+internal final fun foo(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="kt1940">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/checkInnerLocalDeclarations.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/checkInnerLocalDeclarations.txt
new file mode 100644
index 0000000000000..d80464c4c00d1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/checkInnerLocalDeclarations.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final fun test(): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1001.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1001.txt
new file mode 100644
index 0000000000000..9e3be45470a1f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1001.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="kt1001">
+namespace kt1001
+
+internal final fun doSmth(): jet.Tuple0
+internal final fun foo(/*0*/ c: jet.Array<jet.Int>): jet.Tuple0
+internal final fun t1(): jet.Int
+internal final fun t2(): jet.Int
+// </namespace name="kt1001">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1027.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1027.txt
new file mode 100644
index 0000000000000..19eaec93e3f2c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1027.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1027">
+namespace kt1027
+
+internal final fun doSmth(): jet.Tuple0
+internal final fun foo(/*0*/ c: java.util.List<jet.Int>): jet.Tuple0
+internal final fun t1(): jet.Tuple0
+internal final fun t2(): jet.Tuple0
+internal final fun t3(): jet.Tuple0
+internal final fun t4(): jet.Tuple0
+// </namespace name="kt1027">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1066.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1066.txt
new file mode 100644
index 0000000000000..48d46dc10628f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1066.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt1066">
+namespace kt1066
+
+internal final fun foo(/*0*/ excluded: java.util.Set<jet.Char>): jet.Tuple0
+internal final fun randomDigit(): jet.Char
+internal final fun test(): jet.Tuple0
+// </namespace name="kt1066">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1156.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1156.txt
new file mode 100644
index 0000000000000..126bba5106df4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1156.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(/*0*/ maybe: jet.Int?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1189.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1189.txt
new file mode 100644
index 0000000000000..9b42c984facbc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1189.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1189">
+namespace kt1189
+
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>java.util.concurrent.locks.ReentrantReadWriteLock.write(/*0*/ action: jet.Function0<T>): T
+// </namespace name="kt1189">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1191.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1191.txt
new file mode 100644
index 0000000000000..a2866ed58ebff
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1191.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt1191">
+namespace kt1191
+
+internal abstract trait kt1191.FunctionalList</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract val head: T
+ internal abstract val size: jet.Int
+ internal abstract val tail: kt1191.FunctionalList<T>
+}
+internal final fun foo(/*0*/ unused: jet.Int): kt1191.foo.<no name provided>
+internal final fun </*0*/ T : jet.Any?>kt1191.FunctionalList<T>.plus(/*0*/ element: T): kt1191.FunctionalList<T>
+// </namespace name="kt1191">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1219.1301.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1219.1301.txt
new file mode 100644
index 0000000000000..c31ca127afced
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1219.1301.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt1219">
+namespace kt1219
+
+internal final fun </*0*/ T : jet.Any?, /*1*/ R : jet.Any?>jet.Iterable<T>.fold(/*0*/ r: R, /*1*/ op: jet.Function2<T, R, R>): R
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.foreach(/*0*/ operation: jet.Function1<T, jet.Tuple0>): jet.Tuple0
+// </namespace name="kt1219">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1571.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1571.txt
new file mode 100644
index 0000000000000..6692c4cefc94a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1571.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="kt1571">
+namespace kt1571
+
+internal final class kt1571.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1571.A
+ internal final fun divAssign(/*0*/ a: jet.Int): jet.Tuple0
+ internal final var p: jet.Int
+ internal final fun times(/*0*/ a: jet.Int): kt1571.A
+}
+internal final val a: kt1571.A
+internal final var c0: jet.Int
+internal final var c1: jet.Int
+internal final var c2: jet.Int
+internal final fun box(): jet.String
+// </namespace name="kt1571">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1977.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1977.txt
new file mode 100644
index 0000000000000..83e25d8c5b42e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1977.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt1977">
+namespace kt1977
+
+internal final fun bar(): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun strToInt(/*0*/ s: jet.String): jet.Int?
+internal final fun test1(/*0*/ s: jet.String): jet.Int?
+internal final fun test2(/*0*/ s: jet.String): jet.Int?
+// </namespace name="kt1977">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2166_kt2103.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2166_kt2103.txt
new file mode 100644
index 0000000000000..7fa5bdcf469a0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2166_kt2103.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun bar(): jet.Boolean
+internal final fun foo(): jet.Int
+internal final fun foo1(): jet.Boolean
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2226.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2226.txt
new file mode 100644
index 0000000000000..8bb79a4d58fd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2226.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal abstract trait a.A : jet.Any {
+ internal abstract fun foo(): jet.Int
+}
+internal final class a.B : a.A {
+ public final /*constructor*/ fun <init>(): a.B
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal final fun foo(/*0*/ b: a.B): jet.Int
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt510.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt510.txt
new file mode 100644
index 0000000000000..fb0fa3888bc8b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt510.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="kt510">
+namespace kt510
+
+public open class kt510.Identifier1 : jet.Any {
+ public final /*constructor*/ fun <init>(): kt510.Identifier1
+ internal final var field: jet.Boolean
+}
+public open class kt510.Identifier2 : jet.Any {
+ public final /*constructor*/ fun <init>(): kt510.Identifier2
+ internal final var field: jet.Boolean
+}
+// </namespace name="kt510">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt607.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt607.txt
new file mode 100644
index 0000000000000..9515d48ad61a9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt607.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt607">
+namespace kt607
+
+internal final class kt607.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt607.A
+ internal final val z: jet.Int
+}
+internal final fun foo(/*0*/ a: kt607.A): jet.Tuple0
+// </namespace name="kt607">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt609.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt609.txt
new file mode 100644
index 0000000000000..1b4744bef6847
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt609.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="kt609">
+namespace kt609
+
+internal open class kt609.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt609.A
+ internal open fun foo(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final class kt609.B : kt609.A {
+ public final /*constructor*/ fun <init>(): kt609.B
+ internal final override /*1*/ fun foo(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final class kt609.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt609.C
+ internal final fun foo(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final fun test(/*0*/ a: jet.Int): jet.Tuple0
+// </namespace name="kt609">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt610.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt610.txt
new file mode 100644
index 0000000000000..7a6b92e126d7f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt610.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt610">
+namespace kt610
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt610">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt776.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt776.txt
new file mode 100644
index 0000000000000..71633ff4143c0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt776.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt776">
+namespace kt776
+
+internal final fun doSmth(): jet.Tuple0
+internal final fun test1(): jet.Int
+internal final fun test5(): jet.Int
+// </namespace name="kt776">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt843.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt843.txt
new file mode 100644
index 0000000000000..87c51c79675d0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt843.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt843">
+namespace kt843
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt843">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt897.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt897.txt
new file mode 100644
index 0000000000000..1976dac959d5a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt897.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt897">
+namespace kt897
+
+internal final class kt897.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt897.A
+ internal final val i: jet.Int?
+ internal final var j: jet.Int
+ internal final val k: jet.Int
+}
+// </namespace name="kt897">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/ForWithoutBraces.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/ForWithoutBraces.txt
new file mode 100644
index 0000000000000..4b34c64649ab4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/ForWithoutBraces.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt1075.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt1075.txt
new file mode 100644
index 0000000000000..c2f1c60e2241d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt1075.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt1075">
+namespace kt1075
+
+internal final fun foo(/*0*/ b: jet.String): jet.Tuple0
+// </namespace name="kt1075">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt657.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt657.txt
new file mode 100644
index 0000000000000..c6f81f06bd6fa
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt657.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt657">
+namespace kt657
+
+internal final fun cond1(): jet.Boolean
+internal final fun cond2(): jet.Boolean
+internal final fun foo(): jet.Int
+// </namespace name="kt657">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt770.kt351.kt735_StatementType.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt770.kt351.kt735_StatementType.txt
new file mode 100644
index 0000000000000..7558477069c93
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt770.kt351.kt735_StatementType.txt
@@ -0,0 +1,18 @@
+namespace <root>
+
+// <namespace name="kt770_351_735">
+namespace kt770_351_735
+
+internal final val w: [ERROR : Type for while (true) {}]
+internal final fun bar(/*0*/ a: jet.Tuple0): jet.Tuple0
+internal final fun box(): jet.Int
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun test1(): jet.Tuple0
+internal final fun test2(): jet.Tuple0
+internal final fun testCoercionToUnit(): jet.Tuple0
+internal final fun testImplicitCoercion(): jet.Tuple0
+internal final fun testStatementInExpressionContext(): jet.Tuple0
+internal final fun testStatementInExpressionContext2(): jet.Tuple0
+// </namespace name="kt770_351_735">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt786.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt786.txt
new file mode 100644
index 0000000000000..d8b1d7b1252b4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt786.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt786">
+namespace kt786
+
+internal final fun bar(): jet.Int
+internal final fun fff(): jet.Int
+internal final fun foo(): jet.Int
+// </namespace name="kt786">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt799.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt799.txt
new file mode 100644
index 0000000000000..5fc1c2a661e79
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt799.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt799">
+namespace kt799
+
+internal final val a: jet.Nothing
+internal final val b: jet.Nothing
+internal final val c: jet.Tuple0
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun f(/*0*/ mi: jet.Int = ?): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="kt799">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/tryReturnType.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/tryReturnType.txt
new file mode 100644
index 0000000000000..a251051b5f200
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/tryReturnType.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun bar(): jet.Int
+internal final fun doSmth(): jet.Tuple0
+internal final fun foo(): jet.Int
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/when.kt234.kt973.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/when.kt234.kt973.txt
new file mode 100644
index 0000000000000..ee3bfcd083797
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/when.kt234.kt973.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="kt234_kt973">
+namespace kt234_kt973
+
+internal final fun foo3(/*0*/ x: jet.Int): jet.Int
+internal final fun foo4(/*0*/ x: jet.Int): jet.Int
+internal final fun t1(/*0*/ x: jet.Int): jet.Int
+internal final fun t2(/*0*/ x: jet.Int): jet.Int
+internal final fun t3(/*0*/ x: jet.Int): jet.Int
+internal final fun t4(/*0*/ x: jet.Int): jet.Int
+internal final fun t5(/*0*/ x: jet.Int): jet.Int
+internal final fun test(/*0*/ t: jet.Tuple2<out jet.Int, out jet.Int>): jet.Int
+internal final fun test1(/*0*/ t: jet.Tuple2<out jet.Int, out jet.Int>): jet.Int
+// </namespace name="kt234_kt973">
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlow/CalleeExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlow/CalleeExpression.txt
new file mode 100644
index 0000000000000..ce49ca5e9f829
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlow/CalleeExpression.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ f: jet.Function0<jet.Tuple0>): C
+ internal final val f: jet.Function0<jet.Tuple0>
+}
+internal final fun test(/*0*/ e: jet.Any): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlow/TupleExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlow/TupleExpression.txt
new file mode 100644
index 0000000000000..793a6551f3e1d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlow/TupleExpression.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ f: jet.Int): C
+ internal final val f: jet.Int
+}
+internal final fun test(/*0*/ e: jet.Any): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlow/WhenSubject.txt b/compiler/testData/lazyResolve/diagnostics/dataFlow/WhenSubject.txt
new file mode 100644
index 0000000000000..1f96cc7fb1d72
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlow/WhenSubject.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class BinOp : Expr {
+ public final /*constructor*/ fun <init>(/*0*/ operator: jet.String): BinOp
+ internal final val operator: jet.String
+}
+internal abstract trait Expr : jet.Any {
+}
+internal final fun test(/*0*/ e: Expr): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/AndOr.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/AndOr.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/AndOr.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ArrayAccess.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ArrayAccess.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ArrayAccess.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/BinaryExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/BinaryExpression.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/BinaryExpression.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DeepIf.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DeepIf.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DeepIf.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DoWhile.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DoWhile.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DoWhile.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Elvis.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Elvis.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Elvis.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ExclExcl.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ExclExcl.txt
new file mode 100644
index 0000000000000..9af818d67606b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ExclExcl.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun f1(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f2(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f3(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f4(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f5(/*0*/ x: jet.Int?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/For.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/For.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/For.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/FunctionLiteral.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/FunctionLiteral.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/FunctionLiteral.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElse.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElse.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElse.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElseBothInvalid.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElseBothInvalid.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElseBothInvalid.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ObjectExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ObjectExpression.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ObjectExpression.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/QualifiedExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/QualifiedExpression.txt
new file mode 100644
index 0000000000000..1794133d26608
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/QualifiedExpression.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun bar(/*0*/ x: jet.Int): jet.Int
+}
+internal final fun baz(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Return.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Return.txt
new file mode 100644
index 0000000000000..b1c73ed1c32df
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Return.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ThisSuper.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ThisSuper.txt
new file mode 100644
index 0000000000000..314550ba790ea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ThisSuper.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal open class Base : jet.Any {
+ public final /*constructor*/ fun <init>(): Base
+ internal final fun bar(/*0*/ x: jet.Int): jet.Int
+}
+internal final class Derived : Base {
+ public final /*constructor*/ fun <init>(): Derived
+ internal final override /*1*/ fun bar(/*0*/ x: jet.Int): jet.Int
+ internal final fun baz(/*0*/ x: jet.Int): jet.Int
+ internal final fun foo(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Throw.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Throw.txt
new file mode 100644
index 0000000000000..12260238f47c4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Throw.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): java.lang.RuntimeException
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/TryCatch.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/TryCatch.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/TryCatch.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/UnaryExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/UnaryExpression.txt
new file mode 100644
index 0000000000000..11a348b2d0177
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/UnaryExpression.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun baz(/*0*/ b: jet.Boolean): jet.Boolean
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/When.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/When.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/When.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/While.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/While.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/While.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt1141.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt1141.txt
new file mode 100644
index 0000000000000..ac30d56821411
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt1141.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt1141">
+namespace kt1141
+
+internal final class kt1141.C : kt1141.SomeTrait {
+ public final /*constructor*/ fun <init>(): kt1141.C
+ internal abstract override /*1*/ fun foo(): jet.Tuple0
+}
+public abstract trait kt1141.SomeTrait : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
+internal final val Rr: kt1141.Rr
+internal final fun foo(): jet.Tuple0
+internal final fun foo2(): jet.Tuple0
+// </namespace name="kt1141">
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2096.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2096.txt
new file mode 100644
index 0000000000000..ad7d211adaa89
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2096.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal abstract class c.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): c.Foo
+ protected abstract val prop: [ERROR : No type, no body]
+}
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2142.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2142.txt
new file mode 100644
index 0000000000000..f09c4dce1a220
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2142.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt559.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt559.txt
new file mode 100644
index 0000000000000..0426640aa1697
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt559.txt
@@ -0,0 +1,31 @@
+namespace <root>
+
+// <namespace name="kt559">
+namespace kt559
+
+internal abstract class kt559.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt559.A
+ internal final fun fff(): jet.Tuple0
+ internal abstract fun foo(): jet.Int
+ internal abstract val i: jet.Int
+}
+internal final class kt559.B : kt559.A {
+ public final /*constructor*/ fun <init>(): kt559.B
+ internal final override /*1*/ fun fff(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Int
+ internal abstract override /*1*/ val i: jet.Int
+}
+internal final class kt559.C : kt559.D {
+ public final /*constructor*/ fun <init>(): kt559.C
+ internal final override /*1*/ fun fff(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Int
+ internal open override /*1*/ val i: jet.Int
+ internal final fun test(): jet.Tuple0
+}
+internal abstract class kt559.D : kt559.A {
+ public final /*constructor*/ fun <init>(): kt559.D
+ internal final override /*1*/ fun fff(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Int
+ internal open override /*1*/ val i: jet.Int
+}
+// </namespace name="kt559">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionFunctions.txt b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionFunctions.txt
new file mode 100644
index 0000000000000..d65323c776003
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionFunctions.txt
@@ -0,0 +1,32 @@
+namespace <root>
+
+// <namespace name="outer">
+namespace outer
+
+internal final class outer.A : jet.Any {
+ public final /*constructor*/ fun <init>(): outer.A
+}
+internal final val jet.Int.abs: jet.Int
+internal final val </*0*/ T : jet.Any?> T.foo: T
+internal final val jet.Int?.optval: jet.Tuple0
+internal final fun </*0*/ T : jet.Any?, /*1*/ E : jet.Any?>T.foo(/*0*/ x: E, /*1*/ y: outer.A): T
+internal final fun jet.Int.foo(): jet.Int
+internal final fun </*0*/ T : jet.Any?>T.minus(/*0*/ t: T): jet.Int
+internal final fun jet.Int?.optint(): jet.Tuple0
+internal final fun outer.A.plus(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun outer.A.plus(/*0*/ a: jet.Int): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="outer">
+// <namespace name="null_safety">
+namespace null_safety
+
+internal final class null_safety.Command : jet.Any {
+ public final /*constructor*/ fun <init>(): null_safety.Command
+ internal final val foo: jet.Int
+}
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun jet.Any?.equals1(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun jet.Any.equals2(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun parse(/*0*/ cmd: jet.String): null_safety.Command?
+// </namespace name="null_safety">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionsCalledOnSuper.txt b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionsCalledOnSuper.txt
new file mode 100644
index 0000000000000..3650673a33a29
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionsCalledOnSuper.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal final class C : T {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun buzz(): jet.Tuple0
+ internal open override /*1*/ fun buzz1(/*0*/ i: jet.Int): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+}
+internal abstract trait T : jet.Any {
+ internal open fun buzz(): jet.Tuple0
+ internal open fun buzz1(/*0*/ i: jet.Int): jet.Tuple0
+ internal open fun foo(): jet.Tuple0
+}
+internal final fun T.bar(): jet.Tuple0
+internal final fun T.buzz(): jet.Tuple0
+internal final fun T.buzz1(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator.txt b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator.txt
new file mode 100644
index 0000000000000..f173ad02b8f87
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any>T?.iterator(): iterator.<no name provided>
+internal final fun </*0*/ T : jet.Any?>java.util.Enumeration<T>.iterator(): iterator.<no name provided>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator2.txt b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator2.txt
new file mode 100644
index 0000000000000..b4ec6b67f35e9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator2.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun a(/*0*/ e: java.util.Enumeration<jet.Int>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>java.util.Enumeration<T>.iterator(): iterator.<no name provided>
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/kt1875.txt b/compiler/testData/lazyResolve/diagnostics/extensions/kt1875.txt
new file mode 100644
index 0000000000000..2e03bdb4152cc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/kt1875.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1875">
+namespace kt1875
+
+internal abstract trait kt1875.T : jet.Any {
+ internal abstract val f: jet.Function1<jet.Int, jet.Tuple0>?
+}
+internal final fun f(/*0*/ a: jet.Int?, /*1*/ b: jet.ExtensionFunction1<jet.Int, jet.Int, jet.Int>): jet.Int?
+internal final fun test(/*0*/ t: kt1875.T): jet.Tuple0
+internal final fun test1(/*0*/ t: kt1875.T?): jet.Tuple0
+// </namespace name="kt1875">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/kt2317.txt b/compiler/testData/lazyResolve/diagnostics/extensions/kt2317.txt
new file mode 100644
index 0000000000000..f73a9f2c24f3d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/kt2317.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="kt2317">
+namespace kt2317
+
+internal final fun jet.Any?.bar(): jet.Tuple0
+internal final fun jet.Any?.baz(): jet.Int
+internal final fun foo(/*0*/ l: jet.Long?): jet.Int?
+internal final fun quux(/*0*/ x: jet.Int?): jet.Tuple0
+// </namespace name="kt2317">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/kt819ExtensionProperties.txt b/compiler/testData/lazyResolve/diagnostics/extensions/kt819ExtensionProperties.txt
new file mode 100644
index 0000000000000..877ed049f4dab
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/kt819ExtensionProperties.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal open fun jet.Int.foo(): jet.Tuple0
+ internal open val jet.Int.foo: jet.Int
+ internal open fun jet.String.foo(): jet.Tuple0
+ internal open val jet.String.foo: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun jet.Int.foo(): jet.Tuple0
+ internal open override /*1*/ val jet.Int.foo: jet.Int
+ internal open override /*1*/ fun jet.String.foo(): jet.Tuple0
+ internal open override /*1*/ val jet.String.foo: jet.Int
+ internal final fun use(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final val java.io.InputStream.buffered: java.io.BufferedInputStream
+internal final val java.io.Reader.buffered: java.io.BufferedReader
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/Projections.txt b/compiler/testData/lazyResolve/diagnostics/generics/Projections.txt
new file mode 100644
index 0000000000000..a323465fdb0ce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/Projections.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+internal final class In</*0*/ in T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ in T : jet.Any?><init>(): In<T>
+ internal final fun f(/*0*/ t: T): jet.Tuple0
+ internal final fun f(/*0*/ t: jet.Int): jet.Int
+ internal final fun f1(/*0*/ t: T): jet.Tuple0
+}
+internal final class Inv</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): Inv<T>
+ internal final fun f(/*0*/ t: T): T
+ internal final fun inf(/*0*/ t: T): jet.Tuple0
+ internal final fun outf(): T
+}
+internal final class Out</*0*/ out T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ out T : jet.Any?><init>(): Out<T>
+ internal final fun f(): T
+ internal final fun f(/*0*/ a: jet.Int): jet.Int
+}
+internal final fun testInOut(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundCheck.txt b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundCheck.txt
new file mode 100644
index 0000000000000..a6c9123ef914a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundCheck.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class C</*0*/ T : C<T>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : C<T>><init>(): C<T>
+}
+internal final class TestFail : C<C<TestFail>> {
+ public final /*constructor*/ fun <init>(): TestFail
+}
+internal final class TestOK : C<TestOK> {
+ public final /*constructor*/ fun <init>(): TestOK
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundWithTwoArguments.txt b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundWithTwoArguments.txt
new file mode 100644
index 0000000000000..94876dfa4ca1b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundWithTwoArguments.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class D</*0*/ A : D<A, jet.String>, /*1*/ B : D<A, B>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ A : D<A, jet.String>, /*1*/ B : D<A, B>><init>(): D<A, B>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Class.txt b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Class.txt
new file mode 100644
index 0000000000000..f6f869157ef13
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Class.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class C</*0*/ T : C<T>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : C<T>><init>(): C<T>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/kt1575-ClassObject.txt b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-ClassObject.txt
new file mode 100644
index 0000000000000..5afc6944ac6e6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-ClassObject.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class CO</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): CO<T>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Function.txt b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Function.txt
new file mode 100644
index 0000000000000..42516ea3bdc97
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Function.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class C</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): C<T>
+}
+internal final fun </*0*/ T : C<T>>foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/arrayBracketsRange.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/arrayBracketsRange.txt
new file mode 100644
index 0000000000000..95c1f1a60ff5e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/arrayBracketsRange.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="b">
+namespace b
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/checkBackingFieldException.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/checkBackingFieldException.txt
new file mode 100644
index 0000000000000..267fa8fd9bcc3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/checkBackingFieldException.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="h">
+namespace h
+
+internal final class h.Square : jet.Any {
+ public final /*constructor*/ fun <init>(): h.Square
+ internal final var area: jet.Double private set
+ internal final var size: jet.Double
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="h">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/funEquals.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/funEquals.txt
new file mode 100644
index 0000000000000..3ed5be51eb58d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/funEquals.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(): [ERROR : No type, no body]
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteVal.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteVal.txt
new file mode 100644
index 0000000000000..e0371f27491df
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteVal.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final val i: [ERROR : No type, no body]
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteValWithAccessor.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteValWithAccessor.txt
new file mode 100644
index 0000000000000..151368993ca6d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteValWithAccessor.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final val i: jet.String
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteWhen.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteWhen.txt
new file mode 100644
index 0000000000000..bc2eac646d41d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteWhen.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(/*0*/ a: jet.Any): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/namedFun.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/namedFun.txt
new file mode 100644
index 0000000000000..6789f8ae8f80f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/namedFun.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun bar(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/incompleteAssignment.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/incompleteAssignment.txt
new file mode 100644
index 0000000000000..07e455fd78a4a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/incompleteAssignment.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="sum">
+namespace sum
+
+internal final fun </*0*/ T : jet.Any?>assertEquals(/*0*/ actual: T?, /*1*/ expected: T?, /*2*/ message: jet.Any? = ?): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun sum(/*0*/ a: jet.IntArray): jet.Int
+internal final fun test(/*0*/ expectedSum: jet.Int, /*1*/ vararg data: jet.Int /*jet.IntArray*/): jet.Tuple0
+// </namespace name="sum">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt1955.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt1955.txt
new file mode 100644
index 0000000000000..ca6901ec7cba0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt1955.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="b">
+namespace b
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt2014.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt2014.txt
new file mode 100644
index 0000000000000..3b79ea2e6dc75
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt2014.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final class c.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): c.Foo
+ internal final val a: jet.Int
+ internal final fun bar(/*0*/ i: jet.Int): jet.Int
+ internal final fun prop(): jet.Int
+}
+internal final val R: c.R
+internal final fun x(/*0*/ f: c.Foo): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/plusOnTheRight.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/plusOnTheRight.txt
new file mode 100644
index 0000000000000..3a36d1927325f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/plusOnTheRight.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.MyClass1 : jet.Any {
+ public final /*constructor*/ fun <init>(): a.MyClass1
+ public final fun plus(): jet.Tuple0
+}
+internal final fun main(/*0*/ arg: a.MyClass1): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/pseudocodeTraverseNextInstructions.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/pseudocodeTraverseNextInstructions.txt
new file mode 100644
index 0000000000000..ca6901ec7cba0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/pseudocodeTraverseNextInstructions.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="b">
+namespace b
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/senselessComparisonWithNull.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/senselessComparisonWithNull.txt
new file mode 100644
index 0000000000000..0bcc99a0c816e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/senselessComparisonWithNull.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="d">
+namespace d
+
+internal final fun foo(/*0*/ a: jet.IntArray): jet.Tuple0
+// </namespace name="d">
diff --git a/compiler/testData/lazyResolve/diagnostics/inference/NoInferenceFromDeclaredBounds.txt b/compiler/testData/lazyResolve/diagnostics/inference/NoInferenceFromDeclaredBounds.txt
new file mode 100644
index 0000000000000..3ee17563fd3fb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/inference/NoInferenceFromDeclaredBounds.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final val n: jet.Nothing
+internal final fun foo1(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>fooT22(): T?
diff --git a/compiler/testData/lazyResolve/diagnostics/inference/kt1293.txt b/compiler/testData/lazyResolve/diagnostics/inference/kt1293.txt
new file mode 100644
index 0000000000000..53a80612617f8
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/inference/kt1293.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1293">
+namespace kt1293
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun requiresInt(/*0*/ i: jet.Int): jet.Tuple0
+// </namespace name="kt1293">
diff --git a/compiler/testData/lazyResolve/diagnostics/infos/Autocasts.txt b/compiler/testData/lazyResolve/diagnostics/infos/Autocasts.txt
new file mode 100644
index 0000000000000..cb71a027ad8e5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/infos/Autocasts.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun foo(): jet.Tuple0
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal final fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+}
+internal final class C : A {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+}
+internal final fun declarationInsidePattern(/*0*/ x: jet.Tuple2<out jet.Any, out jet.Any>): jet.String
+internal final fun declarations(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun f(): jet.String
+internal final fun f10(/*0*/ init: A?): jet.Tuple0
+internal final fun f101(/*0*/ a: A?): jet.Tuple0
+internal final fun f11(/*0*/ a: A?): jet.Tuple0
+internal final fun f12(/*0*/ a: A?): jet.Tuple0
+internal final fun f13(/*0*/ a: A?): jet.Tuple0
+internal final fun f14(/*0*/ a: A?): jet.Tuple0
+internal final fun f15(/*0*/ a: A?): jet.Tuple0
+internal final fun f9(/*0*/ init: A?): jet.Tuple0
+internal final fun foo(/*0*/ a: jet.Any): jet.Int
+internal final fun getStringLength(/*0*/ obj: jet.Any): jet.Char?
+internal final fun illegalTupleReturnType(/*0*/ a: jet.Any): jet.Tuple2<out jet.Any, out jet.String>
+internal final fun illegalWhenBlock(/*0*/ a: jet.Any): jet.Int
+internal final fun illegalWhenBody(/*0*/ a: jet.Any): jet.Int
+internal final fun mergeAutocasts(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun returnFunctionLiteral(/*0*/ a: jet.Any?): jet.Function0<jet.Int>
+internal final fun returnFunctionLiteralBlock(/*0*/ a: jet.Any?): jet.Function0<jet.Int>
+internal final fun toInt(/*0*/ i: jet.Int?): jet.Int
+internal final fun tuples(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun vars(/*0*/ a: jet.Any?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/infos/PropertiesWithBackingFields.txt b/compiler/testData/lazyResolve/diagnostics/infos/PropertiesWithBackingFields.txt
new file mode 100644
index 0000000000000..d1c732f4f13e0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/infos/PropertiesWithBackingFields.txt
@@ -0,0 +1,46 @@
+namespace <root>
+
+internal open class Super : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int): Super
+}
+internal abstract class Test : jet.Any {
+ public final /*constructor*/ fun <init>(): Test
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+ internal final val c1: jet.Int
+ internal final val c2: jet.Int
+ internal final val c3: jet.Int
+ internal final val c4: jet.Int
+ internal final val c5: jet.Int
+ internal final val c: jet.Int
+ internal final var v10: jet.Int
+ internal abstract val v11: jet.Int
+ internal abstract var v12: jet.Int
+ internal final var v1: jet.Int
+ internal final var v2: jet.Int
+ internal final var v3: jet.Int
+ internal final var v4: jet.Int
+ internal final var v5: jet.Int
+ internal final var v6: jet.Int
+ internal abstract val v7: jet.Int
+ internal abstract var v8: jet.Int
+ internal final var v9: jet.Int
+ internal final var v: jet.Int
+ internal abstract val x1: jet.Int
+ internal abstract val x2: jet.Int
+ internal abstract val x: jet.Int
+ internal abstract var y1: jet.Int
+ internal abstract var y2: jet.Int
+ internal abstract var y3: jet.Int
+ internal abstract var y4: jet.Int
+ internal abstract var y5: jet.Int
+ internal abstract var y6: jet.Int
+ internal abstract var y: jet.Int
+}
+internal final class TestPCParameters : Super {
+ public final /*constructor*/ fun <init>(/*0*/ w: jet.Int, /*1*/ x: jet.Int, /*2*/ y: jet.Int, /*3*/ z: jet.Int): TestPCParameters
+ internal final fun foo(): [ERROR : Error function type]
+ internal final val xx: jet.Int
+ internal final val y: jet.Int
+ internal final var z: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/OverrideVararg.txt b/compiler/testData/lazyResolve/diagnostics/j+k/OverrideVararg.txt
new file mode 100644
index 0000000000000..189d3c78eadc7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/OverrideVararg.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+public abstract class Aaa : java.lang.Object {
+ public final /*constructor*/ fun <init>(): Aaa
+ public abstract fun foo(/*0*/ vararg args: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
+internal final class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ public open override /*1*/ fun foo(/*0*/ vararg args: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/StaticMembersFromSuperclasses.txt b/compiler/testData/lazyResolve/diagnostics/j+k/StaticMembersFromSuperclasses.txt
new file mode 100644
index 0000000000000..57726bf42fcf7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/StaticMembersFromSuperclasses.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+public open class Aaa : java.lang.Object {
+ public final /*constructor*/ fun <init>(): Aaa
+}
+public open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+}
+internal final fun foo(): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-SpecialTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-SpecialTypes.txt
new file mode 100644
index 0000000000000..e6e67c4233ef3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-SpecialTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun barN(/*0*/ a: T): jet.Tuple0
+ package open fun fooN(): T
+}
+public open class Y : X<jet.String> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun barN(/*0*/ a: jet.String): jet.Tuple0
+ package open override /*1*/ fun fooN(): jet.String
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-UserTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-UserTypes.txt
new file mode 100644
index 0000000000000..22612bdce8418
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-UserTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun barN(/*0*/ a: T): jet.Tuple0
+ package open fun fooN(): T
+}
+public open class Y : X<A> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun barN(/*0*/ a: A): jet.Tuple0
+ package open override /*1*/ fun fooN(): A
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-SpecialTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-SpecialTypes.txt
new file mode 100644
index 0000000000000..06d09f0466b3d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-SpecialTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun bar(/*0*/ a: T?): jet.Tuple0
+ package open fun foo(): T?
+}
+public open class Y : X<jet.String> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun bar(/*0*/ a: jet.String?): jet.Tuple0
+ package open override /*1*/ fun foo(): jet.String?
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-UserTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-UserTypes.txt
new file mode 100644
index 0000000000000..c0645c7f2224a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-UserTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun bar(/*0*/ a: T?): jet.Tuple0
+ package open fun foo(): T?
+}
+public open class Y : X<A> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun bar(/*0*/ a: A?): jet.Tuple0
+ package open override /*1*/ fun foo(): A?
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListAndMap.txt b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListAndMap.txt
new file mode 100644
index 0000000000000..0aad809dfb8b1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListAndMap.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kotlin1">
+namespace kotlin1
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun test(/*0*/ a: java.util.List<jet.Int>, /*1*/ m: java.util.Map<jet.String, jet.Int>): jet.Tuple0
+// </namespace name="kotlin1">
diff --git a/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListClone.txt b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListClone.txt
new file mode 100644
index 0000000000000..1bc597a31a8d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListClone.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kotlin1">
+namespace kotlin1
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kotlin1">
diff --git a/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListToArray.txt b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListToArray.txt
new file mode 100644
index 0000000000000..1bc597a31a8d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListToArray.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kotlin1">
+namespace kotlin1
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kotlin1">
diff --git a/compiler/testData/lazyResolve/diagnostics/library/kt828.txt b/compiler/testData/lazyResolve/diagnostics/library/kt828.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/library/kt828.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/AssertNotNull.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/AssertNotNull.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/AssertNotNull.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/InfixCallNullability.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/InfixCallNullability.txt
new file mode 100644
index 0000000000000..8e877cf97c3bc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/InfixCallNullability.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun contains(/*0*/ a: jet.Any?): jet.Boolean
+ internal final fun minus(): jet.Tuple0
+ internal final fun plus(/*0*/ i: jet.Int): jet.Tuple0
+}
+internal final fun A.div(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun test(/*0*/ x: jet.Int?, /*1*/ a: A?): jet.Tuple0
+internal final fun A?.times(/*0*/ i: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/NullableNothingIsExactlyNull.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/NullableNothingIsExactlyNull.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/NullableNothingIsExactlyNull.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/PreferExtensionsOnNullableReceiver.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/PreferExtensionsOnNullableReceiver.txt
new file mode 100644
index 0000000000000..fbae1cecec9be
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/PreferExtensionsOnNullableReceiver.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun jet.Any?.foo(): jet.Tuple0
+internal final fun test(/*0*/ f: Foo?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/QualifiedExpressionNullability.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/QualifiedExpressionNullability.txt
new file mode 100644
index 0000000000000..6eb0e520c461f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/QualifiedExpressionNullability.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ internal final fun foo(/*0*/ a: Foo): Foo
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/ReceiverNullability.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/ReceiverNullability.txt
new file mode 100644
index 0000000000000..1e7b0cb167619
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/ReceiverNullability.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun A.bar(): jet.Tuple0
+internal final fun A?.buzz(): jet.Tuple0
+internal final fun test(/*0*/ a: A?): jet.Tuple0
+internal final fun A.test2(): jet.Tuple0
+internal final fun A?.test3(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/funcLiteralArgsInsideUnresolvedFunction.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/funcLiteralArgsInsideUnresolvedFunction.txt
new file mode 100644
index 0000000000000..f09c4dce1a220
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/funcLiteralArgsInsideUnresolvedFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1270.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1270.txt
new file mode 100644
index 0000000000000..0987b0c6178c7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1270.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt1270">
+namespace kt1270
+
+private final class kt1270.SomeClass : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1270.SomeClass
+ internal final val value: jet.Int
+}
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt1270">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1680.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1680.txt
new file mode 100644
index 0000000000000..c02b697d9c723
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1680.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt1680">
+namespace kt1680
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt1680">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1778.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1778.txt
new file mode 100644
index 0000000000000..0051c85e82945
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1778.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt1778">
+namespace kt1778
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt1778">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2109.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2109.txt
new file mode 100644
index 0000000000000..fbd0b5234342f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2109.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt2109">
+namespace kt2109
+
+internal final class kt2109.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt2109.A
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun kt2109.A?.bar(): jet.Tuple0
+internal final fun kt2109.A.baz(): jet.Tuple0
+// </namespace name="kt2109">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2125.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2125.txt
new file mode 100644
index 0000000000000..517ad563608db
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2125.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="e">
+namespace e
+
+internal final fun main(): jet.Tuple0
+// </namespace name="e">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2146.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2146.txt
new file mode 100644
index 0000000000000..c23acec5508a7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2146.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt2146">
+namespace kt2146
+
+internal final fun f1(/*0*/ s: jet.Int?): jet.Int
+internal final fun f2(/*0*/ s: jet.Int?): jet.Int
+internal final fun f3(/*0*/ s: jet.Int?): jet.Int
+internal final fun f4(/*0*/ s: jet.Int?): jet.Int
+internal final fun f5(/*0*/ s: jet.Int?): jet.Int
+internal final fun f6(/*0*/ s: jet.Int?): jet.Int
+internal final fun f7(/*0*/ s: jet.Int?): jet.Int
+// </namespace name="kt2146">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2164.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2164.txt
new file mode 100644
index 0000000000000..781130097a8de
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2164.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt2164">
+namespace kt2164
+
+internal final fun foo(/*0*/ x: jet.Int): jet.Int
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt2164">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2176.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2176.txt
new file mode 100644
index 0000000000000..7ec2e1d1bd499
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2176.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt2176">
+namespace kt2176
+
+internal final fun f1(/*0*/ a: jet.String?): jet.Tuple0
+internal final fun f2(/*0*/ a: jet.String): jet.Tuple0
+internal final fun f3(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun f4(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun f5(/*0*/ a: jet.String): jet.Tuple0
+// </namespace name="kt2176">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2195.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2195.txt
new file mode 100644
index 0000000000000..ff237fac1cf17
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2195.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+private final fun </*0*/ T : jet.Any?>sendCommand(/*0*/ errorCallback: jet.Function0<jet.Tuple0>? = ?): jet.Tuple0
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2212.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2212.txt
new file mode 100644
index 0000000000000..5f80ce6a9e57f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2212.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt2212">
+namespace kt2212
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt2212">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2216.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2216.txt
new file mode 100644
index 0000000000000..cd5bbc37a1c2f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2216.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt2216">
+namespace kt2216
+
+internal final fun bar(/*0*/ y: jet.Int, /*1*/ z: jet.Int): jet.Int
+internal final fun baz(/*0*/ a: jet.Int, /*1*/ b: jet.Int, /*2*/ c: jet.Int, /*3*/ d: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt2216">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2223.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2223.txt
new file mode 100644
index 0000000000000..4064d3443d8d5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2223.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt2223">
+namespace kt2223
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt2223">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2234.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2234.txt
new file mode 100644
index 0000000000000..bd37813b0997b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2234.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt244.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt244.txt
new file mode 100644
index 0000000000000..5934e1aa9b488
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt244.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt244">
+namespace kt244
+
+internal final class kt244.A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ a: jet.String?): kt244.A
+ internal final val b: jet.Int
+ internal final val i: jet.Int
+}
+internal final fun f(/*0*/ s: jet.String?): jet.Tuple0
+// </namespace name="kt244">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt362.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt362.txt
new file mode 100644
index 0000000000000..f852a63f2f04e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt362.txt
@@ -0,0 +1,23 @@
+namespace <root>
+
+// <namespace name="example">
+namespace example
+
+internal final fun test(): jet.Tuple0
+// </namespace name="example">
+// <namespace name="test">
+namespace test
+
+internal final class test.Internal : jet.Any {
+ public final val public: jet.Int?
+ protected final val protected: jet.Int?
+ internal final val internal: jet.Int?
+ public final /*constructor*/ fun <init>(): test.Internal
+}
+public final class test.Public : jet.Any {
+ public final val public: jet.Int?
+ protected final val protected: jet.Int?
+ internal final val internal: jet.Int?
+ public final /*constructor*/ fun <init>(): test.Public
+}
+// </namespace name="test">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/Objects.txt b/compiler/testData/lazyResolve/diagnostics/objects/Objects.txt
new file mode 100644
index 0000000000000..4439d3ed6cdf0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/Objects.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="toplevelObjectDeclarations">
+namespace toplevelObjectDeclarations
+
+internal open class toplevelObjectDeclarations.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ y: jet.Int): toplevelObjectDeclarations.Foo
+ internal open fun foo(): jet.Int
+}
+internal final class toplevelObjectDeclarations.T : toplevelObjectDeclarations.Foo {
+ public final /*constructor*/ fun <init>(): toplevelObjectDeclarations.T
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal final val A: toplevelObjectDeclarations.A
+internal final val B: toplevelObjectDeclarations.B
+internal final val x: jet.Int
+internal final val y: toplevelObjectDeclarations.<no name provided>
+internal final val z: jet.Int
+// </namespace name="toplevelObjectDeclarations">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/ObjectsInheritance.txt b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsInheritance.txt
new file mode 100644
index 0000000000000..55f2510996fcf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsInheritance.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="toplevelObjectDeclarations">
+namespace toplevelObjectDeclarations
+
+internal final val CObj: toplevelObjectDeclarations.CObj
+internal final val DOjb: toplevelObjectDeclarations.DOjb
+// </namespace name="toplevelObjectDeclarations">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/ObjectsLocal.txt b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsLocal.txt
new file mode 100644
index 0000000000000..a3d8c4efaf419
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsLocal.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="localObjects">
+namespace localObjects
+
+internal open class localObjects.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): localObjects.Foo
+ internal final fun foo(): jet.Int
+}
+internal final val A: localObjects.A
+internal final val bb: [ERROR : <ERROR FUNCTION RETURN TYPE>]
+internal final fun test(): jet.Tuple0
+// </namespace name="localObjects">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/ObjectsNested.txt b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsNested.txt
new file mode 100644
index 0000000000000..8bbf7d09cd85c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsNested.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="nestedObejcts">
+namespace nestedObejcts
+
+internal final val A: nestedObejcts.A
+internal final val B: nestedObejcts.B
+internal final val a: nestedObejcts.A
+internal final val b: nestedObejcts.B
+internal final val c: nestedObejcts.A.B
+internal final val d: nestedObejcts.A.B.A
+internal final val e: [ERROR : <ERROR PROPERTY TYPE>]
+// </namespace name="nestedObejcts">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/kt2240.txt b/compiler/testData/lazyResolve/diagnostics/objects/kt2240.txt
new file mode 100644
index 0000000000000..880ac59f2ce1a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/kt2240.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.A : jet.Any {
+ public final /*constructor*/ fun <init>(): a.A
+}
+internal final val o: a.<no name provided>
+internal final fun </*0*/ T : jet.Any?>a.A.foo(/*0*/ f: T): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/AssignOperatorAmbiguity.txt b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/AssignOperatorAmbiguity.txt
new file mode 100644
index 0000000000000..7ad0e047ef8cf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/AssignOperatorAmbiguity.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt1820">
+namespace kt1820
+
+internal final class kt1820.MyInt : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int): kt1820.MyInt
+ internal final val i: jet.Int
+ internal final fun plus(/*0*/ m: kt1820.MyInt): kt1820.MyInt
+}
+internal final fun jet.Any.plusAssign(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun test(/*0*/ m: kt1820.MyInt): jet.Tuple0
+// </namespace name="kt1820">
diff --git a/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/IteratorAmbiguity.txt b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/IteratorAmbiguity.txt
new file mode 100644
index 0000000000000..c6615a95f13fe
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/IteratorAmbiguity.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+internal abstract trait MyAnotherCollectionInterface : jet.Any {
+}
+internal final class MyCollection : MyCollectionInterface, MyAnotherCollectionInterface {
+ public final /*constructor*/ fun <init>(): MyCollection
+}
+internal abstract trait MyCollectionInterface : jet.Any {
+}
+internal final class MyElement : jet.Any {
+ public final /*constructor*/ fun <init>(): MyElement
+}
+internal final class MyIterator : jet.Any {
+ public final /*constructor*/ fun <init>(): MyIterator
+ internal final fun hasNext(): jet.Boolean
+ internal final fun next(): MyElement
+}
+internal final fun MyAnotherCollectionInterface.iterator(): MyIterator
+internal final fun MyCollectionInterface.iterator(): MyIterator
+internal final fun test1(/*0*/ collection: MyCollection): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/kt1028.txt b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/kt1028.txt
new file mode 100644
index 0000000000000..c0d78048d7742
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/kt1028.txt
@@ -0,0 +1,26 @@
+namespace <root>
+
+// <namespace name="kt1028">
+namespace kt1028
+
+internal final class kt1028.Control : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1028.Control
+ public final val MouseMoved: kt1028.event<kt1028.MouseMovedEventArgs>
+ internal final fun MoveMouse(): jet.Tuple0
+}
+internal final class kt1028.MouseMovedEventArgs : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1028.MouseMovedEventArgs
+ public final val X: jet.Int
+}
+internal final class kt1028.Test : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1028.Test
+ internal final fun test(): jet.Tuple0
+}
+internal final class kt1028.event</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): kt1028.event<T>
+ internal final fun call(/*0*/ value: T): jet.Tuple0
+ internal final val callbacks: java.util.ArrayList<jet.Function1<T, jet.Tuple0>>
+ internal final fun minusAssign(/*0*/ f: jet.Function1<T, jet.Tuple0>): jet.Boolean
+ internal final fun plusAssign(/*0*/ f: jet.Function1<T, jet.Tuple0>): jet.Boolean
+}
+// </namespace name="kt1028">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInClass.txt
new file mode 100644
index 0000000000000..7023b439ed12e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun a(/*0*/ a: jet.Int): jet.Int
+ internal final fun a(/*0*/ a: jet.Int): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInPackage.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInPackage.txt
new file mode 100644
index 0000000000000..b0f26b10ac738
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInPackage.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="qwertyuiop">
+namespace qwertyuiop
+
+internal final fun c(/*0*/ s: jet.String): jet.Tuple0
+internal final fun c(/*0*/ s: jet.String): jet.Tuple0
+// </namespace name="qwertyuiop">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalExtFunsInPackage.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalExtFunsInPackage.txt
new file mode 100644
index 0000000000000..2bee10793dd14
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalExtFunsInPackage.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="extensionFunctions">
+namespace extensionFunctions
+
+internal final fun jet.Int.qwe(/*0*/ a: jet.Float): jet.Int
+internal final fun jet.Int.qwe(/*0*/ a: jet.Float): jet.Int
+// </namespace name="extensionFunctions">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalFunsInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalFunsInClass.txt
new file mode 100644
index 0000000000000..fe0cebc975091
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalFunsInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun b(): jet.Tuple0
+ internal final fun b(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalValsInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalValsInClass.txt
new file mode 100644
index 0000000000000..35e6be0f99a50
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalValsInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final val a: jet.Int
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsValsDifferentTypeInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsValsDifferentTypeInClass.txt
new file mode 100644
index 0000000000000..e516646a23fe2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsValsDifferentTypeInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final val a: jet.Int
+ internal final val a: jet.String
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConstructorVsFunOverload.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConstructorVsFunOverload.txt
new file mode 100644
index 0000000000000..c93803b7356e5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConstructorVsFunOverload.txt
@@ -0,0 +1,37 @@
+namespace <root>
+
+// <namespace name="constructorVsFun">
+namespace constructorVsFun
+
+internal final class constructorVsFun.Rtyu : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Rtyu
+ internal final fun ololo(): jet.Tuple0
+ internal final object constructorVsFun.Rtyu.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): constructorVsFun.Rtyu.<no name provided>
+ internal final class constructorVsFun.Rtyu.<no name provided>.ololo : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Rtyu.<no name provided>.ololo
+ }
+ }
+}
+internal final class constructorVsFun.Tram : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Tram
+ internal final class constructorVsFun.Tram.f : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Tram.f
+ }
+ internal final fun f(): jet.Tuple0
+}
+internal final class constructorVsFun.Yvayva : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Yvayva
+ internal final object constructorVsFun.Yvayva.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): constructorVsFun.Yvayva.<no name provided>
+ internal final class constructorVsFun.Yvayva.<no name provided>.fghj : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Yvayva.<no name provided>.fghj
+ }
+ internal final fun fghj(): jet.Tuple0
+ }
+}
+internal final class constructorVsFun.a : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.a
+}
+internal final fun a(): jet.Int
+// </namespace name="constructorVsFun">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ExtFunDifferentReceiver.txt b/compiler/testData/lazyResolve/diagnostics/overload/ExtFunDifferentReceiver.txt
new file mode 100644
index 0000000000000..118f0018e4a3c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ExtFunDifferentReceiver.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun jet.Int.rty(): jet.Int
+internal final fun jet.String.rty(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/FunNoConflictInDifferentPackages.txt b/compiler/testData/lazyResolve/diagnostics/overload/FunNoConflictInDifferentPackages.txt
new file mode 100644
index 0000000000000..98c8f1da7cb1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/FunNoConflictInDifferentPackages.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="ns1">
+namespace ns1
+
+internal final fun e(): jet.Int
+// </namespace name="ns1">
+// <namespace name="ns2">
+namespace ns2
+
+internal final fun e(): jet.Int
+// </namespace name="ns2">
+// <namespace name="ns3">
+namespace ns3
+
+// <namespace name="ns1">
+namespace ns1
+
+internal final fun e(): jet.Int
+// </namespace name="ns1">
+// </namespace name="ns3">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/OverloadFunRegularAndExt.txt b/compiler/testData/lazyResolve/diagnostics/overload/OverloadFunRegularAndExt.txt
new file mode 100644
index 0000000000000..3749e9defb86f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/OverloadFunRegularAndExt.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="extensionAndRegular">
+namespace extensionAndRegular
+
+internal final fun jet.Int.who(): jet.Int
+internal final fun who(): jet.Int
+// </namespace name="extensionAndRegular">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/OverloadVarAndFunInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/OverloadVarAndFunInClass.txt
new file mode 100644
index 0000000000000..fe115c4686577
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/OverloadVarAndFunInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Aaaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaaa
+ internal final fun bb(): jet.Int
+ internal final val bb: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractFunImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunImplemented.txt
new file mode 100644
index 0000000000000..67bfc5cdc2c74
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract fun foo(): jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractFunNotImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunNotImplemented.txt
new file mode 100644
index 0000000000000..f0a8e4aed57c2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunNotImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract fun foo(): jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractValImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractValImplemented.txt
new file mode 100644
index 0000000000000..1b5c2d0c8f0df
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractValImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract val i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ val i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractValNotImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractValNotImplemented.txt
new file mode 100644
index 0000000000000..19f4c8a8db3d1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractValNotImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract val i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract override /*1*/ val i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractVarImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarImplemented.txt
new file mode 100644
index 0000000000000..a880e410bb584
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract var i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractVarNotImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarNotImplemented.txt
new file mode 100644
index 0000000000000..aabba56d2f9cc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarNotImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract var i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract override /*1*/ var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ComplexValRedeclaration.txt b/compiler/testData/lazyResolve/diagnostics/override/ComplexValRedeclaration.txt
new file mode 100644
index 0000000000000..0472c8a3f8cb0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ComplexValRedeclaration.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="override">
+namespace override
+
+// <namespace name="generics">
+namespace generics
+
+internal abstract class override.generics.MyAbstractClass</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): override.generics.MyAbstractClass<T>
+ internal abstract val pr: T
+}
+internal abstract class override.generics.MyLegalAbstractClass2</*0*/ T : jet.Any?> : override.generics.MyAbstractClass<jet.Int> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyLegalAbstractClass2<T>
+ internal final val </*0*/ R : jet.Any?> pr: T
+ internal abstract override /*1*/ val pr: jet.Int
+}
+// </namespace name="generics">
+// </namespace name="override">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingFunctionSignatureFromSuperclass.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingFunctionSignatureFromSuperclass.txt
new file mode 100644
index 0000000000000..08ea7cab9d645
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingFunctionSignatureFromSuperclass.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final fun foo(): jet.Int
+}
+internal open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ internal final fun </*0*/ T : jet.Any?>foo(): jet.Int
+ internal final override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames-MultipleSupertypes.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames-MultipleSupertypes.txt
new file mode 100644
index 0000000000000..1b56bc4f73b6a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames-MultipleSupertypes.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+internal abstract trait C : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal abstract trait D : jet.Any {
+ internal abstract fun foo(/*0*/ b: jet.Int): jet.Tuple0
+}
+internal abstract trait E : C, D {
+ internal abstract override /*2*/ fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal abstract trait F : C, D {
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames.txt
new file mode 100644
index 0000000000000..f9d5dc79fe945
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal abstract fun b(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal abstract trait B : A {
+ internal abstract override /*1*/ fun b(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal final class C1 : A {
+ public final /*constructor*/ fun <init>(): C1
+ internal open override /*1*/ fun b(/*0*/ b: jet.Int): jet.Tuple0
+}
+internal final class C2 : B {
+ public final /*constructor*/ fun <init>(): C2
+ internal open override /*1*/ fun b(/*0*/ b: jet.Int): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingPropertySignatureFromSuperclass.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingPropertySignatureFromSuperclass.txt
new file mode 100644
index 0000000000000..d7f55dd3917d5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingPropertySignatureFromSuperclass.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final val bar: jet.Int
+}
+internal open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ internal final override /*1*/ val bar: jet.Int
+ internal final val </*0*/ T : jet.Any?> bar: jet.String
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValueInOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValueInOverride.txt
new file mode 100644
index 0000000000000..a86972510e2f2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValueInOverride.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal open fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal final class C : A {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class D : A {
+ public final /*constructor*/ fun <init>(): D
+ internal open override /*1*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValues-NoErrorsWhenInheritingFromOneTypeTwice.txt b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValues-NoErrorsWhenInheritingFromOneTypeTwice.txt
new file mode 100644
index 0000000000000..3c03f6051983e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValues-NoErrorsWhenInheritingFromOneTypeTwice.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait YSub : Y {
+ internal abstract override /*1*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z2 : Y, YSub {
+ public final /*constructor*/ fun <init>(): Z2
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val Z2O: Z2O
diff --git a/compiler/testData/lazyResolve/diagnostics/override/EqualityOfIntersectionTypes.txt b/compiler/testData/lazyResolve/diagnostics/override/EqualityOfIntersectionTypes.txt
new file mode 100644
index 0000000000000..7cf9693ba6415
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/EqualityOfIntersectionTypes.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal open fun </*0*/ T : Bar & Foo>foo(): jet.Tuple0
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun </*0*/ T : Bar & Foo>foo(): jet.Tuple0
+}
+internal abstract trait Bar : jet.Any {
+}
+internal abstract trait Foo : jet.Any {
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ExtendFunctionClass.txt b/compiler/testData/lazyResolve/diagnostics/override/ExtendFunctionClass.txt
new file mode 100644
index 0000000000000..eac9e004e33f6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ExtendFunctionClass.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="extendFunctionClass">
+namespace extendFunctionClass
+
+internal final class extendFunctionClass.A : jet.Function1<jet.Int, jet.Int> {
+ public final /*constructor*/ fun <init>(): extendFunctionClass.A
+ public abstract override /*1*/ fun invoke(/*0*/ p1: jet.Int): jet.Int
+}
+internal final class extendFunctionClass.B : jet.Function1<jet.Int, jet.Int> {
+ public final /*constructor*/ fun <init>(): extendFunctionClass.B
+ public open override /*1*/ fun invoke(/*0*/ p1: jet.Int): jet.Int
+}
+// </namespace name="extendFunctionClass">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/FakeOverrideAbstractAndNonAbstractFun.txt b/compiler/testData/lazyResolve/diagnostics/override/FakeOverrideAbstractAndNonAbstractFun.txt
new file mode 100644
index 0000000000000..6c2c32fc25212
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/FakeOverrideAbstractAndNonAbstractFun.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal open class Ccc : jet.Any {
+ public final /*constructor*/ fun <init>(): Ccc
+ internal final fun foo(): jet.Int
+}
+internal abstract trait Ttt : jet.Any {
+ internal abstract fun foo(): jet.Int
+}
+internal final class Zzz : Ccc, Ttt {
+ public final /*constructor*/ fun <init>(): Zzz
+ internal final override /*2*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/Generics.txt b/compiler/testData/lazyResolve/diagnostics/override/Generics.txt
new file mode 100644
index 0000000000000..244bcf1a9eca3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/Generics.txt
@@ -0,0 +1,105 @@
+namespace <root>
+
+// <namespace name="override">
+namespace override
+
+// <namespace name="generics">
+namespace generics
+
+internal abstract class override.generics.MyAbstractClass</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): override.generics.MyAbstractClass<T>
+ internal abstract fun bar(/*0*/ t: T): T
+ internal abstract val pr: T
+}
+internal abstract class override.generics.MyAbstractClass1 : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyAbstractClass1
+ internal open override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal open override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal abstract override /*1*/ val pr: jet.String
+}
+internal final class override.generics.MyChildClass : override.generics.MyGenericClass<jet.Int> {
+ public final /*constructor*/ fun <init>(): override.generics.MyChildClass
+ internal open override /*1*/ fun bar(/*0*/ t: jet.Int): jet.Int
+ internal open override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal open override /*1*/ val p: jet.Int
+ internal open override /*1*/ val pr: jet.Int
+}
+internal final class override.generics.MyChildClass1</*0*/ T : jet.Any?> : override.generics.MyGenericClass<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyChildClass1<T>
+ internal open override /*1*/ fun bar(/*0*/ t: T): T
+ internal open override /*1*/ fun foo(/*0*/ t: T): T
+ internal open override /*1*/ val p: T
+ internal open override /*1*/ val pr: T
+}
+internal final class override.generics.MyChildClass2</*0*/ T : jet.Any?> : override.generics.MyGenericClass<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyChildClass2<T>
+ internal open override /*1*/ fun bar(/*0*/ t: T): T
+ internal final override /*1*/ fun foo(/*0*/ t: T): T
+ internal open override /*1*/ val p: T
+ internal final override /*1*/ val pr: T
+}
+internal open class override.generics.MyClass : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyClass
+ internal open override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal open override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal open override /*1*/ val pr: jet.String
+}
+internal open class override.generics.MyGenericClass</*0*/ T : jet.Any?> : override.generics.MyTrait<T>, override.generics.MyAbstractClass<T>, override.generics.MyProps<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyGenericClass<T>
+ internal open override /*1*/ fun bar(/*0*/ t: T): T
+ internal open override /*1*/ fun foo(/*0*/ t: T): T
+ internal open override /*1*/ val p: T
+ internal open override /*1*/ val pr: T
+}
+internal final class override.generics.MyIllegalClass1 : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyIllegalClass1
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal abstract override /*1*/ val pr: jet.String
+}
+internal final class override.generics.MyIllegalClass2</*0*/ T : jet.Any?> : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.Int> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyIllegalClass2<T>
+ internal final fun bar(/*0*/ t: T): T
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.Int): jet.Int
+ internal final fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal final val </*0*/ R : jet.Any?> pr: T
+ internal abstract override /*1*/ val pr: jet.Int
+}
+internal final class override.generics.MyIllegalGenericClass1</*0*/ T : jet.Any?> : override.generics.MyTrait<T>, override.generics.MyAbstractClass<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): override.generics.MyIllegalGenericClass1<T>
+ internal abstract override /*1*/ fun bar(/*0*/ t: T): T
+ internal abstract override /*1*/ fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ val pr: T
+}
+internal final class override.generics.MyIllegalGenericClass2</*0*/ T : jet.Any?, /*1*/ R : jet.Any?> : override.generics.MyTrait<T>, override.generics.MyAbstractClass<R> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?, /*1*/ R : jet.Any?><init>(/*0*/ r: R): override.generics.MyIllegalGenericClass2<T, R>
+ internal abstract override /*1*/ fun bar(/*0*/ t: R): R
+ internal open fun foo(/*0*/ r: R): R
+ internal abstract override /*1*/ fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ val pr: R
+ internal open val </*0*/ T : jet.Any?> pr: R
+}
+internal abstract class override.generics.MyLegalAbstractClass1 : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyLegalAbstractClass1
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal abstract override /*1*/ val pr: jet.String
+}
+internal abstract class override.generics.MyLegalAbstractClass2</*0*/ T : jet.Any?> : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.Int> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyLegalAbstractClass2<T>
+ internal final fun bar(/*0*/ t: T): T
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.Int): jet.Int
+ internal final fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal final val </*0*/ R : jet.Any?> pr: T
+ internal abstract override /*1*/ val pr: jet.Int
+}
+internal abstract trait override.generics.MyProps</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract val p: T
+}
+internal abstract trait override.generics.MyTrait</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract fun foo(/*0*/ t: T): T
+}
+// </namespace name="generics">
+// </namespace name="override">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/InvisiblePotentialOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/InvisiblePotentialOverride.txt
new file mode 100644
index 0000000000000..5858324151f82
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/InvisiblePotentialOverride.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ private final fun foo(): jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal final fun foo(): jet.String
+ invisible_fake final override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypes.txt b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypes.txt
new file mode 100644
index 0000000000000..939fe6bbb7d91
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypes.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z : X, Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val ZO: ZO
diff --git a/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypesNoOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypesNoOverride.txt
new file mode 100644
index 0000000000000..95958c0285e0f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypesNoOverride.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z : X, Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal final override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val ZO: ZO
diff --git a/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultsInSupertypesNoExplicitOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultsInSupertypesNoExplicitOverride.txt
new file mode 100644
index 0000000000000..58077d1cddbdf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultsInSupertypesNoExplicitOverride.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z1 : X, Y {
+ public final /*constructor*/ fun <init>(): Z1
+ internal abstract override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val Z1O: Z1O
diff --git a/compiler/testData/lazyResolve/diagnostics/override/NonGenerics.txt b/compiler/testData/lazyResolve/diagnostics/override/NonGenerics.txt
new file mode 100644
index 0000000000000..fa125f197f73a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/NonGenerics.txt
@@ -0,0 +1,70 @@
+namespace <root>
+
+// <namespace name="override">
+namespace override
+
+// <namespace name="normal">
+namespace normal
+
+internal abstract class override.normal.MyAbstractClass : jet.Any {
+ public final /*constructor*/ fun <init>(): override.normal.MyAbstractClass
+ internal abstract fun bar(): jet.Tuple0
+ internal abstract val prr: jet.Tuple0
+}
+internal final class override.normal.MyChildClass : override.normal.MyClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyChildClass
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyChildClass1 : override.normal.MyClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyChildClass1
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+ internal final override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal open class override.normal.MyClass : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyClass
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass
+ internal abstract override /*1*/ fun bar(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Tuple0
+ internal abstract override /*1*/ val pr: jet.Tuple0
+ internal abstract override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass2 : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass2
+ internal abstract override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass3 : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass3
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass4 : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass4
+ internal abstract override /*1*/ fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+ internal open fun other(): jet.Tuple0
+ internal open val otherPr: jet.Int
+ internal final override /*1*/ val pr: jet.Tuple0
+ internal abstract override /*1*/ val prr: jet.Tuple0
+}
+internal abstract trait override.normal.MyTrait : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+ internal abstract val pr: jet.Tuple0
+}
+// </namespace name="normal">
+// </namespace name="override">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ParameterDefaultValues-DefaultValueFromOnlyOneSupertype.txt b/compiler/testData/lazyResolve/diagnostics/override/ParameterDefaultValues-DefaultValueFromOnlyOneSupertype.txt
new file mode 100644
index 0000000000000..9c6fb4c0e60d8
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ParameterDefaultValues-DefaultValueFromOnlyOneSupertype.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal final class Z : X, Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/SuspiciousCase1.txt b/compiler/testData/lazyResolve/diagnostics/override/SuspiciousCase1.txt
new file mode 100644
index 0000000000000..e70daad2e0fce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/SuspiciousCase1.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait Bar</*0*/ Q : jet.Any?> : Foo<Q> {
+ internal open override /*1*/ fun quux(/*0*/ p: Q, /*1*/ q: jet.Int = ?): jet.Int
+}
+internal abstract class Baz : Bar<jet.String> {
+ public final /*constructor*/ fun <init>(): Baz
+ internal open override /*1*/ fun quux(/*0*/ p: jet.String, /*1*/ q: jet.Int = ?): jet.Int
+}
+internal abstract trait Foo</*0*/ P : jet.Any?> : jet.Any {
+ internal open fun quux(/*0*/ p: P, /*1*/ q: jet.Int = ?): jet.Int
+}
+internal final fun zz(/*0*/ b: Baz): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ToAbstractMembersFromSuper-kt1996.txt b/compiler/testData/lazyResolve/diagnostics/override/ToAbstractMembersFromSuper-kt1996.txt
new file mode 100644
index 0000000000000..c02180a656c3c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ToAbstractMembersFromSuper-kt1996.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal abstract trait Bar : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
+internal final class Baz : Foo, Bar {
+ public final /*constructor*/ fun <init>(): Baz
+ internal abstract override /*2*/ fun foo(): jet.Tuple0
+}
+internal abstract trait Foo : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/kt1862.txt b/compiler/testData/lazyResolve/diagnostics/override/kt1862.txt
new file mode 100644
index 0000000000000..96cc596b29d0b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/kt1862.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal open fun foo(): jet.Int
+}
+internal open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal abstract trait Ccc : Aaa {
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal final class Ddd : Bbb, Ccc {
+ public final /*constructor*/ fun <init>(): Ddd
+ internal open override /*2*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/AmbiguityOnLazyTypeComputation.txt b/compiler/testData/lazyResolve/diagnostics/regressions/AmbiguityOnLazyTypeComputation.txt
new file mode 100644
index 0000000000000..5e9050c2b602d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/AmbiguityOnLazyTypeComputation.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="x">
+namespace x
+
+internal final class x.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): x.Foo
+ internal final fun compareTo(/*0*/ other: jet.Byte): jet.Int
+ internal final fun compareTo(/*0*/ other: jet.Char): jet.Int
+}
+internal final val a1: jet.Int
+internal final val b: x.Foo
+// </namespace name="x">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/AssignmentsUnderOperators.txt b/compiler/testData/lazyResolve/diagnostics/regressions/AssignmentsUnderOperators.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/AssignmentsUnderOperators.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/CoercionToUnit.txt b/compiler/testData/lazyResolve/diagnostics/regressions/CoercionToUnit.txt
new file mode 100644
index 0000000000000..400f87e4f3efa
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/CoercionToUnit.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(/*0*/ u: jet.Tuple0): jet.Int
+internal final fun test(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/DoubleDefine.txt b/compiler/testData/lazyResolve/diagnostics/regressions/DoubleDefine.txt
new file mode 100644
index 0000000000000..d4f60be446474
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/DoubleDefine.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun evaluate(/*0*/ expr: java.lang.StringBuilder, /*1*/ numbers: java.util.ArrayList<jet.Int>): jet.Int
+internal final fun evaluateAdd(/*0*/ expr: java.lang.StringBuilder, /*1*/ numbers: java.util.ArrayList<jet.Int>): jet.Int
+internal final fun evaluateArg(/*0*/ expr: jet.CharSequence, /*1*/ numbers: java.util.ArrayList<jet.Int>): jet.Int
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun takeFirst(/*0*/ expr: java.lang.StringBuilder): jet.Char
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/ErrorsOnIbjectExpressionsAsParameters.txt b/compiler/testData/lazyResolve/diagnostics/regressions/ErrorsOnIbjectExpressionsAsParameters.txt
new file mode 100644
index 0000000000000..20d98c49f5b1b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/ErrorsOnIbjectExpressionsAsParameters.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet11.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet11.txt
new file mode 100644
index 0000000000000..70d2d58f77ad5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet11.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal open class NoC : jet.Any {
+ public final /*constructor*/ fun <init>(): NoC
+}
+internal final class NoC1 : NoC {
+ public final /*constructor*/ fun <init>(): NoC1
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet121.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet121.txt
new file mode 100644
index 0000000000000..40656e5f7f5ce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet121.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="jet121">
+namespace jet121
+
+internal final fun apply(/*0*/ arg: jet.String, /*1*/ f: jet.ExtensionFunction0<jet.String, jet.Int>): jet.Int
+internal final fun box(): jet.String
+// </namespace name="jet121">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet124.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet124.txt
new file mode 100644
index 0000000000000..906406dc8cfb5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet124.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(): jet.Tuple0
+internal final fun foo1(): jet.Function1<jet.Int, jet.Int>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet169.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet169.txt
new file mode 100644
index 0000000000000..485284328720a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet169.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun set(/*0*/ key: jet.String, /*1*/ value: jet.String): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet17.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet17.txt
new file mode 100644
index 0000000000000..4368a0787f0a0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet17.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class WithC : jet.Any {
+ public final /*constructor*/ fun <init>(): WithC
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet53.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet53.txt
new file mode 100644
index 0000000000000..277fb8d2562fe
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet53.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final val ab: java.util.List<jet.Int>?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet67.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet67.txt
new file mode 100644
index 0000000000000..2afd760a213ce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet67.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal abstract class XXX : jet.Any {
+ public final /*constructor*/ fun <init>(): XXX
+ internal abstract val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet68.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet68.txt
new file mode 100644
index 0000000000000..e28689cf4ae0f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet68.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet69.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet69.txt
new file mode 100644
index 0000000000000..54d2f7f98be72
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet69.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Command : jet.Any {
+ public final /*constructor*/ fun <init>(): Command
+}
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun parse(/*0*/ cmd: jet.String): Command?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet72.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet72.txt
new file mode 100644
index 0000000000000..0d868ac29e52b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet72.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal abstract class Item : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ room: java.lang.Object): Item
+ internal abstract val name: jet.String
+ internal final val room: java.lang.Object
+}
+internal final val items: java.util.ArrayList<Item>
+internal final fun test(/*0*/ room: java.lang.Object): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet81.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet81.txt
new file mode 100644
index 0000000000000..4a8d5b1db0dc4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet81.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final val A: A
+internal final val a: <no name provided>
+internal final val b: [ERROR : <ERROR PROPERTY TYPE>]
+internal final val c: jet.Int
+internal final val y: <no name provided>
+internal final val z: [ERROR : Type for y]
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/OrphanStarProjection.txt b/compiler/testData/lazyResolve/diagnostics/regressions/OrphanStarProjection.txt
new file mode 100644
index 0000000000000..b5ae30814e185
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/OrphanStarProjection.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class B : jet.Any {
+ public final /*constructor*/ fun <init>(): B
+}
+internal final val b: [ERROR : B<*>]
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/OutProjections.txt b/compiler/testData/lazyResolve/diagnostics/regressions/OutProjections.txt
new file mode 100644
index 0000000000000..0e734f7d29c10
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/OutProjections.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal final class G</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): G<T>
+}
+internal final class Out</*0*/ out T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ out T : jet.Any?><init>(): Out<T>
+}
+internal final class Point : jet.Any {
+ public final /*constructor*/ fun <init>(): Point
+}
+internal final fun </*0*/ T : jet.Any?>f(/*0*/ expression: T): G<out T>
+internal final fun foo(): G<Point>
+internal final fun fooout(): Out<Point>
+internal final fun </*0*/ T : jet.Any?>fout(/*0*/ expression: T): Out<out T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/OverrideResolution.txt b/compiler/testData/lazyResolve/diagnostics/regressions/OverrideResolution.txt
new file mode 100644
index 0000000000000..fa981b347d6d7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/OverrideResolution.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal open fun foo(): jet.Tuple0
+}
+internal open class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun foo(): jet.Tuple0
+}
+internal open class C : B {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun foo(): jet.Tuple0
+}
+internal final fun box(/*0*/ c: C): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/SpecififcityByReceiver.txt b/compiler/testData/lazyResolve/diagnostics/regressions/SpecififcityByReceiver.txt
new file mode 100644
index 0000000000000..4cd7eebe6393b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/SpecififcityByReceiver.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/TypeMismatchOnUnaryOperations.txt b/compiler/testData/lazyResolve/diagnostics/regressions/TypeMismatchOnUnaryOperations.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/TypeMismatchOnUnaryOperations.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/TypeParameterAsASupertype.txt b/compiler/testData/lazyResolve/diagnostics/regressions/TypeParameterAsASupertype.txt
new file mode 100644
index 0000000000000..2861640864159
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/TypeParameterAsASupertype.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class A</*0*/ T : jet.Any?> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): A<T>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/UnavaliableQualifiedThis.txt b/compiler/testData/lazyResolve/diagnostics/regressions/UnavaliableQualifiedThis.txt
new file mode 100644
index 0000000000000..2a808d697c821
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/UnavaliableQualifiedThis.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal abstract trait Iterator</*0*/ out T : jet.Any?> : jet.Any {
+ internal abstract val hasNext: jet.Boolean
+ internal open fun </*0*/ R : jet.Any?>map(/*0*/ transform: jet.Function1<T, R>): Iterator<R>
+ internal abstract fun next(): T
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/WrongTraceInCallResolver.txt b/compiler/testData/lazyResolve/diagnostics/regressions/WrongTraceInCallResolver.txt
new file mode 100644
index 0000000000000..b0b8e8d9c68cc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/WrongTraceInCallResolver.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): Bar
+}
+internal open class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
+internal final fun f(): jet.Tuple0
+internal final fun </*0*/ T : Bar, /*1*/ T1 : jet.Any?>foo(/*0*/ x: jet.Int): jet.Tuple0
+internal final fun </*0*/ T1 : jet.Any?, /*1*/ T : Foo>foo(/*0*/ x: jet.Long): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt127.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt127.txt
new file mode 100644
index 0000000000000..52f7e7f8b5d33
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt127.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun jet.Any?.equals1(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt128.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt128.txt
new file mode 100644
index 0000000000000..35ffbe62f0f23
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt128.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun div(/*0*/ c: jet.String = ?, /*1*/ f: jet.Function0<jet.Tuple0>): jet.Tuple0
+internal final fun f(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1489_1728.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1489_1728.txt
new file mode 100644
index 0000000000000..ee4feff2a8e1e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1489_1728.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="kt606_dependents">
+namespace kt606_dependents
+
+internal abstract trait kt606_dependents.AutoCloseable : jet.Any {
+ internal abstract fun close(): jet.Tuple0
+}
+internal final class kt606_dependents.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt606_dependents.C
+ internal final fun bar(): jet.Tuple0
+ internal final class kt606_dependents.C.Resource : kt606_dependents.AutoCloseable {
+ public final /*constructor*/ fun <init>(): kt606_dependents.C.Resource
+ internal open override /*1*/ fun close(): jet.Tuple0
+ }
+ internal final fun </*0*/ X : kt606_dependents.AutoCloseable>foo(/*0*/ x: X, /*1*/ body: jet.Function1<X, jet.Tuple0>): jet.Tuple0
+ internal final fun p(): kt606_dependents.C.Resource?
+}
+internal final val jet.Int.ext: jet.Function0<jet.Int>
+internal final val x: jet.Int
+// </namespace name="kt606_dependents">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1550.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1550.txt
new file mode 100644
index 0000000000000..5ed3f291218f7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1550.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1647.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1647.txt
new file mode 100644
index 0000000000000..f1b4f3a8b7cb2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1647.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal open class Abs : jet.Any {
+ public final /*constructor*/ fun <init>(): Abs
+}
+internal final class Bar : Abs {
+ public final /*constructor*/ fun <init>(): Bar
+}
+internal final fun </*0*/ F : Abs>patternMatchingAndGenerics(/*0*/ arg: F): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1736.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1736.txt
new file mode 100644
index 0000000000000..a986a0328df57
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1736.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1736">
+namespace kt1736
+
+internal final val Obj: kt1736.Obj
+internal final val x: jet.Tuple0
+// </namespace name="kt1736">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt174.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt174.txt
new file mode 100644
index 0000000000000..047a3793ab71c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt174.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal abstract trait Tree : jet.Any {
+}
+internal final fun jet.Any?.TreeValue(): Tree
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt201.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt201.txt
new file mode 100644
index 0000000000000..282c60847816d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt201.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any>T?.npe(): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt235.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt235.txt
new file mode 100644
index 0000000000000..3e1f8c1ff935f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt235.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="kt235">
+namespace kt235
+
+internal final class kt235.MyArray : jet.Any {
+ public final /*constructor*/ fun <init>(): kt235.MyArray
+ internal final fun get(/*0*/ i: jet.Int): jet.Int
+ internal final fun set(/*0*/ i: jet.Int, /*1*/ value: jet.Int): jet.Int
+}
+internal final class kt235.MyArray1 : jet.Any {
+ public final /*constructor*/ fun <init>(): kt235.MyArray1
+ internal final fun get(/*0*/ i: jet.Int): jet.Int
+ internal final fun set(/*0*/ i: jet.Int, /*1*/ value: jet.Int): jet.Tuple0
+}
+internal final class kt235.MyNumber : jet.Any {
+ public final /*constructor*/ fun <init>(): kt235.MyNumber
+ internal final fun inc(): kt235.MyNumber
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt235">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt2376.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt2376.txt
new file mode 100644
index 0000000000000..d1101ee41311c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt2376.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+public open class Test : java.lang.Object {
+ public final /*constructor*/ fun <init>(): Test
+ package open fun number(/*0*/ n: jet.Number?): jet.Tuple0
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt251.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt251.txt
new file mode 100644
index 0000000000000..d508ebfcc28cf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt251.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final var a: jet.Any
+ internal final val b: jet.Int
+ internal final val c: jet.Int
+ internal final val d: jet.Int
+ internal final val e: jet.Int
+ internal final var x: jet.Int
+ internal final val y: jet.Int
+ internal final val z: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt258.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt258.txt
new file mode 100644
index 0000000000000..d8b05485691e2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt258.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ K : jet.Any?, /*1*/ V : jet.Any?>java.util.Map<K, V>.set(/*0*/ key: K, /*1*/ value: V): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt26.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt26.txt
new file mode 100644
index 0000000000000..8cc56101dc614
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt26.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="html">
+namespace html
+
+internal abstract class html.Factory</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): html.Factory<T>
+ internal final fun create(): T?
+}
+// </namespace name="html">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt282.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt282.txt
new file mode 100644
index 0000000000000..b4cf816c53369
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt282.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class Set : jet.Any {
+ public final /*constructor*/ fun <init>(): Set
+ internal final fun contains(/*0*/ x: jet.Int): jet.Boolean
+}
+internal final fun jet.Int?.contains(/*0*/ x: jet.Int): jet.Boolean
+internal final fun f(): jet.Tuple0
+internal final fun Set?.plus(/*0*/ x: jet.Int): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt287.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt287.txt
new file mode 100644
index 0000000000000..977f81dc7c0ea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt287.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final val attributes: java.util.Map<jet.String, jet.String>
+internal final fun attributes(): java.util.Map<jet.String, jet.String>
+internal final fun foo(/*0*/ m: java.util.Map<jet.String, jet.String>): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt302.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt302.txt
new file mode 100644
index 0000000000000..9ccb8bbc7b3b0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt302.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt302">
+namespace kt302
+
+internal abstract trait kt302.A : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait kt302.B : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal final class kt302.C : kt302.A, kt302.B {
+ public final /*constructor*/ fun <init>(): kt302.C
+ internal open override /*2*/ fun foo(): jet.Tuple0
+}
+// </namespace name="kt302">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt306.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt306.txt
new file mode 100644
index 0000000000000..1b83462abec04
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt306.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class Barr : jet.Any {
+ public final /*constructor*/ fun <init>(): Barr
+ internal final fun bar(): jet.Tuple0
+}
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ internal final fun bar(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt307.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt307.txt
new file mode 100644
index 0000000000000..9f982e8ca5677
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt307.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal open class AL : jet.Any {
+ public final /*constructor*/ fun <init>(): AL
+ internal final fun get(/*0*/ i: jet.Int): jet.Any?
+}
+internal abstract trait ALE</*0*/ T : jet.Any?> : AL {
+ internal final override /*1*/ fun get(/*0*/ i: jet.Int): jet.Any?
+ internal open fun getOrNull(/*0*/ index: jet.Int, /*1*/ value: T): T
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt312.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt312.txt
new file mode 100644
index 0000000000000..c41c0e08376dc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt312.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final val args: jet.Array<jet.String>
+internal final val name: jet.String
+internal final val name1: jet.String?
+internal final fun </*0*/ T : jet.Any?>jet.Array<out T>.safeGet(/*0*/ index: jet.Int): T?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt313.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt313.txt
new file mode 100644
index 0000000000000..72bc183d98c02
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt313.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.join(/*0*/ separator: jet.String?): jet.String
+internal final fun </*0*/ T : jet.Any>T?.npe(): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt316.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt316.txt
new file mode 100644
index 0000000000000..a72a4477360ec
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt316.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class A : B {
+ public final /*constructor*/ fun <init>(): A
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+}
+internal abstract trait B : jet.Any {
+ internal open fun bar(): jet.Tuple0
+ internal open fun foo(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt328.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt328.txt
new file mode 100644
index 0000000000000..67e35484a7cd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt328.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val x: jet.Function0<[ERROR : <return type>]>
+}
+internal final val x: jet.Function0<[ERROR : <return type>]>
+internal final val z: [ERROR : Type for z]
+internal final fun bar1(): jet.Function0<[ERROR : <return type>]>
+internal final fun bar2(): jet.Function0<jet.Tuple0>
+internal final fun bar3(): jet.Tuple0
+internal final fun block(/*0*/ f: jet.Function0<jet.Tuple0>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt335.336.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt335.336.txt
new file mode 100644
index 0000000000000..da8169f6c277f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt335.336.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>java.util.List<T>.plus(/*0*/ other: java.util.List<T>): java.util.List<T>
+internal final fun </*0*/ T : java.lang.Comparable<T>>java.util.List<T>.sort(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt337.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt337.txt
new file mode 100644
index 0000000000000..955e222056bb8
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt337.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt352.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt352.txt
new file mode 100644
index 0000000000000..1597cca18151e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt352.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="kt352">
+namespace kt352
+
+internal final class kt352.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt352.A
+ internal final val f: jet.Function1<jet.Any, jet.Tuple0>
+}
+internal final val f: jet.Function1<jet.Any, jet.Tuple0>
+internal final val g: jet.Function0<jet.Tuple0>
+internal final val h: jet.Function0<jet.Tuple0>
+internal final val testIt: jet.Function1<jet.Any, jet.Tuple0>
+internal final fun doSmth(): jet.Int
+internal final fun doSmth(/*0*/ a: jet.String): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt352">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt353.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt353.txt
new file mode 100644
index 0000000000000..a6b746fac2e83
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt353.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal abstract fun </*0*/ T : jet.Any?>gen(): T
+}
+internal final fun foo(/*0*/ a: A): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt385.109.441.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt385.109.441.txt
new file mode 100644
index 0000000000000..2cbf0ee5a0fa1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt385.109.441.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.foreach(/*0*/ operation: jet.Function1<T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.foreach(/*0*/ operation: jet.Function2<jet.Int, T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterator<T>.foreach(/*0*/ operation: jet.Function1<T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterator<T>.foreach(/*0*/ operation: jet.Function2<jet.Int, T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>generic_invoker(/*0*/ gen: jet.Function0<T>): T
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun println(/*0*/ message: jet.Int): jet.Tuple0
+internal final fun println(/*0*/ message: jet.Long): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>run(/*0*/ body: jet.Function0<T>): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt398.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt398.txt
new file mode 100644
index 0000000000000..dbe7a9bc4f8d1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt398.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class X</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ internal final val check: jet.Function1<jet.Any, jet.Boolean>
+}
+internal final fun box(): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt399.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt399.txt
new file mode 100644
index 0000000000000..087509a18834e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt399.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun </*0*/ T : jet.Any?>getSameTypeChecker(/*0*/ obj: T): jet.Function1<jet.Any, jet.Boolean>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt402.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt402.txt
new file mode 100644
index 0000000000000..bef4752805fa7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt402.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt402">
+namespace kt402
+
+internal final fun f(): jet.Function1<jet.Any, jet.Boolean>
+internal final fun getTypeChecker(): jet.Function1<jet.Any, jet.Boolean>
+// </namespace name="kt402">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt41.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt41.txt
new file mode 100644
index 0000000000000..0fb842f2c66bf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt41.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt41">
+namespace kt41
+
+internal final fun aaa(): [ERROR : Error function type]
+internal final fun bbb(): jet.Tuple0
+// </namespace name="kt41">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt411.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt411.txt
new file mode 100644
index 0000000000000..ea60c1f0cd370
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt411.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt411">
+namespace kt411
+
+internal final fun f(): jet.Tuple0
+internal final fun invoker(/*0*/ gen: jet.Function0<jet.Int>): jet.Int
+internal final fun t1(): jet.Tuple0
+internal final fun t2(): jet.String
+internal final fun t3(): jet.String
+internal final fun t4(): jet.Int
+// </namespace name="kt411">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt439.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt439.txt
new file mode 100644
index 0000000000000..c35601905d8fd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt439.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun main1(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>run1(/*0*/ body: jet.Function0<T>): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt442.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt442.txt
new file mode 100644
index 0000000000000..ec55b504b9891
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt442.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun </*0*/ T : jet.Any?>funny(/*0*/ f: jet.Function0<T>): T
+internal final fun </*0*/ T : jet.Any?>funny2(/*0*/ f: jet.Function1<T, T>): T
+internal final fun </*0*/ T : jet.Any?>generic_invoker(/*0*/ gen: jet.Function1<jet.String, T>): T
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun testFunny(): jet.Tuple0
+internal final fun testFunny2(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>T.with(/*0*/ f: jet.ExtensionFunction0<T, jet.Tuple0>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt443.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt443.txt
new file mode 100644
index 0000000000000..1d3ff8dddb04e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt443.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class M : jet.Any {
+ public final /*constructor*/ fun <init>(): M
+ internal open val b: jet.Int
+}
+internal final class N : M {
+ public final /*constructor*/ fun <init>(): N
+ internal final val a: jet.Int
+ internal open override /*1*/ val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt455.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt455.txt
new file mode 100644
index 0000000000000..decaf84711991
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt455.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt455">
+namespace kt455
+
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt455">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt456.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt456.txt
new file mode 100644
index 0000000000000..5e1da2e3112fb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt456.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="kt456">
+namespace kt456
+
+internal final class kt456.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt456.A
+ internal final val i: jet.Int
+}
+internal final class kt456.B : jet.Any {
+ public final /*constructor*/ fun <init>(): kt456.B
+ internal final val i: jet.Int
+}
+internal final class kt456.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt456.C
+ internal final val i: jet.Int
+}
+internal final fun doSmth(): jet.Tuple0
+// </namespace name="kt456">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt459.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt459.txt
new file mode 100644
index 0000000000000..d8b05485691e2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt459.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ K : jet.Any?, /*1*/ V : jet.Any?>java.util.Map<K, V>.set(/*0*/ key: K, /*1*/ value: V): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt469.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt469.txt
new file mode 100644
index 0000000000000..4ca0d641485a6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt469.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="kt469">
+namespace kt469
+
+internal final class kt469.MyNumber : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int): kt469.MyNumber
+ internal final var i: jet.Int
+ internal final fun minusAssign(/*0*/ m: kt469.MyNumber): jet.Tuple0
+}
+internal final fun bar(/*0*/ list: java.util.List<jet.Int>): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>java.util.List<T>.plusAssign(/*0*/ t: T): jet.Tuple0
+// </namespace name="kt469">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt498.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt498.txt
new file mode 100644
index 0000000000000..e17c5a9b5694d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt498.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class IdUnavailableException : java.lang.Exception {
+ public final /*constructor*/ fun <init>(): IdUnavailableException
+ public final override /*1*/ fun getCause(): jet.Throwable?
+ public final override /*1*/ fun getMessage(): jet.String?
+ public final override /*1*/ fun printStackTrace(): jet.Tuple0
+}
+internal final fun </*0*/ T : jet.Any>T.getJavaClass(): java.lang.Class<T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt524.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt524.txt
new file mode 100644
index 0000000000000..5d8c9ce2cea2c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt524.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="StringBuilder">
+namespace StringBuilder
+
+internal final val jet.Int.bd: java.lang.StringBuilder
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun java.lang.StringBuilder.plus(/*0*/ other: java.lang.StringBuilder): java.lang.StringBuilder
+internal final fun </*0*/ T : jet.Any>T?.sure1(): T
+// </namespace name="StringBuilder">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt526UnresolvedReferenceInnerStatic.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt526UnresolvedReferenceInnerStatic.txt
new file mode 100644
index 0000000000000..219081851dfea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt526UnresolvedReferenceInnerStatic.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="demo">
+namespace demo
+
+internal final class demo.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): demo.Foo
+ internal final object demo.Foo.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): demo.Foo.<no name provided>
+ internal final class demo.Foo.<no name provided>.Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): demo.Foo.<no name provided>.Bar
+ }
+ }
+}
+internal final class demo.User : jet.Any {
+ public final /*constructor*/ fun <init>(): demo.User
+ internal final fun main(): jet.Tuple0
+}
+// </namespace name="demo">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt549.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt549.txt
new file mode 100644
index 0000000000000..f125786e17e11
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt549.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="demo">
+namespace demo
+
+internal final fun </*0*/ T : jet.Any?>filter(/*0*/ list: jet.Array<T>, /*1*/ filter: jet.Function1<T, jet.Boolean>): java.util.List<T>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="demo">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt557.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt557.txt
new file mode 100644
index 0000000000000..a26707c1a3c40
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt557.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun jet.Array<jet.String>.length(): jet.Int
+internal final fun test(/*0*/ array: jet.Array<jet.String?>?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt571.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt571.txt
new file mode 100644
index 0000000000000..86a4a28757dd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt571.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+private final fun double(/*0*/ d: jet.Int): jet.Int
+internal final fun </*0*/ T : jet.Any?, /*1*/ R : jet.Any?>let(/*0*/ t: T, /*1*/ body: jet.Function1<T, R>): R
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt58.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt58.txt
new file mode 100644
index 0000000000000..f09add8b664f6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt58.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="kt58">
+namespace kt58
+
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>lock(/*0*/ lock: java.util.concurrent.locks.Lock, /*1*/ body: jet.Function0<T>): T
+internal final fun t1(): jet.Int
+internal final fun t2(): jet.Int
+internal final fun t3(): jet.Int
+internal final fun t4(): jet.Int
+internal final fun t5(): jet.Int
+internal final fun t6(): jet.Int
+internal final fun t7(): jet.Int
+// </namespace name="kt58">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt580.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt580.txt
new file mode 100644
index 0000000000000..131cc4f4c7016
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt580.txt
@@ -0,0 +1,18 @@
+namespace <root>
+
+// <namespace name="whats">
+namespace whats
+
+// <namespace name="the">
+namespace the
+
+// <namespace name="difference">
+namespace difference
+
+internal final val </*0*/ T : jet.Any?> jet.Array<T>.lastIndex: jet.Int
+internal final fun iarray(/*0*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.Array<jet.String>
+internal final fun </*0*/ T : jet.Any?>jet.Array<T>.lastIndex(): jet.Int
+internal final fun main(): jet.Tuple0
+// </namespace name="difference">
+// </namespace name="the">
+// </namespace name="whats">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt588.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt588.txt
new file mode 100644
index 0000000000000..9824d5fcee301
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt588.txt
@@ -0,0 +1,37 @@
+namespace <root>
+
+internal final class Test : java.lang.Thread {
+ public final /*constructor*/ fun <init>(): Test
+ public final override /*1*/ fun checkAccess(): jet.Tuple0
+ public open override /*1*/ fun countStackFrames(): jet.Int
+ public open override /*1*/ fun destroy(): jet.Tuple0
+ public open override /*1*/ fun getContextClassLoader(): java.lang.ClassLoader?
+ public open override /*1*/ fun getId(): jet.Long
+ public final override /*1*/ fun getName(): jet.String?
+ public final override /*1*/ fun getPriority(): jet.Int
+ public open override /*1*/ fun getStackTrace(): jet.Array<[ERROR : Unresolved java class: StackTraceElement]>?
+ public final override /*1*/ fun getThreadGroup(): [ERROR : Unresolved java class: ThreadGroup]
+ public open override /*1*/ fun interrupt(): jet.Tuple0
+ invisible_fake final override /*1*/ var inheritableThreadLocals: java.lang.ThreadLocal.ThreadLocalMap?
+ invisible_fake final override /*1*/ var threadLocals: java.lang.ThreadLocal.ThreadLocalMap?
+ public final override /*1*/ fun isAlive(): jet.Boolean
+ public final override /*1*/ fun isDaemon(): jet.Boolean
+ public open override /*1*/ fun isInterrupted(): jet.Boolean
+ public final override /*1*/ fun join(): jet.Tuple0
+ public final override /*1*/ fun join(/*0*/ p0: jet.Long): jet.Tuple0
+ public final override /*1*/ fun join(/*0*/ p0: jet.Long, /*1*/ p1: jet.Int): jet.Tuple0
+ public final override /*1*/ fun resume(): jet.Tuple0
+ public open override /*1*/ fun run(): jet.Tuple0
+ public open override /*1*/ fun setContextClassLoader(/*0*/ p0: java.lang.ClassLoader?): jet.Tuple0
+ public final override /*1*/ fun setDaemon(/*0*/ p0: jet.Boolean): jet.Tuple0
+ public final override /*1*/ fun setName(/*0*/ p0: jet.String?): jet.Tuple0
+ public final override /*1*/ fun setPriority(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun start(): jet.Tuple0
+ public final override /*1*/ fun stop(): jet.Tuple0
+ public final override /*1*/ fun stop(/*0*/ p0: jet.Throwable?): jet.Tuple0
+ public final override /*1*/ fun suspend(): jet.Tuple0
+ internal final object Test.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Test.<no name provided>
+ internal final fun init2(): jet.Tuple0
+ }
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt597.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt597.txt
new file mode 100644
index 0000000000000..e944d823e3b54
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt597.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>jet.Array<T>?.get(/*0*/ i: jet.Int): T
+internal final fun jet.Int?.inc(): jet.Int
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt600.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt600.txt
new file mode 100644
index 0000000000000..dd05b09a9faf6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt600.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any>T?._sure(): T
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt604.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt604.txt
new file mode 100644
index 0000000000000..f0952c956b356
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt604.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal abstract trait ChannelPipeline : jet.Any {
+}
+internal abstract trait ChannelPipelineFactory : jet.Any {
+ internal abstract fun getPipeline(): ChannelPipeline
+}
+internal final class DefaultChannelPipeline : ChannelPipeline {
+ public final /*constructor*/ fun <init>(): DefaultChannelPipeline
+}
+internal final class StandardPipelineFactory : ChannelPipelineFactory {
+ public final /*constructor*/ fun <init>(/*0*/ config: jet.ExtensionFunction0<ChannelPipeline, jet.Tuple0>): StandardPipelineFactory
+ internal final val config: jet.ExtensionFunction0<ChannelPipeline, jet.Tuple0>
+ internal open override /*1*/ fun getPipeline(): ChannelPipeline
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt618.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt618.txt
new file mode 100644
index 0000000000000..3ff11450de4ae
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt618.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="lol">
+namespace lol
+
+internal final class lol.B : jet.Any {
+ public final /*constructor*/ fun <init>(): lol.B
+ internal final fun divAssign(/*0*/ other: lol.B): jet.String
+ internal final fun minusAssign(/*0*/ other: lol.B): jet.String
+ internal final fun modAssign(/*0*/ other: lol.B): jet.String
+ internal final fun plusAssign(/*0*/ other: lol.B): jet.String
+ internal final fun timesAssign(/*0*/ other: lol.B): jet.String
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="lol">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt629.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt629.txt
new file mode 100644
index 0000000000000..c4af41b826e72
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt629.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt629">
+namespace kt629
+
+internal final class kt629.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt629.A
+ internal final fun mod(/*0*/ other: kt629.A): kt629.A
+ internal final var p: jet.String
+}
+internal final fun box(): jet.Boolean
+internal final fun box2(): jet.Boolean
+// </namespace name="kt629">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt630.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt630.txt
new file mode 100644
index 0000000000000..6bc93b1f2744b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt630.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final val s: jet.String
+internal final val x: jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt688.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt688.txt
new file mode 100644
index 0000000000000..0597951b0d403
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt688.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal open class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal final fun b(): B
+}
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun </*0*/ T : jet.Any?>a(/*0*/ x: jet.Function1<T, T>, /*1*/ y: T): T
+ internal final val x: B
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt701.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt701.txt
new file mode 100644
index 0000000000000..b4847e1c74a59
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt701.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+public final class Throwables : jet.Any {
+ public final /*constructor*/ fun <init>(): Throwables
+ internal final object Throwables.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Throwables.<no name provided>
+ public final fun </*0*/ X : jet.Throwable?>propagateIfInstanceOf(/*0*/ throwable: jet.Throwable?, /*1*/ declaredType: java.lang.Class<X?>?): jet.Tuple0
+ public final fun propagateIfPossible(/*0*/ throwable: jet.Throwable?): jet.Tuple0
+ }
+}
+internal final fun </*0*/ T : jet.Any?>getJavaClass(): java.lang.Class<T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt716.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt716.txt
new file mode 100644
index 0000000000000..bd191ad0fc62d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt716.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class TypeInfo</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): TypeInfo<T>
+}
+internal final fun </*0*/ T : jet.Any?>TypeInfo<T>.getJavaClass(): java.lang.Class<T>
+internal final fun </*0*/ T : jet.Any?>getJavaClass(): java.lang.Class<T>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>typeinfo(): TypeInfo<T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt743.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt743.txt
new file mode 100644
index 0000000000000..bf9c380a76d04
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt743.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class List</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ head: T, /*1*/ tail: List<T>? = ?): List<T>
+ internal final val head: T
+ internal final val tail: List<T>?
+}
+internal final fun </*0*/ T : jet.Any?>foo(/*0*/ t: T): T
+internal final fun </*0*/ T : jet.Any?, /*1*/ Q : jet.Any?>List<T>.map(/*0*/ f: jet.Function1<T, Q>): List<T>?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt750.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt750.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt750.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt762.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt762.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt762.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt847.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt847.txt
new file mode 100644
index 0000000000000..70b47b23e1705
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt847.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>T.mustBe(/*0*/ t: T): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt860.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt860.txt
new file mode 100644
index 0000000000000..7d99e93722a59
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt860.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kotlin">
+namespace kotlin
+
+// <namespace name="util">
+namespace util
+
+internal final fun </*0*/ T : jet.Any?, /*1*/ U : java.util.Collection<in T>>jet.Iterator<T>.to(/*0*/ container: U): U
+internal final fun </*0*/ T : jet.Any?>jet.Iterator<T>.toArrayList(): java.util.ArrayList<T>
+// </namespace name="util">
+// </namespace name="kotlin">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportFromCurrentWithDifferentName.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportFromCurrentWithDifferentName.txt
new file mode 100644
index 0000000000000..4ea07c437bbc0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportFromCurrentWithDifferentName.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.A : jet.Any {
+ public final /*constructor*/ fun <init>(): a.A
+}
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimes.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimes.txt
new file mode 100644
index 0000000000000..b024e5ffd0869
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimes.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="weatherForecast">
+namespace weatherForecast
+
+internal final fun weatherToday(): jet.String
+// </namespace name="weatherForecast">
+// <namespace name="myApp">
+namespace myApp
+
+internal final fun needUmbrella(): jet.Boolean
+// </namespace name="myApp">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimesStar.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimesStar.txt
new file mode 100644
index 0000000000000..b024e5ffd0869
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimesStar.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="weatherForecast">
+namespace weatherForecast
+
+internal final fun weatherToday(): jet.String
+// </namespace name="weatherForecast">
+// <namespace name="myApp">
+namespace myApp
+
+internal final fun needUmbrella(): jet.Boolean
+// </namespace name="myApp">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportsUselessSimpleImport.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportsUselessSimpleImport.txt
new file mode 100644
index 0000000000000..ec5450c3f40c2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportsUselessSimpleImport.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final val B: a.B
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/initializerScopeOfExtensionProperty.txt b/compiler/testData/lazyResolve/diagnostics/scopes/initializerScopeOfExtensionProperty.txt
new file mode 100644
index 0000000000000..87773d626bbdf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/initializerScopeOfExtensionProperty.txt
@@ -0,0 +1,25 @@
+namespace <root>
+
+// <namespace name="i">
+namespace i
+
+internal final class i.A : jet.Any {
+ public final /*constructor*/ fun <init>(): i.A
+ internal final val ii: jet.Int
+}
+internal final class i.C : jet.Any {
+ public final /*constructor*/ fun <init>(): i.C
+ internal final class i.C.D : jet.Any {
+ public final /*constructor*/ fun <init>(): i.C.D
+ }
+}
+internal final val i.C.bar: i.C.D
+internal final val jet.String.bd: [ERROR : <ERROR FUNCTION RETURN TYPE>]
+internal final val jet.String.bd1: jet.String
+internal final val i.A.foo: [ERROR : Type for ii]
+internal final val i.C.foo: i.C.D
+internal final val i.A.foo1: jet.Int
+internal final val i.C.foo1: i.C.D
+internal final val </*0*/ T : jet.Any?> java.util.List<T>.length: [ERROR : Type for size()]
+internal final val </*0*/ T : jet.Any?> java.util.List<T>.length1: jet.Int
+// </namespace name="i">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1078.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1078.txt
new file mode 100644
index 0000000000000..1b65f105bc8eb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1078.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1078">
+namespace kt1078
+
+internal final class kt1078.B : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1078.B
+ internal final fun bar(): jet.Boolean
+}
+internal final fun foo(): kt1078.B
+internal final fun test(): kt1078.B
+// </namespace name="kt1078">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1244.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1244.txt
new file mode 100644
index 0000000000000..49560a42e0cff
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1244.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt1244">
+namespace kt1244
+
+internal final class kt1244.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1244.A
+ private final var a: jet.String
+}
+internal final class kt1244.B : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1244.B
+}
+// </namespace name="kt1244">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1248.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1248.txt
new file mode 100644
index 0000000000000..4054dfc25e0bd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1248.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="kt1248">
+namespace kt1248
+
+internal abstract trait kt1248.ParseResult</*0*/ out T : jet.Any?> : jet.Any {
+ public abstract val success: jet.Boolean
+ public abstract val value: T
+}
+internal final class kt1248.Success</*0*/ T : jet.Any?> : kt1248.ParseResult<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ value: T): kt1248.Success<T>
+ internal open override /*1*/ val success: jet.Boolean
+ internal open override /*1*/ val value: T
+}
+// </namespace name="kt1248">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt151.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt151.txt
new file mode 100644
index 0000000000000..6b5055cfa2767
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt151.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="kt151">
+namespace kt151
+
+internal open class kt151.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt151.A
+ protected open fun x(): jet.Tuple0
+}
+internal final class kt151.B : kt151.A {
+ public final /*constructor*/ fun <init>(): kt151.B
+ protected open override /*1*/ fun x(): jet.Tuple0
+}
+internal open class kt151.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt151.C
+ internal open fun foo(): jet.Tuple0
+}
+internal final class kt151.D : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.D
+ protected open override /*2*/ fun foo(): jet.Tuple0
+}
+internal final class kt151.E : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.E
+ internal open override /*2*/ fun foo(): jet.Tuple0
+}
+internal final class kt151.F : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.F
+ private open override /*2*/ fun foo(): jet.Tuple0
+}
+internal final class kt151.G : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.G
+ public open override /*2*/ fun foo(): jet.Tuple0
+}
+internal abstract trait kt151.T : jet.Any {
+ protected open fun foo(): jet.Tuple0
+}
+internal final fun test(/*0*/ b: kt151.B): jet.Tuple0
+// </namespace name="kt151">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1579_map_entry.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1579_map_entry.txt
new file mode 100644
index 0000000000000..cc98a11c4fbaf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1579_map_entry.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(/*0*/ b: java.util.Map.Entry<jet.String, jet.String>): java.util.Map.Entry<jet.String, jet.String>
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final fun bar(/*0*/ b: java.util.Map.Entry<jet.String, jet.String>): java.util.Map.Entry<jet.String, jet.String>
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final fun fff(/*0*/ b: java.util.Map.Entry<jet.String, jet.String>): java.util.Map.Entry<jet.String, jet.String>
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1580.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1580.txt
new file mode 100644
index 0000000000000..67c598ce182ca
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1580.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="lib">
+namespace lib
+
+internal abstract trait lib.WithInner : jet.Any {
+ internal abstract trait lib.WithInner.Inner : jet.Any {
+ }
+}
+// </namespace name="lib">
+// <namespace name="user">
+namespace user
+
+internal final fun main(/*0*/ a: lib.WithInner, /*1*/ b: lib.WithInner.Inner): jet.Tuple0
+// </namespace name="user">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1738.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1738.txt
new file mode 100644
index 0000000000000..809fc1501c569
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1738.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1738">
+namespace kt1738
+
+internal final class kt1738.A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int, /*1*/ j: jet.Int): kt1738.A
+ private final var i: jet.Int
+ internal final var j: jet.Int
+}
+internal final fun test(/*0*/ a: kt1738.A): jet.Tuple0
+// </namespace name="kt1738">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1805.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1805.txt
new file mode 100644
index 0000000000000..1d2552ad448e7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1805.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt1805">
+namespace kt1805
+
+internal open class kt1805.Some : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1805.Some
+ private final val privateField: jet.Int
+}
+internal final class kt1805.SomeSubclass : kt1805.Some {
+ public final /*constructor*/ fun <init>(): kt1805.SomeSubclass
+ invisible_fake final override /*1*/ val privateField: jet.Int private get
+ internal final fun test(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
+// </namespace name="kt1805">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1806.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1806.txt
new file mode 100644
index 0000000000000..6b3e7850ff04f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1806.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt1806">
+namespace kt1806
+
+internal final val MyObject: kt1806.MyObject
+internal final val MyObject1: kt1806.<no name provided>
+internal final fun doSmth(/*0*/ s: jet.String): jet.String
+internal final fun test1(): jet.Tuple0
+internal final fun test2(): jet.Tuple0
+// </namespace name="kt1806">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1822.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1822.txt
new file mode 100644
index 0000000000000..42a10a651edb5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1822.txt
@@ -0,0 +1,31 @@
+namespace <root>
+
+// <namespace name="kt1822">
+namespace kt1822
+
+internal open class kt1822.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1822.A
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait kt1822.B : jet.Any {
+ protected open fun foo(): jet.Tuple0
+}
+internal open class kt1822.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1822.C
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait kt1822.D : jet.Any {
+ public open fun foo(): jet.Tuple0
+}
+internal final class kt1822.E : kt1822.A, kt1822.B, kt1822.D {
+ public final /*constructor*/ fun <init>(): kt1822.E
+ public open override /*3*/ fun foo(): jet.Tuple0
+}
+internal final class kt1822.G : kt1822.C, kt1822.T {
+ public final /*constructor*/ fun <init>(): kt1822.G
+ public open override /*2*/ fun foo(): jet.Tuple0
+}
+internal abstract trait kt1822.T : jet.Any {
+ protected open fun foo(): jet.Tuple0
+}
+// </namespace name="kt1822">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt2262.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt2262.txt
new file mode 100644
index 0000000000000..4a824be7d0468
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt2262.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+// <namespace name="kt2262">
+namespace kt2262
+
+internal final class kt2262.Bar : kt2262.Foo {
+ public final /*constructor*/ fun <init>(): kt2262.Bar
+ internal final class kt2262.Bar.Baz : jet.Any {
+ public final /*constructor*/ fun <init>(): kt2262.Bar.Baz
+ internal final val copy: jet.String
+ internal final val j: jet.Int
+ }
+ protected final override /*1*/ val color: jet.String
+ protected final val i: jet.Int
+}
+internal abstract class kt2262.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): kt2262.Foo
+ protected final val color: jet.String
+}
+// </namespace name="kt2262">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt323.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt323.txt
new file mode 100644
index 0000000000000..654e871d558c4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt323.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt323">
+namespace kt323
+
+internal open class kt323.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt323.A
+ internal open var a: jet.Int
+}
+internal final class kt323.B : kt323.A {
+ public final /*constructor*/ fun <init>(): kt323.B
+ internal open override /*1*/ val a: jet.Int
+ internal final var b: jet.Int public get
+ protected final var c: jet.Int private set
+}
+// </namespace name="kt323">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt37.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt37.txt
new file mode 100644
index 0000000000000..71ec1ae45c0a0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt37.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt37">
+namespace kt37
+
+internal final class kt37.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt37.C
+ private final var f: jet.Int
+}
+internal final fun box(): jet.String
+// </namespace name="kt37">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt421Scopes.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt421Scopes.txt
new file mode 100644
index 0000000000000..625a507c5a387
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt421Scopes.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+ internal final val c: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt587.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt587.txt
new file mode 100644
index 0000000000000..9cd8a83d3ab11
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt587.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal final class Main : jet.Any {
+ public final /*constructor*/ fun <init>(): Main
+ internal final object Main.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Main.<no name provided>
+ internal final class Main.<no name provided>.States : jet.Any {
+ public final /*constructor*/ fun <init>(): Main.<no name provided>.States
+ internal final object Main.<no name provided>.States.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Main.<no name provided>.States.<no name provided>
+ public final val N: Main.<no name provided>.States
+ }
+ }
+ }
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt900-1.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-1.txt
new file mode 100644
index 0000000000000..a2782c768468d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-1.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final class c.A : jet.Any {
+ public final /*constructor*/ fun <init>(): c.A
+ internal final object c.A.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): c.A.<no name provided>
+ internal final class c.A.<no name provided>.B : jet.Any {
+ public final /*constructor*/ fun <init>(): c.A.<no name provided>.B
+ internal final object c.A.<no name provided>.B.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): c.A.<no name provided>.B.<no name provided>
+ }
+ }
+ }
+}
+internal final val M: c.M
+internal final fun foo(): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt900-2.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-2.txt
new file mode 100644
index 0000000000000..cc2773f8e563a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-2.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="d">
+namespace d
+
+internal final val A: d.A
+internal final val M: d.M
+internal final var r: d.M.T
+internal final val y: d.M.T
+internal final fun f(): jet.Tuple0
+// </namespace name="d">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt939.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt939.txt
new file mode 100644
index 0000000000000..d3b6a63b4acd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt939.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt939">
+namespace kt939
+
+internal final fun compare(/*0*/ o1: jet.String?, /*1*/ o2: jet.String?): jet.Int
+internal final fun test(): jet.Tuple0
+// </namespace name="kt939">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/stopResolutionOnAmbiguity.txt b/compiler/testData/lazyResolve/diagnostics/scopes/stopResolutionOnAmbiguity.txt
new file mode 100644
index 0000000000000..ded0f368884a5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/stopResolutionOnAmbiguity.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal abstract trait c.B : jet.Any {
+ internal open fun bar(): jet.Tuple0
+}
+internal final class c.C : jet.Any {
+ public final /*constructor*/ fun <init>(): c.C
+ internal final fun bar(): jet.Tuple0
+}
+internal final fun jet.Any?.bar(): jet.Tuple0
+internal final fun test(/*0*/ a: jet.Any?): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/visibility.txt b/compiler/testData/lazyResolve/diagnostics/scopes/visibility.txt
new file mode 100644
index 0000000000000..977bda3f9d270
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/visibility.txt
@@ -0,0 +1,71 @@
+namespace <root>
+
+// <namespace name="test_visibility">
+namespace test_visibility
+
+internal final class test_visibility.A : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.A
+ private final fun f(/*0*/ i: jet.Int): test_visibility.B
+ private final val i: jet.Int
+ internal final fun test(): jet.Tuple0
+ private final val v: test_visibility.B
+}
+internal final class test_visibility.B : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.B
+ internal final fun bMethod(): jet.Tuple0
+}
+internal open class test_visibility.C : test_visibility.T {
+ public final /*constructor*/ fun <init>(): test_visibility.C
+ protected final var i: jet.Int
+ internal final fun test5(): jet.Tuple0
+}
+internal final class test_visibility.D : test_visibility.C {
+ public final /*constructor*/ fun <init>(): test_visibility.D
+ protected final override /*1*/ var i: jet.Int
+ internal final val j: jet.Int
+ internal final override /*1*/ fun test5(): jet.Tuple0
+ internal final fun test6(): jet.Tuple0
+}
+internal final class test_visibility.E : test_visibility.C {
+ public final /*constructor*/ fun <init>(): test_visibility.E
+ protected final override /*1*/ var i: jet.Int
+ internal final override /*1*/ fun test5(): jet.Tuple0
+ internal final fun test7(): jet.Tuple0
+}
+internal final class test_visibility.F : test_visibility.C {
+ public final /*constructor*/ fun <init>(): test_visibility.F
+ protected final override /*1*/ var i: jet.Int
+ internal final override /*1*/ fun test5(): jet.Tuple0
+ internal final fun test8(/*0*/ c: test_visibility.C): jet.Tuple0
+}
+internal final class test_visibility.G : test_visibility.T {
+ public final /*constructor*/ fun <init>(): test_visibility.G
+ internal final fun test8(/*0*/ c: test_visibility.C): jet.Tuple0
+}
+protected final class test_visibility.ProtectedClass : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.ProtectedClass
+}
+protected abstract trait test_visibility.ProtectedTrait : jet.Any {
+}
+internal abstract trait test_visibility.T : jet.Any {
+}
+internal final class test_visibility.Y : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.Y
+ internal final fun test2(): jet.Tuple0
+}
+internal final val internal_val: jet.Int
+private final val private_val: jet.Int
+protected final val protected_val: jet.Int
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Int
+internal final fun internal_fun(): jet.Tuple0
+private final fun private_fun(): jet.Tuple0
+protected final fun protected_fun(): jet.Tuple0
+internal final fun test1(): jet.Tuple0
+internal final fun test3(/*0*/ a: test_visibility.A): jet.Tuple0
+internal final fun test4(/*0*/ c: test_visibility.C): jet.Tuple0
+// </namespace name="test_visibility">
+// <namespace name="test_visibility2">
+namespace test_visibility2
+
+internal final fun test(): jet.Tuple0
+// </namespace name="test_visibility2">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/visibility2.txt b/compiler/testData/lazyResolve/diagnostics/scopes/visibility2.txt
new file mode 100644
index 0000000000000..c7a1fef0d2996
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/visibility2.txt
@@ -0,0 +1,59 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+private open class a.A : jet.Any {
+ public final /*constructor*/ fun <init>(): a.A
+ internal final fun bar(): jet.Tuple0
+}
+private final val PO: a.PO
+private final fun foo(): jet.Tuple0
+internal final fun makeA(): a.A
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final class b.B : a.A {
+ public final /*constructor*/ fun <init>(): b.B
+ invisible_fake final override /*1*/ fun bar(): jet.Tuple0
+}
+internal final class b.NewClass : java.util.ArrayList<java.lang.Integer> {
+ public final /*constructor*/ fun <init>(): b.NewClass
+ public open override /*1*/ fun add(/*0*/ p0: java.lang.Integer): jet.Boolean
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int, /*1*/ p1: java.lang.Integer): jet.Tuple0
+ public open override /*1*/ fun addAll(/*0*/ p0: java.util.Collection<out java.lang.Integer>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: jet.Int, /*1*/ p1: java.util.Collection<out java.lang.Integer>): jet.Boolean
+ public open override /*1*/ fun clear(): jet.Tuple0
+ public open override /*1*/ fun contains(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun containsAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun ensureCapacity(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun get(/*0*/ p0: jet.Int): java.lang.Integer
+ public open override /*1*/ fun indexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun isEmpty(): jet.Boolean
+ public open override /*1*/ fun iterator(): java.util.Iterator<java.lang.Integer>
+ public open override /*1*/ fun lastIndexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun listIterator(): java.util.ListIterator<java.lang.Integer>
+ public open override /*1*/ fun listIterator(/*0*/ p0: jet.Int): java.util.ListIterator<java.lang.Integer>
+ protected final override /*1*/ var modCount: jet.Int
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Int): java.lang.Integer
+ public open override /*1*/ fun removeAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ protected open override /*1*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun retainAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun set(/*0*/ p0: jet.Int, /*1*/ p1: java.lang.Integer): java.lang.Integer
+ public open override /*1*/ fun size(): jet.Int
+ public open override /*1*/ fun subList(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): java.util.List<java.lang.Integer>
+ public open override /*1*/ fun toArray(): jet.Array<jet.Any?>
+ public open override /*1*/ fun </*0*/ T : jet.Any?>toArray(/*0*/ p0: jet.Array<T>): jet.Array<T>
+ public open override /*1*/ fun trimToSize(): jet.Tuple0
+}
+internal final class b.Q : jet.Any {
+ public final /*constructor*/ fun <init>(): b.Q
+ internal final class b.Q.W : jet.Any {
+ public final /*constructor*/ fun <init>(): b.Q.W
+ internal final fun foo(): jet.Tuple0
+ }
+}
+internal final fun test(): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInFunctionBody.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInFunctionBody.txt
new file mode 100644
index 0000000000000..3c8b106de7b4e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInFunctionBody.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(/*0*/ p: jet.Int): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInNestedBlockInFor.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInNestedBlockInFor.txt
new file mode 100644
index 0000000000000..44d0ba473256f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInNestedBlockInFor.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(/*0*/ i: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInClosure.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInClosure.txt
new file mode 100644
index 0000000000000..9e3751a0ccfed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInClosure.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final val f: jet.Function0<jet.Int>
+internal final val i: jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFor.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFor.txt
new file mode 100644
index 0000000000000..8208812b6e320
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFor.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class RedefinePropertyInFor : jet.Any {
+ public final /*constructor*/ fun <init>(): RedefinePropertyInFor
+ internal final fun ff(): jet.Tuple0
+ internal final var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFunction.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFunction.txt
new file mode 100644
index 0000000000000..9990bd4c6a941
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class RedefinePropertyInFunction : jet.Any {
+ public final /*constructor*/ fun <init>(): RedefinePropertyInFunction
+ internal final fun f(): jet.Int
+ internal final var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInFor.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInFor.txt
new file mode 100644
index 0000000000000..d7faa630170d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInFor.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedBlock.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedBlock.txt
new file mode 100644
index 0000000000000..d7faa630170d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedBlock.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosure.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosure.txt
new file mode 100644
index 0000000000000..5d7114f2eee24
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosure.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosureParam.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosureParam.txt
new file mode 100644
index 0000000000000..d7faa630170d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosureParam.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/substitutions/kt1558-short.txt b/compiler/testData/lazyResolve/diagnostics/substitutions/kt1558-short.txt
new file mode 100644
index 0000000000000..3e4365ff960ea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/substitutions/kt1558-short.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun testArrays(/*0*/ ci: java.util.List<jet.Int>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/subtyping/kt-1457.txt b/compiler/testData/lazyResolve/diagnostics/subtyping/kt-1457.txt
new file mode 100644
index 0000000000000..4e199aaf64d42
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/subtyping/kt-1457.txt
@@ -0,0 +1,33 @@
+namespace <root>
+
+internal final class MyListOfPairs</*0*/ T : jet.Any?> : java.util.ArrayList<jet.Tuple2<out T, out T>> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): MyListOfPairs<T>
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int, /*1*/ p1: jet.Tuple2<out T, out T>): jet.Tuple0
+ public open override /*1*/ fun add(/*0*/ p0: jet.Tuple2<out T, out T>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: java.util.Collection<out jet.Tuple2<out T, out T>>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: jet.Int, /*1*/ p1: java.util.Collection<out jet.Tuple2<out T, out T>>): jet.Boolean
+ public open override /*1*/ fun clear(): jet.Tuple0
+ public open override /*1*/ fun contains(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun containsAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun ensureCapacity(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun get(/*0*/ p0: jet.Int): jet.Tuple2<out T, out T>
+ public open override /*1*/ fun indexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun isEmpty(): jet.Boolean
+ public open override /*1*/ fun iterator(): java.util.Iterator<jet.Tuple2<out T, out T>>
+ public open override /*1*/ fun lastIndexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun listIterator(): java.util.ListIterator<jet.Tuple2<out T, out T>>
+ public open override /*1*/ fun listIterator(/*0*/ p0: jet.Int): java.util.ListIterator<jet.Tuple2<out T, out T>>
+ protected final override /*1*/ var modCount: jet.Int
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Int): jet.Tuple2<out T, out T>
+ public open override /*1*/ fun removeAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ protected open override /*1*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun retainAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun set(/*0*/ p0: jet.Int, /*1*/ p1: jet.Tuple2<out T, out T>): jet.Tuple2<out T, out T>
+ public open override /*1*/ fun size(): jet.Int
+ public open override /*1*/ fun subList(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): java.util.List<jet.Tuple2<out T, out T>>
+ public open override /*1*/ fun toArray(): jet.Array<jet.Any?>
+ public open override /*1*/ fun </*0*/ T : jet.Any?>toArray(/*0*/ p0: jet.Array<T>): jet.Array<T>
+ public open override /*1*/ fun trimToSize(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/subtyping/kt2069.txt b/compiler/testData/lazyResolve/diagnostics/subtyping/kt2069.txt
new file mode 100644
index 0000000000000..f3b6159f0df0e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/subtyping/kt2069.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="kt2069">
+namespace kt2069
+
+internal final class kt2069.T : kt2069.T1 {
+ public final /*constructor*/ fun <init>(): kt2069.T
+ internal final fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final object kt2069.T.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): kt2069.T.<no name provided>
+ }
+}
+internal abstract trait kt2069.T1 : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+// </namespace name="kt2069">
diff --git a/compiler/testData/lazyResolve/diagnostics/tuples/BasicTuples.txt b/compiler/testData/lazyResolve/diagnostics/tuples/BasicTuples.txt
new file mode 100644
index 0000000000000..d4170907a0bc6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/tuples/BasicTuples.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(/*0*/ a: jet.Tuple2<out jet.Int, out jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/AmbiguousVararg.txt b/compiler/testData/lazyResolve/diagnostics/varargs/AmbiguousVararg.txt
new file mode 100644
index 0000000000000..9ae417d42d909
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/AmbiguousVararg.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo(/*0*/ vararg t: jet.Int /*jet.IntArray*/): jet.String
+internal final fun foo(/*0*/ vararg t: jet.String /*jet.Array<jet.String>*/): jet.String
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/MoreSpecificVarargsOfEqualLength.txt b/compiler/testData/lazyResolve/diagnostics/varargs/MoreSpecificVarargsOfEqualLength.txt
new file mode 100644
index 0000000000000..f586865c7fb7a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/MoreSpecificVarargsOfEqualLength.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class D : jet.Any {
+ public final /*constructor*/ fun <init>(): D
+ internal final fun from(/*0*/ vararg a: jet.Any /*jet.Array<jet.Any>*/): jet.Tuple0
+ internal final fun from(/*0*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.Tuple0
+}
+internal final fun main(/*0*/ d: D): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/MostSepcificVarargsWithJava.txt b/compiler/testData/lazyResolve/diagnostics/varargs/MostSepcificVarargsWithJava.txt
new file mode 100644
index 0000000000000..1f37d7bfc50b0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/MostSepcificVarargsWithJava.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+public open class C : java.lang.Object {
+ public final /*constructor*/ fun <init>(): C
+ package open fun from(): jet.Tuple0
+ package open fun from(/*0*/ s1: jet.String?, /*1*/ vararg s: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+ package open fun from(/*0*/ s: jet.String?): jet.Tuple0
+ package open fun from(/*0*/ s: jet.String?, /*1*/ s1: jet.String?): jet.Tuple0
+ package open fun from(/*0*/ vararg s: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
+internal final fun main(/*0*/ j: C, /*1*/ s: jet.Array<jet.String?>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/NilaryVsVararg.txt b/compiler/testData/lazyResolve/diagnostics/varargs/NilaryVsVararg.txt
new file mode 100644
index 0000000000000..f996f8debcbb1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/NilaryVsVararg.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo0(): jet.String
+internal final fun foo0(/*0*/ vararg t: jet.Int /*jet.IntArray*/): jet.String
+internal final fun test0(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/UnaryVsVararg.txt b/compiler/testData/lazyResolve/diagnostics/varargs/UnaryVsVararg.txt
new file mode 100644
index 0000000000000..a2a5212852fad
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/UnaryVsVararg.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo1(/*0*/ a: jet.Int): jet.String
+internal final fun foo1(/*0*/ a: jet.Int, /*1*/ vararg t: jet.Int /*jet.IntArray*/): jet.String
+internal final fun test1(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1781.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1781.txt
new file mode 100644
index 0000000000000..eb653699101be
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1781.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+public open class JavaClass : java.lang.Object {
+ public final /*constructor*/ fun <init>(): JavaClass
+ public final /*constructor*/ fun <init>(/*0*/ vararg ss: jet.String? /*jet.Array<jet.String?>*/): JavaClass
+}
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1835.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1835.txt
new file mode 100644
index 0000000000000..39182329abd27
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1835.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+public open class JavaClass : java.lang.Object {
+ public final /*constructor*/ fun <init>(): JavaClass
+ package open fun from(/*0*/ s: jet.String?): jet.Tuple0
+ package open fun from(/*0*/ vararg s: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-param.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-param.txt
new file mode 100644
index 0000000000000..b0f8c7c49f3d2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-param.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ vararg t: jet.Int /*jet.IntArray*/): A
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-val.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-val.txt
new file mode 100644
index 0000000000000..cae074c94a972
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-val.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ vararg t: jet.Int /*jet.IntArray*/): A
+ internal final val t: jet.IntArray
+}
diff --git a/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java b/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java
index 77b940858ad37..00c5f0ae8985c 100644
--- a/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java
+++ b/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java
@@ -37,7 +37,8 @@
*/
public abstract class AbstractDiagnosticsTestWithEagerResolve extends AbstractJetDiagnosticsTest {
- protected void analyzeAndCheck(String expectedText, List<TestFile> testFiles) {
+ @Override
+ protected void analyzeAndCheck(File testDataFile, String expectedText, List<TestFile> testFiles) {
List<JetFile> jetFiles = getJetFiles(testFiles);
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
diff --git a/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java
index 224b863d6a397..5bf46e99695b9 100644
--- a/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java
+++ b/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java
@@ -86,10 +86,10 @@ public TestFile create(String fileName, String text) {
getEnvironment().addToClasspath(javaFilesDir);
}
- analyzeAndCheck(expectedText, testFiles);
+ analyzeAndCheck(file, expectedText, testFiles);
}
- protected abstract void analyzeAndCheck(String expectedText, List<TestFile> files);
+ protected abstract void analyzeAndCheck(File testDataFile, String expectedText, List<TestFile> files);
protected static List<JetFile> getJetFiles(List<TestFile> testFiles) {
List<JetFile> jetFiles = Lists.newArrayList();
diff --git a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java
index 72a492a53e876..5be6dfd47c316 100644
--- a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java
+++ b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java
@@ -16,15 +16,18 @@
package org.jetbrains.jet.lang.resolve.lazy;
-import com.google.common.base.Predicates;
+import com.google.common.base.Predicate;
+import com.intellij.openapi.util.io.FileUtil;
import junit.framework.TestCase;
import org.jetbrains.jet.ConfigurationKind;
+import org.jetbrains.jet.JetTestUtils;
import org.jetbrains.jet.checkers.AbstractJetDiagnosticsTest;
import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment;
import org.jetbrains.jet.jvm.compiler.NamespaceComparator;
import org.jetbrains.jet.lang.descriptors.ModuleDescriptor;
import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor;
import org.jetbrains.jet.lang.psi.JetFile;
+import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.test.generator.SimpleTestClassModel;
import org.jetbrains.jet.test.generator.TestGenerator;
@@ -37,18 +40,31 @@
* @author abreslav
*/
public abstract class AbstractLazyResolveDiagnosticsTest extends AbstractJetDiagnosticsTest {
+
+ private static final File TEST_DATA_DIR = new File("compiler/testData/diagnostics/tests");
+
@Override
protected JetCoreEnvironment createEnvironment() {
- return createEnvironmentWithMockJdk(ConfigurationKind.ALL);
+ return createEnvironmentWithMockJdk(ConfigurationKind.JDK_AND_ANNOTATIONS);
}
@Override
- protected void analyzeAndCheck(String expectedText, List<TestFile> files) {
+ protected void analyzeAndCheck(File testDataFile, String expectedText, List<TestFile> files) {
List<JetFile> jetFiles = getJetFiles(files);
ModuleDescriptor lazyModule = LazyResolveTestUtil.resolveLazily(jetFiles, getEnvironment());
ModuleDescriptor eagerModule = LazyResolveTestUtil.resolveEagerly(jetFiles, getEnvironment());
- NamespaceComparator.assertNamespacesEqual(eagerModule.getRootNamespace(), lazyModule.getRootNamespace(), false, Predicates.<NamespaceDescriptor>alwaysTrue());
+ String path = JetTestUtils.getFilePath(new File(FileUtil.getRelativePath(TEST_DATA_DIR, testDataFile)));
+ String txtFileRelativePath = path.replaceAll("\\.kt$|\\.ktscript", ".txt");
+ File txtFile = new File("compiler/testData/lazyResolve/diagnostics/" + txtFileRelativePath);
+ NamespaceComparator.compareNamespaces(eagerModule.getRootNamespace(), lazyModule.getRootNamespace(), false,
+ new Predicate<NamespaceDescriptor>() {
+ @Override
+ public boolean apply(NamespaceDescriptor descriptor) {
+ return !Name.identifier("jet").equals(descriptor.getName());
+ }
+ },
+ txtFile);
}
public static void main(String[] args) throws IOException {
@@ -59,7 +75,7 @@ public static void main(String[] args) throws IOException {
"LazyResolveDiagnosticsTestGenerated",
thisClass,
Arrays.asList(
- new SimpleTestClassModel(new File("compiler/testData/diagnostics/tests"), true, "kt", "doTest"),
+ new SimpleTestClassModel(TEST_DATA_DIR, true, "kt", "doTest"),
new SimpleTestClassModel(new File("compiler/testData/diagnostics/tests/script"), true, "ktscript", "doTest")
),
thisClass
|
6b3023c2aa76386a0d3b437d593bfd65697dc169
|
spring-framework
|
HandlerExecutionChain prevents re-adding the- interceptors array to the list (and declares varargs now)--Issue: SPR-12566-
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java
index 80c64e29545f..e09a01986843 100644
--- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java
+++ b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.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.
@@ -21,6 +21,7 @@
import java.util.List;
import org.springframework.util.CollectionUtils;
+import org.springframework.util.ObjectUtils;
/**
* Handler execution chain, consisting of handler object and any handler interceptors.
@@ -45,7 +46,7 @@ public class HandlerExecutionChain {
* @param handler the handler object to execute
*/
public HandlerExecutionChain(Object handler) {
- this(handler, null);
+ this(handler, (HandlerInterceptor[]) null);
}
/**
@@ -54,7 +55,7 @@ public HandlerExecutionChain(Object handler) {
* @param interceptors the array of interceptors to apply
* (in the given order) before the handler itself executes
*/
- public HandlerExecutionChain(Object handler, HandlerInterceptor[] interceptors) {
+ public HandlerExecutionChain(Object handler, HandlerInterceptor... interceptors) {
if (handler instanceof HandlerExecutionChain) {
HandlerExecutionChain originalChain = (HandlerExecutionChain) handler;
this.handler = originalChain.getHandler();
@@ -78,25 +79,25 @@ public Object getHandler() {
}
public void addInterceptor(HandlerInterceptor interceptor) {
- initInterceptorList();
- this.interceptorList.add(interceptor);
+ initInterceptorList().add(interceptor);
}
- public void addInterceptors(HandlerInterceptor[] interceptors) {
- if (interceptors != null) {
- initInterceptorList();
- this.interceptorList.addAll(Arrays.asList(interceptors));
+ public void addInterceptors(HandlerInterceptor... interceptors) {
+ if (!ObjectUtils.isEmpty(interceptors)) {
+ initInterceptorList().addAll(Arrays.asList(interceptors));
}
}
- private void initInterceptorList() {
+ private List<HandlerInterceptor> initInterceptorList() {
if (this.interceptorList == null) {
this.interceptorList = new ArrayList<HandlerInterceptor>();
+ if (this.interceptors != null) {
+ // An interceptor array specified through the constructor
+ this.interceptorList.addAll(Arrays.asList(this.interceptors));
+ }
}
- if (this.interceptors != null) {
- this.interceptorList.addAll(Arrays.asList(this.interceptors));
- this.interceptors = null;
- }
+ this.interceptors = null;
+ return this.interceptorList;
}
/**
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java
index 06495c3b6fd9..6fab48f20276 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.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.
@@ -26,6 +26,7 @@
import org.apache.commons.logging.LogFactory;
import org.springframework.util.CollectionUtils;
+import org.springframework.util.ObjectUtils;
/**
* Handler execution chain, consisting of handler object and any handler interceptors.
@@ -53,7 +54,7 @@ public class HandlerExecutionChain {
* @param handler the handler object to execute
*/
public HandlerExecutionChain(Object handler) {
- this(handler, null);
+ this(handler, (HandlerInterceptor[]) null);
}
/**
@@ -62,7 +63,7 @@ public HandlerExecutionChain(Object handler) {
* @param interceptors the array of interceptors to apply
* (in the given order) before the handler itself executes
*/
- public HandlerExecutionChain(Object handler, HandlerInterceptor[] interceptors) {
+ public HandlerExecutionChain(Object handler, HandlerInterceptor... interceptors) {
if (handler instanceof HandlerExecutionChain) {
HandlerExecutionChain originalChain = (HandlerExecutionChain) handler;
this.handler = originalChain.getHandler();
@@ -76,6 +77,7 @@ public HandlerExecutionChain(Object handler, HandlerInterceptor[] interceptors)
}
}
+
/**
* Return the handler object to execute.
* @return the handler object
@@ -85,25 +87,25 @@ public Object getHandler() {
}
public void addInterceptor(HandlerInterceptor interceptor) {
- initInterceptorList();
- this.interceptorList.add(interceptor);
+ initInterceptorList().add(interceptor);
}
- public void addInterceptors(HandlerInterceptor[] interceptors) {
- if (interceptors != null) {
- initInterceptorList();
- this.interceptorList.addAll(Arrays.asList(interceptors));
+ public void addInterceptors(HandlerInterceptor... interceptors) {
+ if (!ObjectUtils.isEmpty(interceptors)) {
+ initInterceptorList().addAll(Arrays.asList(interceptors));
}
}
- private void initInterceptorList() {
+ private List<HandlerInterceptor> initInterceptorList() {
if (this.interceptorList == null) {
this.interceptorList = new ArrayList<HandlerInterceptor>();
+ if (this.interceptors != null) {
+ // An interceptor array specified through the constructor
+ this.interceptorList.addAll(Arrays.asList(this.interceptors));
+ }
}
- if (this.interceptors != null) {
- this.interceptorList.addAll(Arrays.asList(this.interceptors));
- this.interceptors = null;
- }
+ this.interceptors = null;
+ return this.interceptorList;
}
/**
@@ -117,6 +119,7 @@ public HandlerInterceptor[] getInterceptors() {
return this.interceptors;
}
+
/**
* Apply preHandle methods of registered interceptors.
* @return {@code true} if the execution chain should proceed with the
@@ -124,9 +127,10 @@ public HandlerInterceptor[] getInterceptors() {
* that this interceptor has already dealt with the response itself.
*/
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
- if (getInterceptors() != null) {
- for (int i = 0; i < getInterceptors().length; i++) {
- HandlerInterceptor interceptor = getInterceptors()[i];
+ HandlerInterceptor[] interceptors = getInterceptors();
+ if (!ObjectUtils.isEmpty(interceptors)) {
+ for (int i = 0; i < interceptors.length; i++) {
+ HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandle(request, response, this.handler)) {
triggerAfterCompletion(request, response, null);
return false;
@@ -141,12 +145,12 @@ boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response)
* Apply postHandle methods of registered interceptors.
*/
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception {
- if (getInterceptors() == null) {
- return;
- }
- for (int i = getInterceptors().length - 1; i >= 0; i--) {
- HandlerInterceptor interceptor = getInterceptors()[i];
- interceptor.postHandle(request, response, this.handler, mv);
+ HandlerInterceptor[] interceptors = getInterceptors();
+ if (!ObjectUtils.isEmpty(interceptors)) {
+ for (int i = interceptors.length - 1; i >= 0; i--) {
+ HandlerInterceptor interceptor = interceptors[i];
+ interceptor.postHandle(request, response, this.handler, mv);
+ }
}
}
@@ -158,16 +162,16 @@ void applyPostHandle(HttpServletRequest request, HttpServletResponse response, M
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex)
throws Exception {
- if (getInterceptors() == null) {
- return;
- }
- for (int i = this.interceptorIndex; i >= 0; i--) {
- HandlerInterceptor interceptor = getInterceptors()[i];
- try {
- interceptor.afterCompletion(request, response, this.handler, ex);
- }
- catch (Throwable ex2) {
- logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
+ HandlerInterceptor[] interceptors = getInterceptors();
+ if (!ObjectUtils.isEmpty(interceptors)) {
+ for (int i = this.interceptorIndex; i >= 0; i--) {
+ HandlerInterceptor interceptor = interceptors[i];
+ try {
+ interceptor.afterCompletion(request, response, this.handler, ex);
+ }
+ catch (Throwable ex2) {
+ logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
+ }
}
}
}
@@ -176,22 +180,23 @@ void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse resp
* Apply afterConcurrentHandlerStarted callback on mapped AsyncHandlerInterceptors.
*/
void applyAfterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response) {
- if (getInterceptors() == null) {
- return;
- }
- for (int i = getInterceptors().length - 1; i >= 0; i--) {
- if (interceptors[i] instanceof AsyncHandlerInterceptor) {
- try {
- AsyncHandlerInterceptor asyncInterceptor = (AsyncHandlerInterceptor) this.interceptors[i];
- asyncInterceptor.afterConcurrentHandlingStarted(request, response, this.handler);
- }
- catch (Throwable ex) {
- logger.error("Interceptor [" + interceptors[i] + "] failed in afterConcurrentHandlingStarted", ex);
+ HandlerInterceptor[] interceptors = getInterceptors();
+ if (!ObjectUtils.isEmpty(interceptors)) {
+ for (int i = interceptors.length - 1; i >= 0; i--) {
+ if (interceptors[i] instanceof AsyncHandlerInterceptor) {
+ try {
+ AsyncHandlerInterceptor asyncInterceptor = (AsyncHandlerInterceptor) interceptors[i];
+ asyncInterceptor.afterConcurrentHandlingStarted(request, response, this.handler);
+ }
+ catch (Throwable ex) {
+ logger.error("Interceptor [" + interceptors[i] + "] failed in afterConcurrentHandlingStarted", ex);
+ }
}
}
}
}
+
/**
* Delegates to the handler's {@code toString()}.
*/
diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java
index 9d408be31059..b2aac29ac907 100644
--- a/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java
+++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.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.
@@ -46,6 +46,7 @@ public class HandlerExecutionChainTests {
private AsyncHandlerInterceptor interceptor3;
+
@Before
public void setup() {
this.request = new MockHttpServletRequest();
@@ -60,9 +61,12 @@ public void setup() {
this.chain.addInterceptor(this.interceptor1);
this.chain.addInterceptor(this.interceptor2);
+ assertEquals(2, this.chain.getInterceptors().length);
this.chain.addInterceptor(this.interceptor3);
+ assertEquals(3, this.chain.getInterceptors().length);
}
+
@Test
public void successScenario() throws Exception {
ModelAndView mav = new ModelAndView();
|
ad7d030f22ff9450aaff6991680613ee5f90b792
|
camel
|
fixed test case which was failing sometimes on- linux--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@576445 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java b/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java
index 8148943c3ba9c..5ee3229aaa570 100644
--- a/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java
+++ b/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java
@@ -45,7 +45,7 @@ public void testSendAccountBean() throws Exception {
assertMockEndpointsSatisifed();
List<Exchange> list = endpoint.getReceivedExchanges();
- Exchange exchange = list.get(0);
+ Exchange exchange = list.get(list.size() - 1);
List body = exchange.getIn().getBody(List.class);
assertNotNull("Should have returned a List!", body);
assertEquals("Wrong size: " + body, 1, body.size());
|
672a790148381c4a91b8a862959d97096a7bb513
|
intellij-community
|
NPE--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/lang-api/src/com/intellij/psi/search/PsiSearchScopeUtil.java b/lang-api/src/com/intellij/psi/search/PsiSearchScopeUtil.java
index da5b8a1fe907e..9a7ebb9d0278d 100644
--- a/lang-api/src/com/intellij/psi/search/PsiSearchScopeUtil.java
+++ b/lang-api/src/com/intellij/psi/search/PsiSearchScopeUtil.java
@@ -73,14 +73,14 @@ public static boolean isInScope(SearchScope scope, PsiElement element) {
return false;
}
else {
- GlobalSearchScope _scope = (GlobalSearchScope)scope;
-
+ GlobalSearchScope globalScope = (GlobalSearchScope)scope;
PsiFile file = element.getContainingFile();
if (file != null) {
final PsiElement context = file.getContext();
if (context != null) file = context.getContainingFile();
- if (file.getVirtualFile() == null) return true; //?
- return _scope.contains(file.getVirtualFile());
+ if (file == null) return false;
+ VirtualFile virtualFile = file.getVirtualFile();
+ return virtualFile == null || globalScope.contains(file.getVirtualFile());
}
else {
return true;
|
c80b498367e99bae4ad7638e37874d5f58f7ea05
|
Vala
|
json-glib-1.0: Make json_parser_load_from_data.length default to -1
Fixes bug 612601.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/json-glib-1.0.vapi b/vapi/json-glib-1.0.vapi
index 5bedfaa9b3..f5195cb762 100644
--- a/vapi/json-glib-1.0.vapi
+++ b/vapi/json-glib-1.0.vapi
@@ -117,7 +117,7 @@ namespace Json {
public uint get_current_pos ();
public unowned Json.Node get_root ();
public bool has_assignment (out unowned string variable_name);
- public bool load_from_data (string data, ssize_t length) throws GLib.Error;
+ public bool load_from_data (string data, ssize_t length = -1) throws GLib.Error;
public bool load_from_file (string filename) throws GLib.Error;
public virtual signal void array_element (Json.Array array, int index_);
public virtual signal void array_end (Json.Array array);
diff --git a/vapi/packages/json-glib-1.0/json-glib-1.0.metadata b/vapi/packages/json-glib-1.0/json-glib-1.0.metadata
index 5feb0d7627..ed1a81c450 100644
--- a/vapi/packages/json-glib-1.0/json-glib-1.0.metadata
+++ b/vapi/packages/json-glib-1.0/json-glib-1.0.metadata
@@ -26,4 +26,4 @@ json_object_get_values type_arguments="unowned Node" transfer_ownership="1"
json_object_add_member.node transfer_ownership="1"
json_object_set_array_member.value transfer_ownership="1"
json_object_set_object_member.value transfer_ownership="1"
-
+json_parser_load_from_data.length default_value="-1"
|
439a23d21eff5b4ff9ba58465be0bc54f305fedd
|
Delta Spike
|
fix owb managed version handling for openejb
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml
index b4676ace5..1b05f5331 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.0</openejb.version>
+ <openejb.version>4.5.1</openejb.version>
<openejb.owb.version>${owb.version}</openejb.owb.version>
</properties>
@@ -79,6 +79,18 @@
<version>${openejb.owb.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.openwebbeans</groupId>
+ <artifactId>openwebbeans-spi</artifactId>
+ <version>${openejb.owb.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.openwebbeans</groupId>
+ <artifactId>openwebbeans-web</artifactId>
+ <version>${openejb.owb.version}</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.apache.openwebbeans</groupId>
<artifactId>openwebbeans-ee-common</artifactId>
|
24f734d135e137229294f4478b2aba251b4184d3
|
camel
|
Fix for MulticastStreamCachingTest after- interceptor changes--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@658260 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/camel-core/pom.xml b/camel-core/pom.xml
index e33f3ca66bf92..bace8f7a95560 100755
--- a/camel-core/pom.xml
+++ b/camel-core/pom.xml
@@ -114,7 +114,6 @@
<excludes>
<!-- TODO FIXME ASAP -->
<exclude>**/InterceptorLogTest.*</exclude>
- <exclude>**/MulticastStreamCachingTest.*</exclude>
</excludes>
</configuration>
</plugin>
diff --git a/camel-core/src/main/java/org/apache/camel/model/MulticastType.java b/camel-core/src/main/java/org/apache/camel/model/MulticastType.java
index 98cc1360a6492..4acfd1b4bae4f 100644
--- a/camel-core/src/main/java/org/apache/camel/model/MulticastType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/MulticastType.java
@@ -30,6 +30,7 @@
import org.apache.camel.processor.MulticastProcessor;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.processor.aggregate.UseLatestAggregationStrategy;
+import org.apache.camel.processor.interceptor.StreamCachingInterceptor;
/**
* @version $Revision$
@@ -88,6 +89,6 @@ public void setThreadPoolExecutor(ThreadPoolExecutor executor) {
@Override
protected Processor wrapProcessorInInterceptors(RouteContext routeContext, Processor target) throws Exception {
// No need to wrap me in interceptors as they are all applied directly to my children
- return target;
+ return new StreamCachingInterceptor(target);
}
}
\ No newline at end of file
diff --git a/camel-core/src/test/java/org/apache/camel/processor/MulticastStreamCachingTest.java b/camel-core/src/test/java/org/apache/camel/processor/MulticastStreamCachingTest.java
index 82d9c9743cbec..7364e24cc7e98 100644
--- a/camel-core/src/test/java/org/apache/camel/processor/MulticastStreamCachingTest.java
+++ b/camel-core/src/test/java/org/apache/camel/processor/MulticastStreamCachingTest.java
@@ -76,7 +76,7 @@ public void process(Exchange exchange) {
return new RouteBuilder() {
public void configure() {
//stream caching should fix re-readability issues when multicasting messags
- from("direct:a").streamCaching().multicast().to("direct:x", "direct:y", "direct:z");
+ from("direct:a").multicast().to("direct:x", "direct:y", "direct:z");
from("direct:x").process(processor).to("mock:x");
from("direct:y").process(processor).to("mock:y");
|
6cb363ffc6c515d1b9df760d31ee489b3877c4d5
|
restlet-framework-java
|
Fix issue -853--DefaultSslContextFactory would ignore enabledCipherSuites unless you also specified enabledProtocols
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java b/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java
index ee444ce008..d1b7addff2 100644
--- a/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java
+++ b/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java
@@ -686,7 +686,7 @@ public void init(Series<Parameter> helperParameters) {
enabledProtocols.toArray(enabledProtocolsArray);
setEnabledProtocols(enabledProtocolsArray);
} else {
- setEnabledCipherSuites(null);
+ setEnabledProtocols(null);
}
setKeyManagerAlgorithm(helperParameters.getFirstValue(
|
66b20f84864ea54b306cc5bc57c0939d80588f88
|
hadoop
|
YARN-295. Fixed a race condition in ResourceManager- RMAppAttempt state machine. Contributed by Mayank Bansal. svn merge- --ignore-ancestry -c 1501856 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1501857 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 83fb4293beb6a..6ca375b0e684e 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -46,6 +46,9 @@ Release 2.1.1-beta - UNRELEASED
YARN-368. Fixed a typo in error message in Auxiliary services. (Albert Chu
via vinodkv)
+ YARN-295. Fixed a race condition in ResourceManager RMAppAttempt state
+ machine. (Mayank Bansal via vinodkv)
+
Release 2.1.0-beta - 2013-07-02
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
index dd9c42260a62d..11fdd9442f06f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
@@ -245,6 +245,10 @@ RMAppAttemptEventType.LAUNCH_FAILED, new LaunchFailedTransition())
.addTransition(RMAppAttemptState.ALLOCATED, RMAppAttemptState.KILLED,
RMAppAttemptEventType.KILL, new KillAllocatedAMTransition())
+ .addTransition(RMAppAttemptState.ALLOCATED, RMAppAttemptState.FAILED,
+ RMAppAttemptEventType.CONTAINER_FINISHED,
+ new AMContainerCrashedTransition())
+
// Transitions from LAUNCHED State
.addTransition(RMAppAttemptState.LAUNCHED, RMAppAttemptState.RUNNING,
RMAppAttemptEventType.REGISTERED, new AMRegisteredTransition())
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java
index a394110b46931..cafe4f9a7056a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java
@@ -654,6 +654,20 @@ public void testAllocatedToFailed() {
testAppAttemptFailedState(amContainer, diagnostics);
}
+ @Test
+ public void testAMCrashAtAllocated() {
+ Container amContainer = allocateApplicationAttempt();
+ String containerDiagMsg = "some error";
+ int exitCode = 123;
+ ContainerStatus cs =
+ BuilderUtils.newContainerStatus(amContainer.getId(),
+ ContainerState.COMPLETE, containerDiagMsg, exitCode);
+ applicationAttempt.handle(new RMAppAttemptContainerFinishedEvent(
+ applicationAttempt.getAppAttemptId(), cs));
+ assertEquals(RMAppAttemptState.FAILED,
+ applicationAttempt.getAppAttemptState());
+ }
+
@Test
public void testRunningToFailed() {
Container amContainer = allocateApplicationAttempt();
|
910b7e5bf582c4a6bb8a55bc2129a968e0aacb64
|
tapiji
|
Lift root pom into the repository root directory.
Provides a more transparent architecture for tycho build scripts. Moreover, missing license headers are added.
(cherry picked from commit 6e1f55383f0af834b148f77992d251cc5c5286b7)
Conflicts:
pom.xml
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.tapiji.tools.parent/.classpath b/org.eclipse.babel.tapiji.tools.parent/.classpath
deleted file mode 100644
index b6fb50ec..00000000
--- a/org.eclipse.babel.tapiji.tools.parent/.classpath
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
- <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
diff --git a/org.eclipse.babel.tapiji.tools.parent/.project b/org.eclipse.babel.tapiji.tools.parent/.project
deleted file mode 100644
index 4d4e7268..00000000
--- a/org.eclipse.babel.tapiji.tools.parent/.project
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.babel.tapiji.tools.parent</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.m2e.core.maven2Builder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.m2e.core.maven2Nature</nature>
- </natures>
-</projectDescription>
diff --git a/org.eclipse.babel.tapiji.tools.parent/pom.xml b/pom.xml
similarity index 78%
rename from org.eclipse.babel.tapiji.tools.parent/pom.xml
rename to pom.xml
index 76194708..601ac116 100644
--- a/org.eclipse.babel.tapiji.tools.parent/pom.xml
+++ b/pom.xml
@@ -80,17 +80,16 @@
</plugins>
</build>
<modules>
- <module>../org.eclipse.babel.core</module>
- <module>../org.eclipse.babel.editor</module>
- <module>../org.eclipse.babel.tapiji.tools.core</module>
- <module>../org.eclipse.babel.tapiji.tools.core.ui</module>
- <module>../org.eclipse.babel.tapiji.tools.java</module>
- <module>../org.eclipse.babel.tapiji.tools.java.feature</module>
- <module>../org.eclipse.babel.tapiji.tools.java.ui</module>
- <module>../org.eclipse.babel.tapiji.tools.rbmanager</module>
- <module>../org.eclipse.babel.editor.nls</module>
- <module>../org.eclipse.babel.tapiji.tools.target</module>
- <module>../org.eclipse.babel.core.pdeutils</module>
- <module>../org.eclipse.babel.editor.rcp.compat</module>
+ <module>org.eclipse.babel.core</module>
+ <module>org.eclipse.babel.editor</module>
+ <module>org.eclipse.babel.tapiji.tools.core</module>
+ <module>org.eclipse.babel.tapiji.tools.core.ui</module>
+ <module>org.eclipse.babel.tapiji.tools.java</module>
+ <module>org.eclipse.babel.tapiji.tools.java.feature</module>
+ <module>org.eclipse.babel.tapiji.tools.java.ui</module>
+ <module>org.eclipse.babel.tapiji.tools.rbmanager</module>
+ <module>org.eclipse.babel.editor.nls</module>
+ <module>org.eclipse.babel.tapiji.tools.target</module>
+ <module>org.eclipse.babel.core.pdeutils</module>
</modules>
</project>
|
8800bab8a660f5ab9e2b100cee51af8a462d220c
|
spring-framework
|
DataSourceUtils lets timeout exceptions through- even for setReadOnly calls (revised; SPR-7226)--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java
index 73612fe5a3b4..5bf57f3e3691 100644
--- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java
+++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2010 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.
@@ -18,7 +18,6 @@
import java.sql.Connection;
import java.sql.SQLException;
-
import javax.sql.DataSource;
import org.springframework.beans.factory.InitializingBean;
@@ -236,7 +235,7 @@ protected void doBegin(Object transaction, TransactionDefinition definition) {
}
}
- catch (SQLException ex) {
+ catch (Exception ex) {
DataSourceUtils.releaseConnection(con, this.dataSource);
throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
}
diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java
index bb79f43d87e1..d6c57f9aee9f 100644
--- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java
+++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java
@@ -154,14 +154,28 @@ public static Integer prepareConnectionForTransaction(Connection con, Transactio
}
con.setReadOnly(true);
}
- catch (Throwable ex) {
- if (ex instanceof SQLException && (ex.getClass().getSimpleName().contains("Timeout") ||
- (ex.getCause() != null && ex.getCause().getClass().getSimpleName().contains("Timeout")))) {
- // Assume it's a connection timeout that would otherwise get lost: e.g. from C3P0.
- throw (SQLException) ex;
+ catch (SQLException ex) {
+ Throwable exToCheck = ex;
+ while (exToCheck != null) {
+ if (exToCheck.getClass().getSimpleName().contains("Timeout")) {
+ // Assume it's a connection timeout that would otherwise get lost: e.g. from JDBC 4.0
+ throw ex;
+ }
+ exToCheck = exToCheck.getCause();
}
- // "read-only not supported" SQLException or UnsupportedOperationException
- // -> ignore, it's just a hint anyway.
+ // "read-only not supported" SQLException -> ignore, it's just a hint anyway
+ logger.debug("Could not set JDBC Connection read-only", ex);
+ }
+ catch (RuntimeException ex) {
+ Throwable exToCheck = ex;
+ while (exToCheck != null) {
+ if (exToCheck.getClass().getSimpleName().contains("Timeout")) {
+ // Assume it's a connection timeout that would otherwise get lost: e.g. from Hibernate
+ throw ex;
+ }
+ exToCheck = exToCheck.getCause();
+ }
+ // "read-only not supported" UnsupportedOperationException -> ignore, it's just a hint anyway
logger.debug("Could not set JDBC Connection read-only", ex);
}
}
|
9ef7a9c6df9d0e7398c838de6a284fb141a86cf4
|
Delta Spike
|
DELTASPIKE-344 provide getContextualReference with a BeanManager param
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java
index 9c2381462..ca7d0c759 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java
@@ -115,6 +115,29 @@ public static <T> T getContextualReference(Class<T> type, Annotation... qualifie
public static <T> T getContextualReference(Class<T> type, boolean optional, Annotation... qualifiers)
{
BeanManager beanManager = getBeanManager();
+
+ return getContextualReference(beanManager, type, optional, qualifiers);
+ }
+
+ /**
+ * {@link #getContextualReference(Class, Annotation...)} which returns <code>null</code> if the
+ * 'optional' parameter is set to <code>true</code>.
+ * This method is intended for usage where the BeanManger is known, e.g. in Extensions.
+ *
+ * @param beanManager the BeanManager to use
+ * @param type the type of the bean in question
+ * @param optional if <code>true</code> it will return <code>null</code> if no bean could be found or created.
+ * Otherwise it will throw an {@code IllegalStateException}
+ * @param qualifiers additional qualifiers which further distinct the resolved bean
+ * @param <T> target type
+ * @return the resolved Contextual Reference
+ * @see #getContextualReference(Class, Annotation...)
+ */
+ public static <T> T getContextualReference(BeanManager beanManager,
+ Class<T> type,
+ boolean optional,
+ Annotation... qualifiers)
+ {
Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers);
if (beans == null || beans.isEmpty())
|
0773327a0f169f69d00dfc85eee0cfea3b40dd14
|
Search_api
|
Issue #2150347 by drunken monkey: Added access callbacks for indexes and servers.
|
a
|
https://github.com/lucidworks/drupal_search_api
|
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index 447cb83c..c73ea285 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -1,5 +1,6 @@
Search API 1.x, dev (xx/xx/xxxx):
---------------------------------
+- #2150347 by drunken monkey: Added access callbacks for indexes and servers.
Search API 1.10 (12/09/2013):
-----------------------------
diff --git a/search_api.module b/search_api.module
index 7c44dbe0..4086764e 100644
--- a/search_api.module
+++ b/search_api.module
@@ -392,6 +392,7 @@ function search_api_entity_info() {
'entity class' => 'SearchApiServer',
'base table' => 'search_api_server',
'uri callback' => 'search_api_server_url',
+ 'access callback' => 'search_api_entity_access',
'module' => 'search_api',
'exportable' => TRUE,
'entity keys' => array(
@@ -407,6 +408,7 @@ function search_api_entity_info() {
'entity class' => 'SearchApiIndex',
'base table' => 'search_api_index',
'uri callback' => 'search_api_index_url',
+ 'access callback' => 'search_api_entity_access',
'module' => 'search_api',
'exportable' => TRUE,
'entity keys' => array(
@@ -2362,6 +2364,15 @@ function search_api_access_delete_page(Entity $entity) {
return user_access('administer search_api') && $entity->hasStatus(ENTITY_CUSTOM);
}
+/**
+ * Determines whether a user can access a certain search server or index.
+ *
+ * Used as an access callback in search_api_entity_info().
+ */
+function search_api_entity_access() {
+ return user_access('administer search_api');
+}
+
/**
* Inserts a new search server into the database.
*
|
06ef3883f57116596653cf68e7728e0d695e45b0
|
Valadoc
|
coding style changes
|
p
|
https://github.com/GNOME/vala/
|
diff --git a/src/doclets/devhelp/doclet.vala b/src/doclets/devhelp/doclet.vala
index 26b8c55ce0..bd10d48092 100644
--- a/src/doclets/devhelp/doclet.vala
+++ b/src/doclets/devhelp/doclet.vala
@@ -45,7 +45,8 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
}
private string get_real_path (Api.Node element) {
- return GLib.Path.build_filename (this.settings.path, this.package_dir_name, element.get_full_name () + ".html");
+ return GLib.Path.build_filename (this.settings.path,
+ this.package_dir_name, element.get_full_name () + ".html");
}
protected override string get_icon_directory () {
@@ -56,7 +57,10 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
public override void process (Settings settings, Api.Tree tree, ErrorReporter reporter) {
base.process (settings, tree, reporter);
DirUtils.create_with_parents (this.settings.path, 0777);
- write_wiki_pages (tree, css_path_wiki, js_path_wiki, Path.build_filename (this.settings.path, this.settings.pkg_name));
+ write_wiki_pages (tree,
+ css_path_wiki,
+ js_path_wiki,
+ Path.build_filename (this.settings.path, this.settings.pkg_name));
tree.accept (this);
}
@@ -85,8 +89,12 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
var devfile = FileStream.open (devpath, "w");
_devhelpwriter = new Devhelp.MarkupWriter (devfile);
- _devhelpwriter.start_book (pkg_name+" Reference Manual", "vala", "index.htm", pkg_name, "", "");
-
+ _devhelpwriter.start_book (pkg_name+" Reference Manual",
+ "vala",
+ "index.htm",
+ pkg_name,
+ "",
+ "");
GLib.FileStream file = GLib.FileStream.open (filepath, "w");
writer = new Html.MarkupWriter (file);
@@ -120,7 +128,9 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
typekeyword = "struct";
}
- _devhelpwriter.simple_tag ("keyword", {"type", typekeyword, "name", node.name, "link", get_link (node, node.package)});
+ _devhelpwriter.simple_tag ("keyword", {"type", typekeyword,
+ "name", node.name,
+ "link", get_link (node, node.package)});
}
_devhelpwriter.end_functions ();
@@ -135,7 +145,9 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
GLib.FileStream file = GLib.FileStream.open (rpath, "w");
writer = new Html.MarkupWriter (file);
_renderer.set_writer (writer);
- write_file_header (css_path, js_path, node.get_full_name () + " – " + node.package.name);
+ write_file_header (css_path,
+ js_path,
+ node.get_full_name () + " – " + node.package.name);
write_symbol_content (node);
write_file_footer ();
file = null;
@@ -158,7 +170,9 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
GLib.FileStream file = GLib.FileStream.open (rpath, "w");
writer = new Html.MarkupWriter (file);
_renderer.set_writer (writer);
- write_file_header (css_path, js_path, node.get_full_name() + " – " + node.package.name);
+ write_file_header (css_path,
+ js_path,
+ node.get_full_name() + " – " + node.package.name);
write_symbol_content (node);
write_file_footer ();
file = null;
diff --git a/src/doclets/gtkdoc/commentconverter.vala b/src/doclets/gtkdoc/commentconverter.vala
index 5f79f1a7af..91ab7591cb 100644
--- a/src/doclets/gtkdoc/commentconverter.vala
+++ b/src/doclets/gtkdoc/commentconverter.vala
@@ -64,7 +64,8 @@ public class Gtkdoc.CommentConverter : ContentVisitor {
current_builder.append_printf ("<title>%s</title>", em.caption);
}
- current_builder.append_printf ("<mediaobject><imageobject><imagedata fileref=\"%s\"/></imageobject>", em.url);
+ current_builder.append_printf ("<mediaobject><imageobject><imagedata fileref=\"%s\"/></imageobject>",
+ em.url);
if (em.caption != null) {
current_builder.append_printf ("<textobject><phrase>%s</phrase></textobject>", em.caption);
@@ -150,7 +151,8 @@ public class Gtkdoc.CommentConverter : ContentVisitor {
break;
default:
- reporter.simple_warning ("GtkDoc: warning: unsupported list type: %s", list.bullet.to_string ());
+ reporter.simple_warning ("GtkDoc: warning: unsupported list type: %s",
+ list.bullet.to_string ());
break;
}
@@ -286,7 +288,9 @@ public class Gtkdoc.CommentConverter : ContentVisitor {
} else if (t is Taglets.Throws) {
var taglet = (Taglets.Throws) t;
var link = get_docbook_link (taglet.error_domain) ?? taglet.error_domain_name;
- old_builder.append_printf ("\n<para>%s will be returned in @error %s</para>", link, current_builder.str);
+ old_builder.append_printf ("\n<para>%s will be returned in @error %s</para>",
+ link,
+ current_builder.str);
} else {
reporter.simple_warning ("GtkDoc: warning: Taglet not supported"); // TODO
}
diff --git a/src/doclets/gtkdoc/dbus.vala b/src/doclets/gtkdoc/dbus.vala
index c9f0a5fc75..d1474074f8 100644
--- a/src/doclets/gtkdoc/dbus.vala
+++ b/src/doclets/gtkdoc/dbus.vala
@@ -59,7 +59,9 @@ namespace Gtkdoc.DBus {
if (direction == Direction.NONE) {
return """<parameter><type>'%s'</type> %s</parameter>""".printf (signature, name);
} else {
- return """<parameter>%s <type>'%s'</type> %s</parameter>""".printf (direction.to_string(), signature, name);
+ return """<parameter>%s <type>'%s'</type> %s</parameter>""".printf (direction.to_string(),
+ signature,
+ name);
}
}
}
@@ -88,9 +90,15 @@ namespace Gtkdoc.DBus {
if (link) {
builder.append_printf ("""
-<link linkend="%s-%s">%s</link>%s(""", iface.get_docbook_id (), get_docbook_id (), name, string.nfill (indent-name.length, ' '));
+<link linkend="%s-%s">%s</link>%s(""",
+ iface.get_docbook_id (),
+ get_docbook_id (),
+ name,
+ string.nfill (indent-name.length, ' '));
} else {
- builder.append_printf ("\n%s%s(", name, string.nfill (indent-name.length, ' '));
+ builder.append_printf ("\n%s%s(",
+ name,
+ string.nfill (indent-name.length, ' '));
}
if (parameters.size > 0) {
@@ -114,7 +122,11 @@ namespace Gtkdoc.DBus {
public Gee.List<Member> methods = new Gee.LinkedList<Member>();
public Gee.List<Member> signals = new Gee.LinkedList<Member>();
- public Interface (string package_name, string name, string purpose = "", string description = "") {
+ public Interface (string package_name,
+ string name,
+ string purpose = "",
+ string description = "")
+ {
this.package_name = package_name;
this.name = name;
this.purpose = purpose;
@@ -139,10 +151,12 @@ namespace Gtkdoc.DBus {
var xml_dir = Path.build_filename (settings.path, "xml");
DirUtils.create_with_parents (xml_dir, 0777);
- var xml_file = Path.build_filename (xml_dir, "%s.xml".printf (to_docbook_id (name)));
+ var xml_file = Path.build_filename (xml_dir,
+ "%s.xml".printf (to_docbook_id (name)));
var writer = new TextWriter (xml_file, "w");
if (!writer.open ()) {
- reporter.simple_error ("GtkDoc: error: unable to open %s for writing", writer.filename);
+ reporter.simple_error ("GtkDoc: error: unable to open %s for writing",
+ writer.filename);
return false;
}
writer.write_line (to_string (reporter));
@@ -182,7 +196,13 @@ namespace Gtkdoc.DBus {
<refnamediv>
<refname>%s</refname>
<refpurpose>%s</refpurpose>
-</refnamediv>""", docbook_id, docbook_id, name, package_name.up (), name, purpose ?? "");
+</refnamediv>""",
+ docbook_id,
+ docbook_id,
+ name,
+ package_name.up (),
+ name,
+ purpose ?? "");
/*
* Methods
@@ -236,7 +256,12 @@ namespace Gtkdoc.DBus {
<programlisting>%s
</programlisting>
%s
-</refsect2>""", docbook_id, method.get_docbook_id (), method.name, method.to_string (method_indent, false), method.comment != null ? method.comment.to_docbook (reporter) : "");
+</refsect2>""",
+ docbook_id,
+ method.get_docbook_id (),
+ method.name,
+ method.to_string (method_indent, false),
+ method.comment != null ? method.comment.to_docbook (reporter) : "");
}
builder.append ("</refsect1>");
@@ -257,7 +282,12 @@ namespace Gtkdoc.DBus {
<programlisting>%s
</programlisting>
%s
-</refsect2>""", docbook_id, sig.get_docbook_id (), sig.name, sig.to_string (signal_indent, false), sig.comment != null ? sig.comment.to_docbook (reporter) : "");
+</refsect2>""",
+ docbook_id,
+ sig.get_docbook_id (),
+ sig.name,
+ sig.to_string (signal_indent, false),
+ sig.comment != null ? sig.comment.to_docbook (reporter) : "");
}
builder.append ("</refsect1>");
diff --git a/src/doclets/gtkdoc/doclet.vala b/src/doclets/gtkdoc/doclet.vala
index 82871e5846..74e16c16ca 100644
--- a/src/doclets/gtkdoc/doclet.vala
+++ b/src/doclets/gtkdoc/doclet.vala
@@ -196,7 +196,8 @@ public class Gtkdoc.Director : Valadoc.Doclet, Object {
} else if (filename.has_suffix (".h")) {
prepare_h_file (filename);
} else {
- reporter.simple_error ("GtkDoc: error: %s is not a supported source file type. Only .h, and .c files are supported.", relative_filename);
+ reporter.simple_error ("GtkDoc: error: %s is not a supported source file type. Only .h, and .c files are supported.",
+ relative_filename);
}
}
@@ -353,7 +354,8 @@ public class Gtkdoc.Director : Valadoc.Doclet, Object {
try {
FileUtils.get_contents (main_file, out contents);
} catch (Error e) {
- reporter.simple_error ("GtkDoc: error: Error while reading main file '%s' contents: %s", main_file, e.message);
+ reporter.simple_error ("GtkDoc: error: Error while reading main file '%s' contents: %s",
+ main_file, e.message);
return false;
}
@@ -366,12 +368,15 @@ public class Gtkdoc.Director : Valadoc.Doclet, Object {
// hackish but prevents us from re-creating the whole main file,
// which would more even more hackish
var builder = new StringBuilder ();
- builder.append_printf ("\n<chapter>\n<title>%s D-Bus API Reference</title>\n", settings.pkg_name);
+ builder.append_printf ("\n<chapter>\n<title>%s D-Bus API Reference</title>\n",
+ settings.pkg_name);
foreach (var iface in generator.dbus_interfaces) {
- builder.append_printf ("<xi:include href=\"xml/%s.xml\"/>\n", to_docbook_id (iface.name));
+ builder.append_printf ("<xi:include href=\"xml/%s.xml\"/>\n",
+ to_docbook_id (iface.name));
}
- var hierarchy_file = Path.build_filename (settings.path, "%s.hierarchy".printf (settings.pkg_name));
+ var hierarchy_file = Path.build_filename (settings.path, "%s.hierarchy"
+ .printf (settings.pkg_name));
if (FileUtils.test (hierarchy_file, FileTest.EXISTS)) {
// if hierarchy exists, gtkdoc-mkdb will output it
builder.append ("</chapter>\n<chapter id=\"object-tree\">");
@@ -385,7 +390,8 @@ public class Gtkdoc.Director : Valadoc.Doclet, Object {
try {
FileUtils.set_contents (main_file, contents);
} catch (Error e) {
- reporter.simple_error ("GtkDoc: error: Error while writing main file '%s' contents: %s", main_file, e.message);
+ reporter.simple_error ("GtkDoc: error: Error while writing main file '%s' contents: %s",
+ main_file, e.message);
return false;
}
}
diff --git a/src/doclets/gtkdoc/generator.vala b/src/doclets/gtkdoc/generator.vala
index 8829ce7283..1d6f821858 100644
--- a/src/doclets/gtkdoc/generator.vala
+++ b/src/doclets/gtkdoc/generator.vala
@@ -186,7 +186,9 @@ public class Gtkdoc.Generator : Api.Visitor {
return file_data;
}
- private Gee.List<Header> merge_headers (Gee.List<Header> doc_headers, Gee.List<Header>? lang_headers) {
+ private Gee.List<Header> merge_headers (Gee.List<Header> doc_headers,
+ Gee.List<Header>? lang_headers)
+ {
if (lang_headers == null) {
return doc_headers;
}
@@ -230,7 +232,11 @@ public class Gtkdoc.Generator : Api.Visitor {
return headers;
}
- private void set_section_comment (string filename, string section_name, Content.Comment? comment, string symbol_full_name) {
+ private void set_section_comment (string filename,
+ string section_name,
+ Content.Comment? comment,
+ string symbol_full_name)
+ {
var file_data = get_file_data (filename);
if (file_data.title == null) {
file_data.title = section_name;
@@ -253,11 +259,17 @@ public class Gtkdoc.Generator : Api.Visitor {
* forward that as a Valadoc warning so that it doesn’t get lost
* in the gtk-doc output files. */
if (gcomment.long_comment == null || gcomment.long_comment == "") {
- reporter.simple_warning ("Missing long description in the documentation for ‘%s’ which forms gtk-doc section ‘%s’.", symbol_full_name, section_name);
+ reporter.simple_warning ("Missing long description in the documentation for ‘%s’ which forms gtk-doc section ‘%s’.",
+ symbol_full_name,
+ section_name);
}
}
- private GComment create_gcomment (string symbol, Content.Comment? comment, string[]? returns_annotations = null, bool is_dbus = false) {
+ private GComment create_gcomment (string symbol,
+ Content.Comment? comment,
+ string[]? returns_annotations = null,
+ bool is_dbus = false)
+ {
var converter = new Gtkdoc.CommentConverter (reporter, current_method_or_delegate);
if (comment != null) {
@@ -285,7 +297,12 @@ public class Gtkdoc.Generator : Api.Visitor {
return gcomment;
}
- private GComment add_symbol (string filename, string cname, Content.Comment? comment = null, string? symbol = null, string[]? returns_annotations = null) {
+ private GComment add_symbol (string filename,
+ string cname,
+ Content.Comment? comment = null,
+ string? symbol = null,
+ string[]? returns_annotations = null)
+ {
var file_data = get_file_data (filename);
file_data.register_section_line (cname);
@@ -295,7 +312,12 @@ public class Gtkdoc.Generator : Api.Visitor {
return gcomment;
}
- private Header? add_custom_header (string name, string? comment, string[]? annotations = null, double pos = double.MAX, bool block = true) {
+ private Header? add_custom_header (string name,
+ string? comment,
+ string[]? annotations = null,
+ double pos = double.MAX,
+ bool block = true)
+ {
if (comment == null && annotations == null) {
return null;
}
@@ -318,7 +340,11 @@ public class Gtkdoc.Generator : Api.Visitor {
return null;
}
- private Header? add_header (string name, Content.Comment? comment, string[]? annotations = null, double pos = double.MAX) {
+ private Header? add_header (string name,
+ Content.Comment? comment,
+ string[]? annotations = null,
+ double pos = double.MAX)
+ {
if (comment == null && annotations == null) {
return null;
}
@@ -357,7 +383,10 @@ public class Gtkdoc.Generator : Api.Visitor {
public override void visit_namespace (Api.Namespace ns) {
if (ns.get_filename () != null && ns.documentation != null) {
- set_section_comment (ns.get_filename (), get_section (ns.get_filename ()), ns.documentation, ns.get_full_name ());
+ set_section_comment (ns.get_filename (),
+ get_section (ns.get_filename ()),
+ ns.documentation,
+ ns.get_full_name ());
}
ns.accept_all_children (this);
@@ -378,7 +407,10 @@ public class Gtkdoc.Generator : Api.Visitor {
iface.accept_all_children (this);
var gcomment = add_symbol (iface.get_filename(), iface.get_cname(), iface.documentation, null);
- set_section_comment (iface.get_filename(), iface.get_cname(), iface.documentation, iface.get_full_name ());
+ set_section_comment (iface.get_filename(),
+ iface.get_cname(),
+ iface.documentation,
+ iface.get_full_name ());
if (current_dbus_interface != null) {
current_dbus_interface.write (settings, reporter);
@@ -413,9 +445,12 @@ public class Gtkdoc.Generator : Api.Visitor {
foreach (Api.Node _type in type_parameters) {
var type = _type as Api.TypeParameter;
string type_name_down = type.name.down ();
- add_custom_header ("get_%s_type".printf (type_name_down), "The #GType for %s".printf (type_name_down));
- add_custom_header ("get_%s_dup_func".printf (type_name_down), "A dup function for #%sIface.get_%s_type()".printf (iface.get_cname (), type_name_down));
- add_custom_header ("get_%s_destroy_func".printf (type_name_down), "A destroy function for #%sIface.get_%s_type()".printf (iface.get_cname (), type_name_down));
+ add_custom_header ("get_%s_type".printf (type_name_down),
+ "The #GType for %s".printf (type_name_down));
+ add_custom_header ("get_%s_dup_func".printf (type_name_down),
+ "A dup function for #%sIface.get_%s_type()".printf (iface.get_cname (), type_name_down));
+ add_custom_header ("get_%s_destroy_func".printf (type_name_down),
+ "A destroy function for #%sIface.get_%s_type()".printf (iface.get_cname (), type_name_down));
}
}
gcomment = add_symbol (iface.get_filename (), iface.get_cname () + "Iface");
@@ -486,36 +521,49 @@ public class Gtkdoc.Generator : Api.Visitor {
add_custom_header ("name", "canonical name of the property specified");
add_custom_header ("nick", "nick name for the property specified");
add_custom_header ("blurb", "description of the property specified");
- add_custom_header ("object_type", "%s derived type of this property".printf (get_docbook_type_link (cl)));
+ add_custom_header ("object_type", "%s derived type of this property"
+ .printf (get_docbook_type_link (cl)));
add_custom_header ("flags", "flags for the property specified");
gcomment = add_symbol (filename, cl.get_param_spec_function_cname ());
- gcomment.brief_comment = "Creates a new <link linkend=\"GParamSpecBoxed\"><type>GParamSpecBoxed</type></link> instance specifying a %s derived property.".printf (get_docbook_type_link (cl));
+ gcomment.brief_comment = "Creates a new <link linkend=\"GParamSpecBoxed\"><type>GParamSpecBoxed</type></link> instance specifying a %s derived property."
+ .printf (get_docbook_type_link (cl));
gcomment.long_comment = "See <link linkend=\"g-param-spec-internal\"><function>g_param_spec_internal()</function></link> for details on property names.";
// value_set
current_headers.clear ();
- add_custom_header ("value", "a valid <link linkend=\"GValue\"><type>GValue</type></link> of %s derived type".printf (get_docbook_type_link (cl)));
+ add_custom_header ("value", "a valid <link linkend=\"GValue\"><type>GValue</type></link> of %s derived type"
+ .printf (get_docbook_type_link (cl)));
add_custom_header ("v_object", "object value to be set");
gcomment = add_symbol (filename, cl.get_set_value_function_cname ());
- gcomment.brief_comment = "Set the contents of a %s derived <link linkend=\"GValue\"><type>GValue</type></link> to @v_object.".printf (get_docbook_type_link (cl));
+ gcomment.brief_comment = "Set the contents of a %s derived <link linkend=\"GValue\"><type>GValue</type></link> to @v_object."
+ .printf (get_docbook_type_link (cl));
gcomment.long_comment = "<link linkend=\"%s\"><function>%s()</function></link> increases the reference count of @v_object (the <link linkend=\"GValue\"><type>GValue</type></link> holds a reference to @v_object). If you do not wish to increase the reference count of the object (i.e. you wish to pass your current reference to the <link linkend=\"GValue\"><type>GValue</type></link> because you no longer need it), use <link linkend=\"%s\"><function>%s()</function></link> instead.
-It is important that your <link linkend=\"GValue\"><type>GValue</type></link> holds a reference to @v_object (either its own, or one it has taken) to ensure that the object won't be destroyed while the <link linkend=\"GValue\"><type>GValue</type></link> still exists).".printf (to_docbook_id (cl.get_set_value_function_cname ()), cl.get_set_value_function_cname (), to_docbook_id (cl.get_take_value_function_cname ()), cl.get_take_value_function_cname ());
+It is important that your <link linkend=\"GValue\"><type>GValue</type></link> holds a reference to @v_object (either its own, or one it has taken) to ensure that the object won't be destroyed while the <link linkend=\"GValue\"><type>GValue</type></link> still exists)."
+ .printf (to_docbook_id (cl.get_set_value_function_cname ()),
+ cl.get_set_value_function_cname (),
+ to_docbook_id (cl.get_take_value_function_cname ()),
+ cl.get_take_value_function_cname ());
// value_get
current_headers.clear ();
- add_custom_header ("value", "a valid <link linkend=\"GValue\"><type>GValue</type></link> of %s derived type".printf (get_docbook_type_link (cl)));
+ add_custom_header ("value", "a valid <link linkend=\"GValue\"><type>GValue</type></link> of %s derived type"
+ .printf (get_docbook_type_link (cl)));
gcomment = add_symbol (filename, cl.get_get_value_function_cname ());
- gcomment.brief_comment = "Get the contents of a %s derived <link linkend=\"GValue\"><type>GValue</type></link>.".printf (get_docbook_type_link (cl));
+ gcomment.brief_comment = "Get the contents of a %s derived <link linkend=\"GValue\"><type>GValue</type></link>."
+ .printf (get_docbook_type_link (cl));
gcomment.returns = "object contents of @value";
// value_take
current_headers.clear ();
- add_custom_header ("value", "a valid <link linkend=\"GValue\"><type>GValue</type></link> of %s derived type".printf (get_docbook_type_link (cl)));
+ add_custom_header ("value", "a valid <link linkend=\"GValue\"><type>GValue</type></link> of %s derived type"
+ .printf (get_docbook_type_link (cl)));
add_custom_header ("v_object", "object value to be set");
gcomment = add_symbol (filename, cl.get_take_value_function_cname ());
- gcomment.brief_comment = "Sets the contents of a %s derived <link linkend=\"GValue\"><type>GValue</type></link> to @v_object and takes over the ownership of the callers reference to @v_object; the caller doesn't have to unref it any more (i.e. the reference count of the object is not increased).".printf (get_docbook_type_link (cl));
- gcomment.long_comment = "If you want the GValue to hold its own reference to @v_object, use <link linkend=\"%s\"><function>%s()</function></link> instead.".printf (to_docbook_id (cl.get_set_value_function_cname ()), cl.get_set_value_function_cname ());
+ gcomment.brief_comment = "Sets the contents of a %s derived <link linkend=\"GValue\"><type>GValue</type></link> to @v_object and takes over the ownership of the callers reference to @v_object; the caller doesn't have to unref it any more (i.e. the reference count of the object is not increased)."
+ .printf (get_docbook_type_link (cl));
+ gcomment.long_comment = "If you want the GValue to hold its own reference to @v_object, use <link linkend=\"%s\"><function>%s()</function></link> instead."
+ .printf (to_docbook_id (cl.get_set_value_function_cname ()), cl.get_set_value_function_cname ());
}
// Class struct
@@ -539,7 +587,8 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
add_custom_header ("parent_class", "the parent class structure");
gcomment = add_symbol (cl.get_filename (), cl.get_cname () + "Class");
- gcomment.brief_comment = "The class structure for %s. All the fields in this structure are private and should never be accessed directly.".printf (get_docbook_type_link (cl));
+ gcomment.brief_comment = "The class structure for %s. All the fields in this structure are private and should never be accessed directly."
+ .printf (get_docbook_type_link (cl));
// Standard/Private symbols
var file_data = get_file_data (cl.get_filename ());
@@ -552,7 +601,9 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
file_data.register_standard_section_line (cl.get_type_function_name ());
file_data.register_private_section_line (cl.get_private_cname ());
- file_data.register_private_section_line (((cl.nspace.name != null)? cl.nspace.name.down () + "_" : "") + to_lower_case (cl.name) + "_construct");
+ file_data.register_private_section_line (((cl.nspace.name != null)? cl.nspace.name.down () + "_" : "")
+ + to_lower_case (cl.name)
+ + "_construct");
current_cname = old_cname;
current_headers = old_headers;
@@ -597,41 +648,55 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
string? destroy_function_cname = st.get_destroy_function_cname ();
if (dup_function_cname != null) {
var dup_gcomment = add_symbol (st.get_filename (), dup_function_cname);
- dup_gcomment.headers.add (new Header ("self", "the instance to duplicate"));
+ dup_gcomment.headers.add (new Header ("self",
+ "the instance to duplicate"));
if (free_function_cname != null) {
- dup_gcomment.returns = "a copy of @self, free with %s()".printf (free_function_cname);
+ dup_gcomment.returns = "a copy of @self, free with %s()"
+ .printf (free_function_cname);
} else {
dup_gcomment.returns = "a copy of @self";
}
dup_gcomment.brief_comment = "Creates a copy of self.";
- dup_gcomment.see_also = create_see_function_array ({copy_function_cname, destroy_function_cname, free_function_cname});
+ dup_gcomment.see_also = create_see_function_array ({copy_function_cname,
+ destroy_function_cname,
+ free_function_cname});
}
if (free_function_cname != null) {
var free_gcomment = add_symbol (st.get_filename (), free_function_cname);
free_gcomment.headers.add (new Header ("self", "the struct to free"));
free_gcomment.brief_comment = "Frees the heap-allocated struct.";
- free_gcomment.see_also = create_see_function_array ({dup_function_cname, copy_function_cname, destroy_function_cname});
+ free_gcomment.see_also = create_see_function_array ({dup_function_cname,
+ copy_function_cname,
+ destroy_function_cname});
}
if (copy_function_cname != null) {
var copy_gcomment = add_symbol (st.get_filename (), copy_function_cname);
- copy_gcomment.headers.add (new Header ("self", "the struct to copy"));
+ copy_gcomment.headers.add (new Header ("self",
+ "the struct to copy"));
if (destroy_function_cname != null) {
- copy_gcomment.headers.add (new Header ("dest", "a unused struct. Use %s() to free the content.".printf (destroy_function_cname)));
+ copy_gcomment.headers.add (new Header ("dest",
+ "a unused struct. Use %s() to free the content."
+ .printf (destroy_function_cname)));
} else {
- copy_gcomment.headers.add (new Header ("dest", "a unused struct."));
+ copy_gcomment.headers.add (new Header ("dest",
+ "a unused struct."));
}
copy_gcomment.brief_comment = "Creates a copy of self.";
- copy_gcomment.see_also = create_see_function_array ({dup_function_cname, destroy_function_cname, free_function_cname});
+ copy_gcomment.see_also = create_see_function_array ({dup_function_cname,
+ destroy_function_cname,
+ free_function_cname});
}
if (destroy_function_cname != null) {
var destroy_gcomment = add_symbol (st.get_filename (), destroy_function_cname);
destroy_gcomment.headers.add (new Header ("self", "the struct to destroy"));
destroy_gcomment.brief_comment = "Frees the content of the struct pointed by @self.";
- destroy_gcomment.see_also = create_see_function_array ({dup_function_cname, copy_function_cname, free_function_cname});
+ destroy_gcomment.see_also = create_see_function_array ({dup_function_cname,
+ copy_function_cname,
+ free_function_cname});
}
}
@@ -650,7 +715,10 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
var edomain = error as Api.ErrorDomain;
if (edomain != null) {
if (param_header == null) {
- add_custom_header ("error", "location to store the error occuring, or %NULL to ignore", {"error-domains %s".printf (edomain.get_cname ())}, double.MAX-1);
+ add_custom_header ("error",
+ "location to store the error occuring, or %NULL to ignore",
+ {"error-domains %s".printf (edomain.get_cname ())},
+ double.MAX-1);
} else {
// assume the only annotation is error-domains
var annotation = param_header.annotations[0];
@@ -658,7 +726,10 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
param_header.annotations[0] = annotation;
}
} else if (param_header == null) {
- add_custom_header ("error", "location to store the error occuring, or %NULL to ignore", null, double.MAX-1);
+ add_custom_header ("error",
+ "location to store the error occuring, or %NULL to ignore",
+ null,
+ double.MAX - 1);
}
}
@@ -671,7 +742,9 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
current_headers = new Gee.LinkedList<Header>();
edomain.accept_all_children (this);
- var gcomment = add_symbol (edomain.get_filename(), edomain.get_cname(), edomain.documentation);
+ var gcomment = add_symbol (edomain.get_filename(),
+ edomain.get_cname(),
+ edomain.documentation);
// Handle attributes for things like deprecation.
process_attributes (edomain, gcomment);
@@ -733,11 +806,15 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
public override void visit_property (Api.Property prop) {
- if (prop.is_override || prop.is_private || (!prop.is_abstract && !prop.is_virtual && prop.base_property != null)) {
+ if (prop.is_override
+ || prop.is_private
+ || (!prop.is_abstract && !prop.is_virtual && prop.base_property != null))
+ {
return;
}
- var gcomment = add_comment (prop.get_filename(), "%s:%s".printf (current_cname, prop.get_cname ()), prop.documentation);
+ var gcomment = add_comment (prop.get_filename(), "%s:%s"
+ .printf (current_cname, prop.get_cname ()), prop.documentation);
prop.accept_all_children (this);
Api.TypeParameter type_parameter = prop.property_type.data_type as Api.TypeParameter;
@@ -745,8 +822,11 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
if (type_parameter != null) {
if (type_parameter.parent is Api.Class) {
return_type_link = "#%s:%s-type".printf (get_cname (prop.parent), type_parameter.name.down ());
- } else if (type_parameter.parent is Api.Interface && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null) {
- return_type_link = "#_%sIface.get_%s_type()".printf (get_cname (type_parameter.parent), type_parameter.name.down ());
+ } else if (type_parameter.parent is Api.Interface
+ && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null)
+ {
+ return_type_link = "#_%sIface.get_%s_type()"
+ .printf (get_cname (type_parameter.parent), type_parameter.name.down ());
}
}
@@ -755,18 +835,25 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
if (prop.getter != null && !prop.getter.is_private && prop.getter.is_get) {
var getter_gcomment = add_symbol (prop.get_filename(), prop.getter.get_cname ());
- getter_gcomment.headers.add (new Header ("self", "the %s instance to query".printf (get_docbook_link (prop.parent)), 1));
- getter_gcomment.returns = "the value of the %s property".printf (get_docbook_link (prop));
+ getter_gcomment.headers.add (new Header ("self",
+ "the %s instance to query".printf (get_docbook_link (prop.parent)), 1));
+ getter_gcomment.returns = "the value of the %s property"
+ .printf (get_docbook_link (prop));
if (return_type_link != null) {
getter_gcomment.returns += " of type " + return_type_link;
}
- getter_gcomment.brief_comment = "Get and return the current value of the %s property.".printf (get_docbook_link (prop));
- getter_gcomment.long_comment = combine_comments (gcomment.brief_comment, gcomment.long_comment);
+ getter_gcomment.brief_comment = "Get and return the current value of the %s property."
+ .printf (get_docbook_link (prop));
+ getter_gcomment.long_comment = combine_comments (gcomment.brief_comment,
+ gcomment.long_comment);
if (prop.property_type != null && prop.property_type.data_type is Api.Array) {
var array_type = prop.property_type.data_type;
- for (uint dim = 1; array_type != null && array_type is Api.Array; dim++, array_type = ((Api.Array) array_type).data_type) {
- gcomment.headers.add (new Header ("result_length%u".printf (dim), "return location for the length of the property's value"));
+ for (uint dim = 1; array_type != null && array_type is Api.Array;
+ dim++, array_type = ((Api.Array) array_type).data_type)
+ {
+ gcomment.headers.add (new Header ("result_length%u".printf (dim),
+ "return location for the length of the property's value"));
}
}
@@ -776,16 +863,23 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
if (prop.setter != null && !prop.setter.is_private && prop.setter.is_set) {
var setter_gcomment = add_symbol (prop.get_filename(), prop.setter.get_cname ());
- setter_gcomment.headers.add (new Header ("self", "the %s instance to modify".printf (get_docbook_link (prop.parent)), 1));
+ setter_gcomment.headers.add (new Header ("self", "the %s instance to modify"
+ .printf (get_docbook_link (prop.parent)), 1));
string type_desc = (return_type_link != null)? " of type " + return_type_link : "";
- setter_gcomment.headers.add (new Header ("value", "the new value of the %s property%s".printf (get_docbook_link (prop), type_desc), 2));
- setter_gcomment.brief_comment = "Set the value of the %s property to @value.".printf (get_docbook_link (prop));
- setter_gcomment.long_comment = combine_comments (gcomment.brief_comment, gcomment.long_comment);
+ setter_gcomment.headers.add (new Header ("value", "the new value of the %s property%s"
+ .printf (get_docbook_link (prop), type_desc), 2));
+ setter_gcomment.brief_comment = "Set the value of the %s property to @value."
+ .printf (get_docbook_link (prop));
+ setter_gcomment.long_comment = combine_comments (gcomment.brief_comment,
+ gcomment.long_comment);
if (prop.property_type != null && prop.property_type.data_type is Api.Array) {
var array_type = prop.property_type.data_type;
- for (uint dim = 1; array_type != null && array_type is Api.Array; dim++, array_type = ((Api.Array) array_type).data_type) {
- gcomment.headers.add (new Header ("value_length%u".printf (dim), "length of the property's new value"));
+ for (uint dim = 1; array_type != null && array_type is Api.Array;
+ dim++, array_type = ((Api.Array) array_type).data_type)
+ {
+ gcomment.headers.add (new Header ("value_length%u".printf (dim),
+ "length of the property's new value"));
}
}
@@ -794,7 +888,8 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
if (return_type_link != null) {
- string return_type_desc = "<para>Holds a value from type #%s:%s-type.</para>".printf (get_cname (prop.parent), type_parameter.name.down ());
+ string return_type_desc = "<para>Holds a value from type #%s:%s-type.</para>"
+ .printf (get_cname (prop.parent), type_parameter.name.down ());
gcomment.long_comment = combine_inline_docs (return_type_desc, gcomment.long_comment);
}
}
@@ -845,10 +940,14 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
Api.TypeParameter type_parameter = d.return_type.data_type as Api.TypeParameter;
if (type_parameter != null) {
if (type_parameter.parent is Api.Class) {
- string return_type_desc = "A value from type #%s:%s-type.".printf (get_cname (d.parent), type_parameter.name.down ());
+ string return_type_desc = "A value from type #%s:%s-type."
+ .printf (get_cname (d.parent), type_parameter.name.down ());
gcomment.returns = combine_inline_docs (return_type_desc, gcomment.returns);
- } else if (type_parameter.parent is Api.Interface && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null) {
- string return_type_desc = "A value from type #_%sIface.get_%s_type().".printf (get_cname (d.parent), type_parameter.name.down ());
+ } else if (type_parameter.parent is Api.Interface
+ && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null)
+ {
+ string return_type_desc = "A value from type #_%sIface.get_%s_type()."
+ .printf (get_cname (d.parent), type_parameter.name.down ());
gcomment.returns = combine_inline_docs (return_type_desc, gcomment.returns);
/*
} else if (type_parameter.parent is Api.Struct) {
@@ -884,7 +983,8 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
var gcomment = add_comment (sig.get_filename(), "%s::%s".printf (current_cname, name), sig.documentation);
// gtkdoc maps parameters by their ordering, so let's customly add the first parameter
gcomment.headers.insert (0, new Header (to_lower_case (((Api.Node)sig.parent).name),
- "the %s instance that received the signal".printf (get_docbook_link (sig.parent)), 0.1));
+ "the %s instance that received the signal".printf (get_docbook_link (sig.parent)),
+ 0.1));
if (current_dbus_interface != null && sig.is_dbus_visible) {
var dbuscomment = create_gcomment (sig.get_dbus_name (), sig.documentation, null, true);
current_dbus_member.comment = dbuscomment;
@@ -894,11 +994,17 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
Api.TypeParameter type_parameter = sig.return_type.data_type as Api.TypeParameter;
if (type_parameter != null) {
if (type_parameter.parent is Api.Class) {
- string return_type_desc = "A value from type #%s:%s-type.".printf (get_cname (type_parameter.parent), type_parameter.name.down ());
- gcomment.returns = combine_inline_docs (return_type_desc, gcomment.returns);
- } else if (type_parameter.parent is Api.Interface && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null) {
- string return_type_desc = "A value from type #_%sIface.get_%s_type().".printf (get_cname (type_parameter.parent), type_parameter.name.down ());
- gcomment.returns = combine_inline_docs (return_type_desc, gcomment.returns);
+ string return_type_desc = "A value from type #%s:%s-type."
+ .printf (get_cname (type_parameter.parent), type_parameter.name.down ());
+ gcomment.returns = combine_inline_docs (return_type_desc,
+ gcomment.returns);
+ } else if (type_parameter.parent is Api.Interface
+ && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null)
+ {
+ string return_type_desc = "A value from type #_%sIface.get_%s_type()."
+ .printf (get_cname (type_parameter.parent), type_parameter.name.down ());
+ gcomment.returns = combine_inline_docs (return_type_desc,
+ gcomment.returns);
}
}
@@ -912,7 +1018,11 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
public override void visit_method (Api.Method m) {
- if ((m.is_constructor && current_class != null && current_class.is_abstract) || m.is_override || m.is_private || (!m.is_abstract && !m.is_virtual && m.base_method != null)) {
+ if ((m.is_constructor && current_class != null && current_class.is_abstract)
+ || m.is_override
+ || m.is_private
+ || (!m.is_abstract && !m.is_virtual && m.base_method != null))
+ {
return;
}
@@ -940,7 +1050,10 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
if (!m.is_static && !m.is_constructor) {
- add_custom_header ("self", "the %s instance".printf (get_docbook_link (m.parent)), null, 0.1);
+ add_custom_header ("self",
+ "the %s instance".printf (get_docbook_link (m.parent)),
+ null,
+ 0.1);
}
if (m.is_constructor) {
@@ -949,9 +1062,12 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
foreach (Api.Node _type in type_parameters) {
var type = _type as Api.TypeParameter;
string type_name_down = type.name.down ();
- add_custom_header (type_name_down + "_type", "A #GType");
- add_custom_header (type_name_down + "_dup_func", "A dup function for @%s_type".printf (type_name_down));
- add_custom_header (type_name_down + "_destroy_func", "A destroy function for @%s_type".printf (type_name_down));
+ add_custom_header (type_name_down + "_type",
+ "A #GType");
+ add_custom_header (type_name_down + "_dup_func",
+ "A dup function for @%s_type".printf (type_name_down));
+ add_custom_header (type_name_down + "_destroy_func",
+ "A destroy function for @%s_type".printf (type_name_down));
}
}
@@ -960,9 +1076,18 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
foreach (Api.Node _type in type_parameters) {
var type = _type as Api.TypeParameter;
string type_name_down = type.name.down ();
- add_custom_header (type_name_down + "_type", "The #GType for @%s".printf (type_name_down), null, 0.2);
- add_custom_header (type_name_down + "_dup_func", "A dup function for @%s_type".printf (type_name_down), null, 0.3);
- add_custom_header (type_name_down + "_destroy_func", "A destroy function for @%s_type".printf (type_name_down), null, 0.4);
+ add_custom_header (type_name_down + "_type",
+ "The #GType for @%s".printf (type_name_down),
+ null,
+ 0.2);
+ add_custom_header (type_name_down + "_dup_func",
+ "A dup function for @%s_type".printf (type_name_down),
+ null,
+ 0.3);
+ add_custom_header (type_name_down + "_destroy_func",
+ "A destroy function for @%s_type".printf (type_name_down),
+ null,
+ 0.4);
}
m.accept_children ({NodeType.FORMAL_PARAMETER, NodeType.TYPE_PARAMETER}, this);
@@ -974,8 +1099,12 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
Header error_header = null;
GComment gcomment = null;
if (m.is_yields) {
- add_custom_header ("_callback_", "callback to call when the request is satisfied", {"scope async"});
- add_custom_header ("_user_data_", "the data to pass to @_callback_ function", {"closure"});
+ add_custom_header ("_callback_",
+ "callback to call when the request is satisfied",
+ {"scope async"});
+ add_custom_header ("_user_data_",
+ "the data to pass to @_callback_ function",
+ {"closure"});
// remove error from here, put that in the _finish function
error_header = remove_custom_header ("error");
@@ -985,7 +1114,11 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
see_also += get_docbook_link (m, false, true);
gcomment.see_also = see_also;
} else {
- gcomment = add_symbol (m.get_filename(), m.get_cname (), m.documentation, null, annotations);
+ gcomment = add_symbol (m.get_filename(),
+ m.get_cname (),
+ m.documentation,
+ null,
+ annotations);
}
// Handle attributes for things like deprecation.
@@ -995,10 +1128,15 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
if (current_dbus_interface != null && m.is_dbus_visible && !m.is_constructor) {
if (m.return_type != null && m.return_type.data_type != null) {
- var dresult = new DBus.Parameter (m.get_dbus_result_name (), m.return_type.get_dbus_type_signature (), DBus.Parameter.Direction.OUT);
+ var dresult = new DBus.Parameter (m.get_dbus_result_name (),
+ m.return_type.get_dbus_type_signature (),
+ DBus.Parameter.Direction.OUT);
current_dbus_member.add_parameter (dresult);
}
- var dbus_gcomment = create_gcomment (m.get_dbus_name (), m.documentation, null, true);
+ var dbus_gcomment = create_gcomment (m.get_dbus_name (),
+ m.documentation,
+ null,
+ true);
current_dbus_member.comment = dbus_gcomment;
current_dbus_interface.add_method (current_dbus_member);
}
@@ -1011,9 +1149,13 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
Api.TypeParameter type_parameter = m.return_type.data_type as Api.TypeParameter;
if (type_parameter != null) {
if (type_parameter.parent is Api.Class) {
- return_type_desc = "A value from type #%s:%s-type.".printf (get_cname (m.parent), type_parameter.name.down ());
- } else if (type_parameter.parent is Api.Interface && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null) {
- return_type_desc = "A value from type #_%sIface.get_%s_type().".printf (get_cname (m.parent), type_parameter.name.down ());
+ return_type_desc = "A value from type #%s:%s-type."
+ .printf (get_cname (m.parent), type_parameter.name.down ());
+ } else if (type_parameter.parent is Api.Interface
+ && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null)
+ {
+ return_type_desc = "A value from type #_%sIface.get_%s_type()."
+ .printf (get_cname (m.parent), type_parameter.name.down ());
} else if (type_parameter.parent is Api.Struct) {
// type not stored
} else if (type_parameter.parent == m) {
@@ -1022,13 +1164,17 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
if (m.is_yields) {
- var finish_gcomment = add_symbol (m.get_filename(), m.get_finish_function_cname (), m.documentation);
+ var finish_gcomment = add_symbol (m.get_filename(),
+ m.get_finish_function_cname (),
+ m.documentation);
finish_gcomment.headers.clear ();
if (!m.is_static) {
- finish_gcomment.headers.add (new Header ("self", "the %s instance".printf (get_docbook_link (m.parent))));
+ finish_gcomment.headers.add (new Header ("self",
+ "the %s instance".printf (get_docbook_link (m.parent))));
}
- finish_gcomment.headers.add (new Header ("_res_", "a <link linkend=\"GAsyncResult\"><type>GAsyncResult</type></link>"));
+ finish_gcomment.headers.add (new Header ("_res_",
+ "a <link linkend=\"GAsyncResult\"><type>GAsyncResult</type></link>"));
if (error_header != null) {
finish_gcomment.headers.add (error_header);
}
@@ -1048,7 +1194,8 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
if (m.is_constructor && !m.get_cname ().has_suffix ("_new")) {
- // Hide secondary _construct methods from the documentation (the primary _construct method is hidden in visit_class())
+ // Hide secondary _construct methods from the documentation
+ // (the primary _construct method is hidden in visit_class())
var file_data = get_file_data (m.get_filename ());
file_data.private_section_lines.add (m.get_cname ().replace ("_new", "_construct"));
}
@@ -1063,10 +1210,12 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
if (!m.is_private && !m.is_protected && !m.is_internal) {
- add_custom_header (m.name, "virtual method called by %s".printf (get_docbook_link (m)));
+ add_custom_header (m.name, "virtual method called by %s"
+ .printf (get_docbook_link (m)));
if (m.is_yields) {
- add_custom_header (m.name + "_finish", "asynchronous finish function for <structfield>%s</structfield>, called by %s".printf (m.name, get_docbook_link (m)));
+ add_custom_header (m.name + "_finish", "asynchronous finish function for <structfield>%s</structfield>, called by %s"
+ .printf (m.name, get_docbook_link (m)));
}
} else {
add_custom_header (m.name, "virtual method used internally");
@@ -1086,11 +1235,13 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
}
if (prop.getter != null && !prop.getter.is_private && !prop.getter.is_internal && prop.getter.is_get) {
- add_custom_header ("get_" + prop.name, "getter method for the abstract property %s".printf (get_docbook_link (prop)));
+ add_custom_header ("get_" + prop.name, "getter method for the abstract property %s"
+ .printf (get_docbook_link (prop)));
}
if (prop.setter != null && !prop.setter.is_private && !prop.setter.is_internal && prop.setter.is_set && !prop.setter.is_construct) {
- add_custom_header ("set_" + prop.name, "setter method for the abstract property %s".printf (get_docbook_link (prop)));
+ add_custom_header ("set_" + prop.name, "setter method for the abstract property %s"
+ .printf (get_docbook_link (prop)));
}
}
@@ -1112,13 +1263,17 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
TypeParameter type_parameter = param.parameter_type.data_type as TypeParameter;
if (type_parameter != null) {
if (type_parameter.parent is Api.Class) {
- add_custom_header (param_name, "A parameter from type #%s:%s-type.".printf (get_cname (type_parameter.parent), type_parameter.name.down ()), null, double.MAX, false);
- } else if (type_parameter.parent is Api.Interface && ((Api.Symbol) type_parameter.parent).get_attribute ("GenericAccessors") != null) {
- add_custom_header (param_name, "A parameter from type #_%sIface.get_%s_type().".printf (get_cname (type_parameter.parent), type_parameter.name.down ()), null, double.MAX, false);
+ add_custom_header (param_name, "A parameter from type #%s:%s-type."
+ .printf (get_cname (type_parameter.parent), type_parameter.name.down ()), null, double.MAX, false);
+ } else if (type_parameter.parent is Api.Interface && ((Api.Symbol) type_parameter.parent)
+ .get_attribute ("GenericAccessors") != null) {
+ add_custom_header (param_name, "A parameter from type #_%sIface.get_%s_type()."
+ .printf (get_cname (type_parameter.parent), type_parameter.name.down ()), null, double.MAX, false);
} else if (type_parameter.parent is Api.Struct) {
// type not stored
} else if (type_parameter.parent is Method) {
- add_custom_header (param_name, "A parameter from type @%s_type.".printf (type_parameter.name.down ()), null, double.MAX, false);
+ add_custom_header (param_name, "A parameter from type @%s_type."
+ .printf (type_parameter.name.down ()), null, double.MAX, false);
}
}
@@ -1126,17 +1281,23 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
annotations += "allow-none";
}
- if (param.parameter_type.is_owned && !(param.parameter_type.data_type is Api.Delegate)) {
+ if (param.parameter_type.is_owned
+ && !(param.parameter_type.data_type is Api.Delegate))
+ {
annotations += "transfer full";
}
if (param.parameter_type.data_type is Api.Array) {
annotations += "array length=%s_length1".printf (param_name);
- add_custom_header ("%s_length1".printf (param_name), "length of the @%s array".printf (param_name),
- null, get_parameter_pos (current_method_or_delegate, param_name)+0.1);
+ add_custom_header ("%s_length1".printf (param_name),
+ "length of the @%s array".printf (param_name),
+ null,
+ get_parameter_pos (current_method_or_delegate, param_name)+0.1);
}
- if (!param.ellipsis && param.parameter_type.data_type != null && get_cname (param.parameter_type.data_type) == "GError") {
+ if (!param.ellipsis && param.parameter_type.data_type != null
+ && get_cname (param.parameter_type.data_type) == "GError")
+ {
annotations += "not-error";
}
@@ -1165,7 +1326,9 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
} else if (param.is_out) {
ddirection = DBus.Parameter.Direction.OUT;
}
- var dparam = new DBus.Parameter (param_name, param.parameter_type.get_dbus_type_signature (), ddirection);
+ var dparam = new DBus.Parameter (param_name,
+ param.parameter_type.get_dbus_type_signature (),
+ ddirection);
current_dbus_member.add_parameter (dparam);
}
param.accept_all_children (this);
@@ -1210,11 +1373,14 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
replacement_symbol_name = replacement_symbol_name[0:-2];
}
- replacement_symbol = current_tree.search_symbol_str (sym, replacement_symbol_name);
+ replacement_symbol = current_tree.search_symbol_str (sym,
+ replacement_symbol_name);
}
if (replacement != null && replacement_symbol == null) {
- reporter.simple_warning ("Couldn’t resolve replacement symbol ‘%s’ for ‘Deprecated’ attribute on %s.", replacement_symbol_name, sym.get_full_name ());
+ reporter.simple_warning ("Couldn’t resolve replacement symbol ‘%s’ for ‘Deprecated’ attribute on %s.",
+ replacement_symbol_name,
+ sym.get_full_name ());
}
var deprecation_string = "No replacement specified.";
@@ -1226,7 +1392,8 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
} else if (since == null && replacement_symbol != null) {
deprecation_string = "Replaced by %s.".printf (get_gtkdoc_link (replacement_symbol));
} else {
- reporter.simple_warning ("Missing ‘since’ and ‘replacement’ arguments to ‘Deprecated’ attribute on %s.", sym.get_full_name ());
+ reporter.simple_warning ("Missing ‘since’ and ‘replacement’ arguments to ‘Deprecated’ attribute on %s.",
+ sym.get_full_name ());
}
gcomment.versioning.add (new Header ("Deprecated", deprecation_string));
diff --git a/src/doclets/gtkdoc/utils.vala b/src/doclets/gtkdoc/utils.vala
index 93037d6658..53bf8fb164 100644
--- a/src/doclets/gtkdoc/utils.vala
+++ b/src/doclets/gtkdoc/utils.vala
@@ -76,11 +76,14 @@ namespace Gtkdoc {
}
public string get_docbook_type_link (Api.Class cls) {
- return """<link linkend="%s:CAPS"><literal>%s</literal></link>""".printf (to_docbook_id (cls.get_type_id ()), cls.get_type_id ());
+ return """<link linkend="%s:CAPS"><literal>%s</literal></link>"""
+ .printf (to_docbook_id (cls.get_type_id ()), cls.get_type_id ());
}
public string? get_gtkdoc_link (Api.Node symbol) {
- if (symbol is Class || symbol is Interface || symbol is Struct || symbol is Enum || symbol is ErrorDomain) {
+ if (symbol is Class || symbol is Interface || symbol is Struct || symbol is Enum
+ || symbol is ErrorDomain)
+ {
return "#%s".printf (get_cname (symbol));
}
@@ -127,15 +130,18 @@ namespace Gtkdoc {
}
parent = "";
}
- return """<link linkend="%s%s"><function>%s()</function></link>""".printf (to_docbook_id (parent), to_docbook_id (name), name);
+ return """<link linkend="%s%s"><function>%s()</function></link>"""
+ .printf (to_docbook_id (parent), to_docbook_id (name), name);
} else if (item is Api.FormalParameter) {
return "<parameter>%s</parameter>".printf (((Api.FormalParameter)item).name);
} else if (item is Api.Constant) {
var cname = ((Api.Constant)item).get_cname ();
- return """<link linkend="%s:CAPS"><literal>%s</literal></link>""".printf (to_docbook_id (cname), cname);
+ return """<link linkend="%s:CAPS"><literal>%s</literal></link>"""
+ .printf (to_docbook_id (cname), cname);
} else if (item is Api.ErrorCode) {
var cname = ((Api.ErrorCode)item).get_cname ();
- return """<link linkend="%s:CAPS"><literal>%s</literal></link>""".printf (to_docbook_id (cname), cname);
+ return """<link linkend="%s:CAPS"><literal>%s</literal></link>"""
+ .printf (to_docbook_id (cname), cname);
} else if (item is Api.Property) {
string name;
string parent;
@@ -146,7 +152,8 @@ namespace Gtkdoc {
name = ((Api.Property)item).get_cname ();
parent = get_cname (item.parent);
}
- return """<link linkend="%s--%s"><type>"%s"</type></link>""".printf (to_docbook_id (parent), to_docbook_id (name), name);
+ return """<link linkend="%s--%s"><type>"%s"</type></link>"""
+ .printf (to_docbook_id (parent), to_docbook_id (name), name);
} else if (item is Api.Signal) {
string name;
string parent;
@@ -158,11 +165,13 @@ namespace Gtkdoc {
name = name.replace ("_", "-");
parent = get_cname (item.parent);
}
- return """<link linkend="%s-%s"><type>"%s"</type></link>""".printf (to_docbook_id (parent), to_docbook_id (name), name);
+ return """<link linkend="%s-%s"><type>"%s"</type></link>"""
+ .printf (to_docbook_id (parent), to_docbook_id (name), name);
} else {
var cname = get_cname (item);
if (cname != null) {
- return """<link linkend="%s"><type>%s</type></link>""".printf (to_docbook_id (cname), cname);
+ return """<link linkend="%s"><type>%s</type></link>"""
+ .printf (to_docbook_id (cname), cname);
}
}
return null;
@@ -210,7 +219,9 @@ namespace Gtkdoc {
Process.spawn_command_line_sync (pc, null, null, out exit_status);
return (0 == exit_status);
} catch (SpawnError e) {
- reporter.simple_warning ("GtkDoc: warning: Error pkg-config --exists %s: %s", package_name, e.message);
+ reporter.simple_warning ("GtkDoc: warning: Error pkg-config --exists %s: %s",
+ package_name,
+ e.message);
return false;
}
}
diff --git a/src/driver/0.14.x/driver.vala b/src/driver/0.14.x/driver.vala
index 253bc7bea5..f58656967d 100644
--- a/src/driver/0.14.x/driver.vala
+++ b/src/driver/0.14.x/driver.vala
@@ -40,7 +40,11 @@ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver {
gir_directory = settings.gir_directory;
}
- gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name);
+ 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) {
diff --git a/src/driver/0.14.x/treebuilder.vala b/src/driver/0.14.x/treebuilder.vala
index 6cbec291e0..e3636b0d92 100644
--- a/src/driver/0.14.x/treebuilder.vala
+++ b/src/driver/0.14.x/treebuilder.vala
@@ -85,7 +85,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
&& ((Vala.SourceFile) file.data).file_type == Vala.SourceFileType.SOURCE)
) {
Vala.SourceReference pos = c.source_reference;
- comment = new SourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ comment = new SourceComment (c.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
break;
}
}
@@ -154,20 +159,34 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 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);
+ 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_ref.data_type = new TypeParameter (caller,
+ // caller.get_source_file (),
+ // ((Vala.GenericType) vtyperef).type_parameter.name,
+ // vtyperef);
}
// type parameters:
@@ -452,7 +471,11 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
var cl = element as Vala.Class;
if (cl != null && cl.type_check_function != null) {
return cl.type_check_function;
- } else if ((cl != null && cl.is_compact) || element is Vala.Struct || element is Vala.Enum || element is Vala.Delegate) {
+ } else if ((cl != null && cl.is_compact)
+ || element is Vala.Struct
+ || element is Vala.Enum
+ || element is Vala.Delegate)
+ {
return null;
} else {
return element.get_upper_case_cname ("IS_");
@@ -469,7 +492,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_function_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -481,7 +507,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_macro_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -525,7 +554,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
if (comment != null) {
Vala.SourceReference pos = comment.source_reference;
SourceFile file = files.get (pos.file);
- return new SourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ return new SourceComment (comment.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
}
return null;
@@ -561,7 +595,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 (), source_file);
+ SourceFile file = new SourceFile (meta_data.package,
+ source_file.get_relative_filename (),
+ source_file.get_csource_filename (),
+ source_file);
files.set (source_file, file);
meta_data.register_source_file (source_file);
@@ -679,7 +716,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are weak, not unowned
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true) {
+ if (element.data_type is Vala.TypeSymbol
+ && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true)
+ {
return false;
}
@@ -711,7 +750,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are unowned, not weak
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false) {
+ if (element.data_type is Vala.TypeSymbol
+ && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false)
+ {
return false;
}
@@ -883,7 +924,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
register_source_file (source_package, vfile);
- add_deps (context, Path.build_filename (Path.get_dirname (source), "%s.deps".printf (file_name)), file_name);
+ 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);
@@ -1056,8 +1099,34 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_private_cname (element), get_class_macro_name (element), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_class_type_macro_name (element), get_is_class_type_macro_name (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_free_function_name (element), get_finalize_function_name (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);
-
+ Class node = new Class (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_private_cname (element),
+ get_class_macro_name (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_class_type_macro_name (element),
+ get_is_class_type_macro_name (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_free_function_name (element),
+ get_finalize_function_name (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);
@@ -1089,7 +1158,19 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_interface_macro_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Interface node = new Interface (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_interface_macro_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1115,9 +1196,25 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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_type_macro_name (element), get_type_function_name (element), get_ccode_type_id (element), get_dup_function (element), get_copy_function (element), get_struct_destroy_function (element), get_free_function (element), is_basic_type, element);
+ 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_type_macro_name (element),
+ get_type_function_name (element),
+ get_ccode_type_id (element),
+ get_dup_function (element),
+ get_copy_function (element),
+ get_struct_destroy_function (element),
+ get_free_function (element),
+ is_basic_type,
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1139,7 +1236,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1156,7 +1261,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1164,12 +1278,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// Process property type
if (element.get_accessor != null) {
var accessor = element.get_accessor;
- node.getter = new PropertyAccessor (node, file, element.name, get_access_modifier(accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.getter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ 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(accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.setter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ get_cname (accessor),
+ get_property_accessor_type (accessor),
+ get_property_ownership (accessor),
+ accessor);
}
process_attributes (node, element.attributes);
@@ -1184,7 +1312,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1201,7 +1342,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1218,7 +1372,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1235,7 +1398,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1252,7 +1421,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_type_function_name (element), element);
+ Symbol node = new Enum (parent,
+ file,
+ element.name,
+ get_access_modifier(element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_type_function_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1268,7 +1445,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 node = new Api.EnumValue (parent,
+ file,
+ element.name,
+ comment,
+ get_cname (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1284,7 +1466,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1301,7 +1488,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_quark_macro_name (element), get_quark_function_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Symbol node = new ErrorDomain (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_quark_macro_name (element),
+ get_quark_function_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1321,7 +1517,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 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);
@@ -1350,7 +1552,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
diff --git a/src/driver/0.16.x/driver.vala b/src/driver/0.16.x/driver.vala
index 1a164976c0..799ac77d78 100644
--- a/src/driver/0.16.x/driver.vala
+++ b/src/driver/0.16.x/driver.vala
@@ -45,7 +45,11 @@ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver {
gir_directory = settings.gir_directory;
}
- gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name);
+ 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) {
diff --git a/src/driver/0.16.x/treebuilder.vala b/src/driver/0.16.x/treebuilder.vala
index 96cece0ffa..06304e0de4 100644
--- a/src/driver/0.16.x/treebuilder.vala
+++ b/src/driver/0.16.x/treebuilder.vala
@@ -87,12 +87,27 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
Vala.SourceReference pos = c.source_reference;
#if ! VALA_0_15_0
if (c is Vala.GirComment) {
- comment = new GirSourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ 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);
+ comment = new SourceComment (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);
+ comment = new SourceComment (c.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
#endif
break;
}
@@ -162,20 +177,34 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 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);
+ 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_ref.data_type = new TypeParameter (caller,
+ // caller.get_source_file (),
+ // ((Vala.GenericType) vtyperef).type_parameter.name,
+ // vtyperef);
}
// type parameters:
@@ -362,7 +391,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_function_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -370,7 +402,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_macro_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -398,29 +433,54 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
if (comment != null) {
Vala.SourceReference pos = comment.source_reference;
SourceFile file = files.get (pos.file);
- return new SourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ return new SourceComment (comment.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
}
#else
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);
+ 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);
+ 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);
+ 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 new SourceComment (comment.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
}
}
#endif
@@ -457,7 +517,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 (), source_file);
+ SourceFile file = new SourceFile (meta_data.package,
+ source_file.get_relative_filename (),
+ source_file.get_csource_filename (),
+ source_file);
files.set (source_file, file);
meta_data.register_source_file (source_file);
@@ -574,7 +637,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are weak, not unowned
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true) {
+ if (element.data_type is Vala.TypeSymbol
+ && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true)
+ {
return false;
}
@@ -606,7 +671,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are unowned, not weak
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false) {
+ if (element.data_type is Vala.TypeSymbol
+ && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false)
+ {
return false;
}
@@ -782,7 +849,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
register_source_file (source_package, vfile);
- add_deps (context, Path.build_filename (Path.get_dirname (source), "%s.deps".printf (file_name)), file_name);
+ 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);
@@ -956,7 +1025,34 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_private_cname (element), get_class_macro_name (element), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_class_type_macro_name (element), get_is_class_type_macro_name (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_free_function_name (element), get_finalize_function_name (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);
+ Class node = new Class (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_private_cname (element),
+ get_class_macro_name (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_class_type_macro_name (element),
+ get_is_class_type_macro_name (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_free_function_name (element),
+ get_finalize_function_name (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);
@@ -989,7 +1085,19 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_interface_macro_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Interface node = new Interface (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_interface_macro_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1015,9 +1123,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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_type_macro_name (element), get_type_function_name (element), get_ccode_type_id (element), get_dup_function (element), get_copy_function (element), get_destroy_function (element), get_free_function (element), is_basic_type, element);
+ 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_type_macro_name (element),
+ get_type_function_name (element),
+ get_ccode_type_id (element),
+ get_dup_function (element),
+ get_copy_function (element),
+ get_destroy_function (element),
+ get_free_function (element),
+ is_basic_type,
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1039,7 +1164,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1056,7 +1189,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1064,12 +1206,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// Process property type
if (element.get_accessor != null) {
var accessor = element.get_accessor;
- node.getter = new PropertyAccessor (node, file, element.name, get_access_modifier(accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.getter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ 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(accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.setter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ get_cname (accessor),
+ get_property_accessor_type (accessor),
+ get_property_ownership (accessor),
+ accessor);
}
process_attributes (node, element.attributes);
@@ -1084,7 +1240,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1101,7 +1270,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1118,7 +1300,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1135,7 +1326,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1152,7 +1350,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_type_function_name (element), element);
+ Symbol node = new Enum (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_type_function_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1168,7 +1374,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 node = new Api.EnumValue (parent,
+ file,
+ element.name,
+ comment,
+ get_cname (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1184,7 +1395,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1201,7 +1418,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_quark_macro_name (element), get_quark_function_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Symbol node = new ErrorDomain (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_quark_macro_name (element),
+ get_quark_function_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1221,7 +1447,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 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);
@@ -1250,7 +1482,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1280,7 +1518,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// 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) {
+ 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);
}
diff --git a/src/driver/0.18.x/driver.vala b/src/driver/0.18.x/driver.vala
index 35d43d1381..6bed3b9425 100644
--- a/src/driver/0.18.x/driver.vala
+++ b/src/driver/0.18.x/driver.vala
@@ -41,7 +41,11 @@ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver {
gir_directory = settings.gir_directory;
}
- gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name);
+ 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) {
diff --git a/src/driver/0.18.x/treebuilder.vala b/src/driver/0.18.x/treebuilder.vala
index c597f274d2..993374b2a8 100644
--- a/src/driver/0.18.x/treebuilder.vala
+++ b/src/driver/0.18.x/treebuilder.vala
@@ -87,15 +87,35 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
Vala.SourceReference pos = c.source_reference;
if (c is Vala.GirComment) {
#if VALA_0_17_0
- comment = new GirSourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ comment = new GirSourceComment (c.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
#else
- comment = new GirSourceComment (c.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ comment = new GirSourceComment (c.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
#endif
} else {
#if VALA_0_17_0
- comment = new SourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ comment = new SourceComment (c.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
#else
- comment = new SourceComment (c.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ comment = new SourceComment (c.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
#endif
}
break;
@@ -166,20 +186,33 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 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);
+ 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_ref.data_type = new TypeParameter (caller,
+ // caller.get_source_file (),
+ // ((Vala.GenericType) vtyperef).type_parameter.name,
+ // vtyperef);
}
// type parameters:
@@ -333,16 +366,36 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
SourceFile file = files.get (pos.file);
if (comment is Vala.GirComment) {
#if VALA_0_17_0
- var tmp = new GirSourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ var tmp = new GirSourceComment (comment.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
#else
- var tmp = new GirSourceComment (comment.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ var tmp = new GirSourceComment (comment.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
#endif
if (((Vala.GirComment) comment).return_content != null) {
Vala.SourceReference return_pos = ((Vala.GirComment) comment).return_content.source_reference;
#if VALA_0_17_0
- 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);
+ 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);
#else
- tmp.return_comment = new SourceComment (((Vala.GirComment) comment).return_content.content, file, return_pos.begin.line, return_pos.begin.column, return_pos.end.line, return_pos.end.column);
+ tmp.return_comment = new SourceComment (((Vala.GirComment) comment).return_content.content,
+ file,
+ return_pos.begin.line,
+ return_pos.begin.column,
+ return_pos.end.line,
+ return_pos.end.column);
#endif
}
@@ -351,18 +404,38 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
Vala.Comment vala_param = it.get_value ();
Vala.SourceReference param_pos = vala_param.source_reference;
#if VALA_0_17_0
- 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);
+ 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);
#else
- var param_comment = new SourceComment (vala_param.content, file, param_pos.begin.line, param_pos.begin.column, param_pos.end.line, param_pos.end.column);
+ var param_comment = new SourceComment (vala_param.content,
+ file,
+ param_pos.begin.line,
+ param_pos.begin.column,
+ param_pos.end.line,
+ param_pos.end.column);
#endif
tmp.add_parameter_content (it.get_key (), param_comment);
}
return tmp;
} else {
#if VALA_0_17_0
- return new SourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column);
+ return new SourceComment (comment.content,
+ file,
+ pos.first_line,
+ pos.first_column,
+ pos.last_line,
+ pos.last_column);
#else
- return new SourceComment (comment.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ return new SourceComment (comment.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
#endif
}
}
@@ -422,7 +495,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_function_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -430,7 +506,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_macro_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -471,7 +550,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 (), source_file);
+ SourceFile file = new SourceFile (meta_data.package,
+ source_file.get_relative_filename (),
+ source_file.get_csource_filename (),
+ source_file);
files.set (source_file, file);
meta_data.register_source_file (source_file);
@@ -588,7 +670,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are weak, not unowned
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true) {
+ if (element.data_type is Vala.TypeSymbol &&
+ is_reference_counting ((Vala.TypeSymbol) element.data_type) == true)
+ {
return false;
}
@@ -620,7 +704,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are unowned, not weak
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false) {
+ if (element.data_type is Vala.TypeSymbol
+ && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false)
+ {
return false;
}
@@ -839,7 +925,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// add default packages:
- if (settings.profile == "gobject-2.0" || settings.profile == "gobject" || settings.profile == null) {
+ if (settings.profile == "gobject-2.0"
+ || settings.profile == "gobject"
+ || settings.profile == null)
+ {
context.profile = Vala.Profile.GOBJECT;
context.add_define ("GOBJECT");
}
@@ -861,7 +950,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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) {
+ 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");
}
@@ -973,7 +1064,34 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_private_cname (element), get_class_macro_name (element), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_class_type_macro_name (element), get_is_class_type_macro_name (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_free_function_name (element), get_finalize_function_name (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);
+ Class node = new Class (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_private_cname (element),
+ get_class_macro_name (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_class_type_macro_name (element),
+ get_is_class_type_macro_name (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_free_function_name (element),
+ get_finalize_function_name (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);
@@ -1005,7 +1123,19 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_interface_macro_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Interface node = new Interface (parent,
+ file,
+ element.name,
+ get_access_modifier(element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_interface_macro_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1031,9 +1161,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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_type_macro_name (element), get_type_function_name (element), get_ccode_type_id (element), get_dup_function (element), get_copy_function (element), get_destroy_function (element), get_free_function (element), is_basic_type, element);
+ 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_type_macro_name (element),
+ get_type_function_name (element),
+ get_ccode_type_id (element),
+ get_dup_function (element),
+ get_copy_function (element),
+ get_destroy_function (element),
+ get_free_function (element),
+ is_basic_type,
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1055,7 +1202,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1072,7 +1227,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1080,12 +1244,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// Process property type
if (element.get_accessor != null) {
var accessor = element.get_accessor;
- node.getter = new PropertyAccessor (node, file, element.name, get_access_modifier (accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.getter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ 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 (accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.setter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ get_cname (accessor),
+ get_property_accessor_type (accessor),
+ get_property_ownership (accessor),
+ accessor);
}
process_attributes (node, element.attributes);
@@ -1100,7 +1278,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1117,7 +1308,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1134,7 +1338,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1151,7 +1364,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1168,7 +1388,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_type_function_name (element), element);
+ Symbol node = new Enum (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_type_function_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1184,7 +1412,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 node = new Api.EnumValue (parent,
+ file,
+ element.name,
+ comment,
+ get_cname (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1200,7 +1433,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1217,7 +1456,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_quark_macro_name (element), get_quark_function_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Symbol node = new ErrorDomain (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_quark_macro_name (element),
+ get_quark_function_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1237,7 +1485,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 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);
@@ -1266,7 +1520,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1296,7 +1556,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// 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) {
+ 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);
}
diff --git a/src/driver/0.20.x/driver.vala b/src/driver/0.20.x/driver.vala
index 35d43d1381..6bed3b9425 100644
--- a/src/driver/0.20.x/driver.vala
+++ b/src/driver/0.20.x/driver.vala
@@ -41,7 +41,11 @@ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver {
gir_directory = settings.gir_directory;
}
- gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name);
+ 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) {
diff --git a/src/driver/0.20.x/treebuilder.vala b/src/driver/0.20.x/treebuilder.vala
index 4deb224108..ad30d00787 100644
--- a/src/driver/0.20.x/treebuilder.vala
+++ b/src/driver/0.20.x/treebuilder.vala
@@ -86,9 +86,19 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
) {
Vala.SourceReference pos = c.source_reference;
if (c is Vala.GirComment) {
- comment = new GirSourceComment (c.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ comment = new GirSourceComment (c.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
} else {
- comment = new SourceComment (c.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ comment = new SourceComment (c.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
}
break;
}
@@ -158,20 +168,33 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 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);
+ 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_ref.data_type = new TypeParameter (caller,
+ // caller.get_source_file (),
+ // ((Vala.GenericType) vtyperef).type_parameter.name,
+ // vtyperef);
}
// type parameters:
@@ -324,22 +347,42 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ var tmp = new GirSourceComment (comment.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.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.begin.line, return_pos.begin.column, return_pos.end.line, return_pos.end.column);
+ tmp.return_comment = new SourceComment (((Vala.GirComment) comment).return_content.content,
+ file,
+ return_pos.begin.line,
+ return_pos.begin.column,
+ return_pos.end.line,
+ return_pos.end.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.begin.line, param_pos.begin.column, param_pos.end.line, param_pos.end.column);
+ var param_comment = new SourceComment (vala_param.content,
+ file,
+ param_pos.begin.line,
+ param_pos.begin.column,
+ param_pos.end.line,
+ param_pos.end.column);
tmp.add_parameter_content (it.get_key (), param_comment);
}
return tmp;
} else {
- return new SourceComment (comment.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ return new SourceComment (comment.content,
+ file,
+ pos.begin.line,
+ pos.begin.column,
+ pos.end.line,
+ pos.end.column);
}
}
@@ -398,7 +441,11 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_function_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class
+ && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -406,7 +453,11 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_macro_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ if ((element is Vala.Class
+ && ((Vala.Class) element).is_compact)
+ || element is Vala.ErrorDomain
+ || element is Vala.Delegate)
+ {
return null;
}
@@ -414,7 +465,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
private string? get_type_cast_macro_name (Vala.TypeSymbol element) {
- if ((element is Vala.Class && !((Vala.Class) element).is_compact) || element is Vala.Interface) {
+ if ((element is Vala.Class
+ && !((Vala.Class) element).is_compact)
+ || element is Vala.Interface)
+ {
return Vala.CCodeBaseModule.get_ccode_upper_case_name (element, null);
} else {
return null;
@@ -447,7 +501,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
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 (), source_file);
+ SourceFile file = new SourceFile (meta_data.package,
+ source_file.get_relative_filename (),
+ source_file.get_csource_filename (),
+ source_file);
files.set (source_file, file);
meta_data.register_source_file (source_file);
@@ -564,12 +621,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are weak, not unowned
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true) {
+ 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;
+ return (element.parent_node is Vala.Parameter == false)
+ ? element.is_weak ()
+ : false;
}
private bool is_type_reference_owned (Vala.DataType? element) {
@@ -596,7 +657,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
}
// non ref counted types are unowned, not weak
- if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false) {
+ if (element.data_type is Vala.TypeSymbol
+ && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false)
+ {
return false;
}
@@ -935,7 +998,34 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_private_cname (element), get_class_macro_name (element), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_class_type_macro_name (element), get_is_class_type_macro_name (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_free_function_name (element), get_finalize_function_name (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);
+ Class node = new Class (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_private_cname (element),
+ get_class_macro_name (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_class_type_macro_name (element),
+ get_is_class_type_macro_name (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_free_function_name (element),
+ get_finalize_function_name (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);
@@ -967,7 +1057,19 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_interface_macro_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Interface node = new Interface (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_is_type_macro_name (element),
+ get_type_cast_macro_name (element),
+ get_type_function_name (element),
+ get_interface_macro_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -993,9 +1095,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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_type_macro_name (element), get_type_function_name (element), get_ccode_type_id (element), get_dup_function (element), get_copy_function (element), get_destroy_function (element), get_free_function (element), is_basic_type, element);
+ 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_type_macro_name (element),
+ get_type_function_name (element),
+ get_ccode_type_id (element),
+ get_dup_function (element),
+ get_copy_function (element),
+ get_destroy_function (element),
+ get_free_function (element),
+ is_basic_type,
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1017,7 +1136,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1034,7 +1161,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1042,12 +1178,26 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// Process property type
if (element.get_accessor != null) {
var accessor = element.get_accessor;
- node.getter = new PropertyAccessor (node, file, element.name, get_access_modifier (accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.getter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ 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 (accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ node.setter = new PropertyAccessor (node,
+ file,
+ element.name,
+ get_access_modifier (accessor),
+ get_cname (accessor),
+ get_property_accessor_type (accessor),
+ get_property_ownership (accessor),
+ accessor);
}
process_attributes (node, element.attributes);
@@ -1062,7 +1212,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1079,7 +1242,20 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1096,7 +1272,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1113,7 +1298,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1130,7 +1322,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_type_macro_name (element), get_type_function_name (element), element);
+ Symbol node = new Enum (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_type_macro_name (element),
+ get_type_function_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1146,7 +1346,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 node = new Api.EnumValue (parent,
+ file,
+ element.name,
+ comment,
+ get_cname (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1162,7 +1367,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1179,7 +1390,16 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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), get_quark_macro_name (element), get_quark_function_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ Symbol node = new ErrorDomain (parent,
+ file,
+ element.name,
+ get_access_modifier (element),
+ comment,
+ get_cname (element),
+ get_quark_macro_name (element),
+ get_quark_function_name (element),
+ Vala.GDBusModule.get_dbus_name (element),
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1199,7 +1419,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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 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);
@@ -1214,7 +1440,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
Api.Node parent = get_parent_node_for (element);
SourceFile? file = get_source_file (element);
- Symbol node = new TypeParameter (parent, file, element.name, element);
+ Symbol node = new TypeParameter (parent,
+ file,
+ element.name,
+ element);
symbol_map.set (element, node);
parent.add_child (node);
@@ -1228,7 +1457,13 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
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);
+ 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);
@@ -1258,7 +1493,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
// 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) {
+ 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);
}
diff --git a/src/libvaladoc/api/class.vala b/src/libvaladoc/api/class.vala
index 8176b6d0f9..8d792a75a6 100644
--- a/src/libvaladoc/api/class.vala
+++ b/src/libvaladoc/api/class.vala
@@ -46,8 +46,17 @@ public class Valadoc.Api.Class : TypeSymbol {
private string? private_cname;
private string? cname;
- public Class (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? private_cname, string? class_macro_name, string? type_macro_name, string? is_type_macro_name, string? type_cast_macro_name, string? type_function_name, string? class_type_macro_name, string? is_class_type_macro_name, string? dbus_name, string? type_id, string? param_spec_function_name, string? ref_function_name, string? unref_function_name, string? free_function_name, string? finalize_function_name, string? take_value_function_cname, string? get_value_function_cname, string? set_value_function_cname, bool is_fundamental, bool is_abstract, bool is_basic_type, void* data) {
- base (parent, file, name, accessibility, comment, type_macro_name, is_type_macro_name, type_cast_macro_name, type_function_name, is_basic_type, data);
+ public Class (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? private_cname, string? class_macro_name,
+ string? type_macro_name, string? is_type_macro_name, string? type_cast_macro_name,
+ string? type_function_name, string? class_type_macro_name, string? is_class_type_macro_name,
+ string? dbus_name, string? type_id, string? param_spec_function_name, string? ref_function_name,
+ string? unref_function_name, string? free_function_name, string? finalize_function_name,
+ string? take_value_function_cname, string? get_value_function_cname, string? set_value_function_cname,
+ bool is_fundamental, bool is_abstract, bool is_basic_type, void* data)
+ {
+ base (parent, file, name, accessibility, comment, type_macro_name,
+ is_type_macro_name, type_cast_macro_name, type_function_name, is_basic_type, data);
this.interfaces = new ArrayList<TypeReference> ();
diff --git a/src/libvaladoc/api/constant.vala b/src/libvaladoc/api/constant.vala
index 9c15fc43ca..351584be4e 100644
--- a/src/libvaladoc/api/constant.vala
+++ b/src/libvaladoc/api/constant.vala
@@ -37,7 +37,9 @@ public class Valadoc.Api.Constant : Member {
get;
}
- public Constant (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, void* data) {
+ public Constant (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, void* data)
+ {
base (parent, file, name, accessibility, comment, data);
this.cname = cname;
diff --git a/src/libvaladoc/api/delegate.vala b/src/libvaladoc/api/delegate.vala
index a5f6c67520..cd7e7c5522 100644
--- a/src/libvaladoc/api/delegate.vala
+++ b/src/libvaladoc/api/delegate.vala
@@ -39,7 +39,9 @@ public class Valadoc.Api.Delegate : TypeSymbol, Callable {
}
- public Delegate (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, bool is_static, void* data) {
+ public Delegate (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, bool is_static, void* data)
+ {
base (parent, file, name, accessibility, comment, null, null, null, null, false, data);
this.is_static = is_static;
diff --git a/src/libvaladoc/api/enum.vala b/src/libvaladoc/api/enum.vala
index 12652f8bd5..230c0bb642 100644
--- a/src/libvaladoc/api/enum.vala
+++ b/src/libvaladoc/api/enum.vala
@@ -30,8 +30,12 @@ using Valadoc.Content;
public class Valadoc.Api.Enum : TypeSymbol {
private string cname;
- public Enum (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? type_macro_name, string? type_function_name, void* data) {
- base (parent, file, name, accessibility, comment, type_macro_name, null, null, type_function_name, false, data);
+ public Enum (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? type_macro_name,
+ string? type_function_name, void* data)
+ {
+ base (parent, file, name, accessibility, comment, type_macro_name, null, null,
+ type_function_name, false, data);
this.cname = cname;
}
diff --git a/src/libvaladoc/api/errorcode.vala b/src/libvaladoc/api/errorcode.vala
index c42202360c..71d365fd5d 100644
--- a/src/libvaladoc/api/errorcode.vala
+++ b/src/libvaladoc/api/errorcode.vala
@@ -32,7 +32,9 @@ public class Valadoc.Api.ErrorCode : Symbol {
private string? dbus_name;
private string? cname;
- public ErrorCode (ErrorDomain parent, SourceFile file, string name, SourceComment? comment, string? cname, string? dbus_name, void* data) {
+ public ErrorCode (ErrorDomain parent, SourceFile file, string name, SourceComment? comment,
+ string? cname, string? dbus_name, void* data)
+ {
base (parent, file, name, parent.accessibility, data);
this.source_comment = comment;
diff --git a/src/libvaladoc/api/errordomain.vala b/src/libvaladoc/api/errordomain.vala
index 4851010c3d..969f294a31 100644
--- a/src/libvaladoc/api/errordomain.vala
+++ b/src/libvaladoc/api/errordomain.vala
@@ -33,7 +33,10 @@ public class Valadoc.Api.ErrorDomain : TypeSymbol {
private string? dbus_name;
private string? cname;
- public ErrorDomain (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? quark_macro_name, string? quark_function_name, string? dbus_name, void* data) {
+ public ErrorDomain (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? quark_macro_name,
+ string? quark_function_name, string? dbus_name, void* data)
+ {
base (parent, file, name, accessibility, comment, null, null, null, null, false, data);
this.quark_function_name = quark_function_name;
diff --git a/src/libvaladoc/api/field.vala b/src/libvaladoc/api/field.vala
index 800e83d854..a167c35b89 100644
--- a/src/libvaladoc/api/field.vala
+++ b/src/libvaladoc/api/field.vala
@@ -30,7 +30,10 @@ using Valadoc.Content;
public class Valadoc.Api.Field : Member {
private string? cname;
- public Field (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, bool is_static, bool is_volatile, void* data) {
+ public Field (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, bool is_static, bool is_volatile,
+ void* data)
+ {
base (parent, file, name, accessibility, comment, data);
this.is_static = !(parent is Namespace) && is_static;
diff --git a/src/libvaladoc/api/interface.vala b/src/libvaladoc/api/interface.vala
index 2446d1b0f3..c75846ed8c 100644
--- a/src/libvaladoc/api/interface.vala
+++ b/src/libvaladoc/api/interface.vala
@@ -34,8 +34,13 @@ public class Valadoc.Api.Interface : TypeSymbol {
private string? cname;
- public Interface (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? type_macro_name, string? is_type_macro_name, string? type_cast_macro_name, string? type_function_name, string interface_macro_name, string? dbus_name, void* data) {
- base (parent, file, name, accessibility, comment, type_macro_name, is_type_macro_name, type_cast_macro_name, type_function_name, false, data);
+ public Interface (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? type_macro_name, string? is_type_macro_name,
+ string? type_cast_macro_name, string? type_function_name, string interface_macro_name,
+ string? dbus_name, void* data)
+ {
+ base (parent, file, name, accessibility, comment, type_macro_name, is_type_macro_name,
+ type_cast_macro_name, type_function_name, false, data);
this.interface_macro_name = interface_macro_name;
this.dbus_name = dbus_name;
diff --git a/src/libvaladoc/api/member.vala b/src/libvaladoc/api/member.vala
index 59a80490d4..02754c7b76 100644
--- a/src/libvaladoc/api/member.vala
+++ b/src/libvaladoc/api/member.vala
@@ -26,7 +26,9 @@ using Gee;
public abstract class Valadoc.Api.Member : Symbol {
private SourceComment? source_comment;
- public Member (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, void* data) {
+ public Member (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, void* data)
+ {
base (parent, file, name, accessibility, data);
this.source_comment = comment;
diff --git a/src/libvaladoc/api/method.vala b/src/libvaladoc/api/method.vala
index 3ce82a5001..ce891e1122 100644
--- a/src/libvaladoc/api/method.vala
+++ b/src/libvaladoc/api/method.vala
@@ -44,7 +44,11 @@ public class Valadoc.Api.Method : Member, Callable {
}
- public Method (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? dbus_name, string? dbus_result_name, string? finish_function_cname, MethodBindingType binding_type, bool is_yields, bool is_dbus_visible, bool is_constructor, void* data) {
+ public Method (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? dbus_name, string? dbus_result_name,
+ string? finish_function_cname, MethodBindingType binding_type, bool is_yields,
+ bool is_dbus_visible, bool is_constructor, void* data)
+ {
base (parent, file, name, accessibility, comment, data);
this.finish_function_cname = finish_function_cname;
@@ -139,7 +143,8 @@ public class Valadoc.Api.Method : Member, Callable {
*/
public bool is_static {
get {
- return !is_constructor && binding_type == MethodBindingType.STATIC && parent is Namespace == false;
+ return !is_constructor && binding_type == MethodBindingType.STATIC
+ && parent is Namespace == false;
}
}
diff --git a/src/libvaladoc/api/property.vala b/src/libvaladoc/api/property.vala
index 81ddaa775d..895ddcdf7a 100644
--- a/src/libvaladoc/api/property.vala
+++ b/src/libvaladoc/api/property.vala
@@ -32,7 +32,10 @@ public class Valadoc.Api.Property : Member {
private string? dbus_name;
private string? cname;
- public Property (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? dbus_name, bool is_dbus_visible, PropertyBindingType binding_type, void* data) {
+ public Property (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? dbus_name, bool is_dbus_visible,
+ PropertyBindingType binding_type, void* data)
+ {
base (parent, file, name, accessibility, comment, data);
this.is_dbus_visible = is_dbus_visible;
diff --git a/src/libvaladoc/api/propertyaccessor.vala b/src/libvaladoc/api/propertyaccessor.vala
index 56e0f4918f..7d4b255a82 100644
--- a/src/libvaladoc/api/propertyaccessor.vala
+++ b/src/libvaladoc/api/propertyaccessor.vala
@@ -32,7 +32,9 @@ public class Valadoc.Api.PropertyAccessor : Symbol {
private Ownership ownership;
private string? cname;
- public PropertyAccessor (Property parent, SourceFile file, string name, SymbolAccessibility accessibility, string? cname, PropertyAccessorType type, Ownership ownership, void* data) {
+ public PropertyAccessor (Property parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ string? cname, PropertyAccessorType type, Ownership ownership, void* data)
+ {
base (parent, file, name, accessibility, data);
this.ownership = ownership;
diff --git a/src/libvaladoc/api/signal.vala b/src/libvaladoc/api/signal.vala
index 95d17a02cd..646e71cfb7 100644
--- a/src/libvaladoc/api/signal.vala
+++ b/src/libvaladoc/api/signal.vala
@@ -41,7 +41,10 @@ public class Valadoc.Api.Signal : Member, Callable {
}
- public Signal (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? dbus_name, bool is_dbus_visible, bool is_virtual, void* data) {
+ public Signal (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? dbus_name, bool is_dbus_visible,
+ bool is_virtual, void* data)
+ {
base (parent, file, name, accessibility, comment, data);
this.dbus_name = dbus_name;
diff --git a/src/libvaladoc/api/sourcecomment.vala b/src/libvaladoc/api/sourcecomment.vala
index 4f5c277026..df6d1e1dab 100644
--- a/src/libvaladoc/api/sourcecomment.vala
+++ b/src/libvaladoc/api/sourcecomment.vala
@@ -71,7 +71,9 @@ public class Valadoc.Api.SourceComment {
get;
}
- public SourceComment (string content, SourceFile file, int first_line, int first_column, int last_line, int last_column) {
+ public SourceComment (string content, SourceFile file, int first_line, int first_column,
+ int last_line, int last_column)
+ {
this.first_column = first_column;
this.last_column = last_column;
this.first_line = first_line;
diff --git a/src/libvaladoc/api/struct.vala b/src/libvaladoc/api/struct.vala
index 9910994ded..e1df479c3e 100644
--- a/src/libvaladoc/api/struct.vala
+++ b/src/libvaladoc/api/struct.vala
@@ -35,8 +35,14 @@ public class Valadoc.Api.Struct : TypeSymbol {
private string? type_id;
private string? cname;
- public Struct (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? cname, string? type_macro_name, string? type_function_name, string? type_id, string? dup_function_cname, string? copy_function_cname, string? destroy_function_cname, string? free_function_cname, bool is_basic_type, void* data) {
- base (parent, file, name, accessibility, comment, type_macro_name, null, null, type_function_name, is_basic_type, data);
+ public Struct (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? cname, string? type_macro_name,
+ string? type_function_name, string? type_id, string? dup_function_cname,
+ string? copy_function_cname, string? destroy_function_cname,
+ string? free_function_cname, bool is_basic_type, void* data)
+ {
+ base (parent, file, name, accessibility, comment, type_macro_name, null, null,
+ type_function_name, is_basic_type, data);
this.dup_function_cname = dup_function_cname;
this.copy_function_cname = copy_function_cname;
diff --git a/src/libvaladoc/api/symbol.vala b/src/libvaladoc/api/symbol.vala
index e4cd1ad52e..e4520b3879 100644
--- a/src/libvaladoc/api/symbol.vala
+++ b/src/libvaladoc/api/symbol.vala
@@ -35,7 +35,9 @@ public abstract class Valadoc.Api.Symbol : Node {
get;
}
- public Symbol (Node parent, SourceFile file, string? name, SymbolAccessibility accessibility, void* data) {
+ public Symbol (Node parent, SourceFile file, string? name, SymbolAccessibility accessibility,
+ void* data)
+ {
base (parent, file, name, data);
this.accessibility = accessibility;
diff --git a/src/libvaladoc/api/tree.vala b/src/libvaladoc/api/tree.vala
index cc662d13e8..493a4b45da 100644
--- a/src/libvaladoc/api/tree.vala
+++ b/src/libvaladoc/api/tree.vala
@@ -273,12 +273,15 @@ public class Valadoc.Api.Tree {
* @param packages sources
* @param import_directories List of directories where to find the files
*/
- public void import_documentation (DocumentationImporter[] importers, string[] packages, string[] import_directories) {
+ public void import_documentation (DocumentationImporter[] importers, string[] packages,
+ string[] import_directories)
+ {
HashSet<string> processed = new HashSet<string> ();
foreach (string pkg_name in packages) {
bool imported = false;
foreach (DocumentationImporter importer in importers) {
- string? path = get_file_path ("%s.%s".printf (pkg_name, importer.file_extension), import_directories);
+ string? path = get_file_path ("%s.%s".printf (pkg_name, importer.file_extension),
+ import_directories);
if (path == null) {
continue;
}
diff --git a/src/libvaladoc/api/typereference.vala b/src/libvaladoc/api/typereference.vala
index 1759687d2c..0d5bffc1fb 100644
--- a/src/libvaladoc/api/typereference.vala
+++ b/src/libvaladoc/api/typereference.vala
@@ -32,7 +32,9 @@ public class Valadoc.Api.TypeReference : Item {
private string? dbus_type_signature;
private Ownership ownership;
- public TypeReference (Item parent, Ownership ownership, bool pass_ownership, bool is_dynamic, bool is_nullable, string? dbus_type_signature, void* data) {
+ public TypeReference (Item parent, Ownership ownership, bool pass_ownership, bool is_dynamic,
+ bool is_nullable, string? dbus_type_signature, void* data)
+ {
base (data);
this.dbus_type_signature = dbus_type_signature;
diff --git a/src/libvaladoc/api/typesymbol.vala b/src/libvaladoc/api/typesymbol.vala
index e50ff1596b..d6331ed324 100644
--- a/src/libvaladoc/api/typesymbol.vala
+++ b/src/libvaladoc/api/typesymbol.vala
@@ -34,7 +34,11 @@ public abstract class Valadoc.Api.TypeSymbol : Symbol {
private string? type_cast_macro_name;
private string? type_function_name;
- public TypeSymbol (Node parent, SourceFile file, string name, SymbolAccessibility accessibility, SourceComment? comment, string? type_macro_name, string? is_type_macro_name, string? type_cast_macro_name, string? type_function_name, bool is_basic_type, void* data) {
+ public TypeSymbol (Node parent, SourceFile file, string name, SymbolAccessibility accessibility,
+ SourceComment? comment, string? type_macro_name, string? is_type_macro_name,
+ string? type_cast_macro_name, string? type_function_name, bool is_basic_type,
+ void* data)
+ {
base (parent, file, name, accessibility, data);
this.type_cast_macro_name = type_cast_macro_name;
diff --git a/src/libvaladoc/content/blockcontent.vala b/src/libvaladoc/content/blockcontent.vala
index 54d9e567a4..0411b61fde 100644
--- a/src/libvaladoc/content/blockcontent.vala
+++ b/src/libvaladoc/content/blockcontent.vala
@@ -35,7 +35,9 @@ public abstract class Valadoc.Content.BlockContent : ContentElement {
public override void configure (Settings settings, ResourceLocator locator) {
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
foreach (Block element in _content) {
element.parent = this;
element.check (api_root, container, file_path, reporter, settings);
diff --git a/src/libvaladoc/content/comment.vala b/src/libvaladoc/content/comment.vala
index 6f036c0ba9..71b80b9adf 100644
--- a/src/libvaladoc/content/comment.vala
+++ b/src/libvaladoc/content/comment.vala
@@ -43,7 +43,9 @@ public class Valadoc.Content.Comment : BlockContent {
public override void configure (Settings settings, ResourceLocator locator) {
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
base.check (api_root, container, file_path, reporter, settings);
foreach (Taglet element in _taglets) {
diff --git a/src/libvaladoc/content/contentelement.vala b/src/libvaladoc/content/contentelement.vala
index dbec72d103..6e2c659347 100644
--- a/src/libvaladoc/content/contentelement.vala
+++ b/src/libvaladoc/content/contentelement.vala
@@ -33,7 +33,8 @@ public abstract class Valadoc.Content.ContentElement : Object {
public virtual void configure (Settings settings, ResourceLocator locator) {
}
- public abstract void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings);
+ public abstract void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings);
public abstract void accept (ContentVisitor visitor);
diff --git a/src/libvaladoc/content/embedded.vala b/src/libvaladoc/content/embedded.vala
index bdfdbb6c3a..47add58a46 100644
--- a/src/libvaladoc/content/embedded.vala
+++ b/src/libvaladoc/content/embedded.vala
@@ -25,12 +25,31 @@ using Gee;
public class Valadoc.Content.Embedded : ContentElement, Inline, StyleAttributes {
- public string url { get; set; }
- public string? caption { get; set; }
+ public string url {
+ get;
+ set;
+ }
+
+ public string? caption {
+ get;
+ set;
+ }
+
+ public HorizontalAlign? horizontal_align {
+ get;
+ set;
+ }
+
+ public VerticalAlign? vertical_align {
+ get;
+ set;
+ }
+
+ public string? style {
+ get;
+ set;
+ }
- public HorizontalAlign? horizontal_align { get; set; }
- public VerticalAlign? vertical_align { get; set; }
- public string? style { get; set; }
public Api.Package package;
private ResourceLocator _locator;
@@ -43,10 +62,14 @@ public class Valadoc.Content.Embedded : ContentElement, Inline, StyleAttributes
_locator = locator;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// search relative to our file
if (!Path.is_absolute (url)) {
- string relative_to_file = Path.build_path (Path.DIR_SEPARATOR_S, Path.get_dirname (file_path), url);
+ string relative_to_file = Path.build_path (Path.DIR_SEPARATOR_S,
+ Path.get_dirname (file_path),
+ url);
if (FileUtils.test (relative_to_file, FileTest.EXISTS | FileTest.IS_REGULAR)) {
url = (owned) relative_to_file;
package = container.package;
diff --git a/src/libvaladoc/content/headline.vala b/src/libvaladoc/content/headline.vala
index 3f7150c455..56a4a443e4 100644
--- a/src/libvaladoc/content/headline.vala
+++ b/src/libvaladoc/content/headline.vala
@@ -32,7 +32,9 @@ public class Valadoc.Content.Headline : InlineContent, Block {
_level = 0;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// TODO report error if level == 0 ?
// TODO: content.size == 0?
diff --git a/src/libvaladoc/content/inlinecontent.vala b/src/libvaladoc/content/inlinecontent.vala
index f3c47f1640..aca48c20c4 100644
--- a/src/libvaladoc/content/inlinecontent.vala
+++ b/src/libvaladoc/content/inlinecontent.vala
@@ -25,7 +25,11 @@ using Gee;
public abstract class Valadoc.Content.InlineContent : ContentElement {
- public Gee.List<Inline> content { get { return _content; } }
+ public Gee.List<Inline> content {
+ get {
+ return _content;
+ }
+ }
private Gee.List<Inline> _content;
@@ -36,7 +40,9 @@ public abstract class Valadoc.Content.InlineContent : ContentElement {
internal InlineContent () {
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
foreach (Inline element in _content) {
element.parent = this;
element.check (api_root, container, file_path, reporter, settings);
diff --git a/src/libvaladoc/content/inlinetaglet.vala b/src/libvaladoc/content/inlinetaglet.vala
index 6b7e81786c..812eab39a5 100644
--- a/src/libvaladoc/content/inlinetaglet.vala
+++ b/src/libvaladoc/content/inlinetaglet.vala
@@ -49,7 +49,9 @@ public abstract class Valadoc.Content.InlineTaglet : ContentElement, Taglet, Inl
this.locator = locator;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
ContentElement element = get_content ();
element.parent = this;
diff --git a/src/libvaladoc/content/link.vala b/src/libvaladoc/content/link.vala
index 20fd095e99..6f3bd709a1 100644
--- a/src/libvaladoc/content/link.vala
+++ b/src/libvaladoc/content/link.vala
@@ -25,7 +25,10 @@ using Gee;
public class Valadoc.Content.Link : InlineContent, Inline {
- public string url { get; set; }
+ public string url {
+ get;
+ set;
+ }
internal Link () {
base ();
@@ -34,7 +37,9 @@ public class Valadoc.Content.Link : InlineContent, Inline {
public override void configure (Settings settings, ResourceLocator locator) {
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
base.check (api_root, container, file_path, reporter, settings);
//TODO: check url
}
diff --git a/src/libvaladoc/content/list.vala b/src/libvaladoc/content/list.vala
index 0b04c03c79..b234526488 100644
--- a/src/libvaladoc/content/list.vala
+++ b/src/libvaladoc/content/list.vala
@@ -97,9 +97,17 @@ public class Valadoc.Content.List : ContentElement, Block {
}
}
- public Bullet bullet { get; set; }
+ public Bullet bullet {
+ get;
+ set;
+ }
+
// TODO add initial value (either a number or some letters)
- public Gee.List<ListItem> items { get { return _items; } }
+ public Gee.List<ListItem> items {
+ get {
+ return _items;
+ }
+ }
private Gee.List<ListItem> _items;
@@ -109,7 +117,9 @@ public class Valadoc.Content.List : ContentElement, Block {
_items = new ArrayList<ListItem> ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check individual list items
foreach (ListItem element in _items) {
element.parent = this;
diff --git a/src/libvaladoc/content/listitem.vala b/src/libvaladoc/content/listitem.vala
index 00a112a894..299ce4e4e5 100644
--- a/src/libvaladoc/content/listitem.vala
+++ b/src/libvaladoc/content/listitem.vala
@@ -30,7 +30,9 @@ public class Valadoc.Content.ListItem : BlockContent {
base ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check block content
base.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/note.vala b/src/libvaladoc/content/note.vala
index c8b24e47b4..d35347e05e 100644
--- a/src/libvaladoc/content/note.vala
+++ b/src/libvaladoc/content/note.vala
@@ -29,7 +29,9 @@ public class Valadoc.Content.Note : BlockContent, Block {
base ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check inline content
base.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/paragraph.vala b/src/libvaladoc/content/paragraph.vala
index d50859d0bf..6d474b9404 100644
--- a/src/libvaladoc/content/paragraph.vala
+++ b/src/libvaladoc/content/paragraph.vala
@@ -25,15 +25,28 @@ using Gee;
public class Valadoc.Content.Paragraph : InlineContent, Block, StyleAttributes {
- public HorizontalAlign? horizontal_align { get; set; }
- public VerticalAlign? vertical_align { get; set; }
- public string? style { get; set; }
+ public HorizontalAlign? horizontal_align {
+ get;
+ set;
+ }
+
+ public VerticalAlign? vertical_align {
+ get;
+ set;
+ }
+
+ public string? style {
+ get;
+ set;
+ }
internal Paragraph () {
base ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check inline content
base.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/run.vala b/src/libvaladoc/content/run.vala
index 15a9501e07..e7b19d4b4b 100644
--- a/src/libvaladoc/content/run.vala
+++ b/src/libvaladoc/content/run.vala
@@ -118,7 +118,9 @@ public class Valadoc.Content.Run : InlineContent, Inline {
_style = style;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check inline content
base.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/sourcecode.vala b/src/libvaladoc/content/sourcecode.vala
index de3bdebe61..dd84f1f3e2 100644
--- a/src/libvaladoc/content/sourcecode.vala
+++ b/src/libvaladoc/content/sourcecode.vala
@@ -78,18 +78,29 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
}
}
- public string code { get; set; }
- public Language? language { get; set; }
+ public string code {
+ get;
+ set;
+ }
+
+ public Language? language {
+ get;
+ set;
+ }
internal SourceCode () {
base ();
_language = Language.VALA;
}
- private string? get_path (string path, Api.Node container, string source_file_path, ErrorReporter reporter) {
+ private string? get_path (string path, Api.Node container, 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);
+ 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;
}
@@ -106,7 +117,9 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
return path;
}
- private void load_source_code (string _path, Api.Node container, string source_file_path, ErrorReporter reporter) {
+ private void load_source_code (string _path, Api.Node container, string source_file_path,
+ ErrorReporter reporter)
+ {
string? path = get_path (_path, container, source_file_path, reporter);
if (path == null) {
return ;
@@ -119,7 +132,10 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
code = (owned) content;
} catch (FileError err) {
string node_segment = (container is Api.Package)? "" : container.get_full_name () + ": ";
- reporter.simple_error ("%s: %s{{{: error: Can't read file %s: %s", source_file_path, node_segment, path, err.message);
+ reporter.simple_error ("%s: %s{{{: error: Can't read file %s: %s", source_file_path,
+ node_segment,
+ path,
+ err.message);
}
}
@@ -146,7 +162,9 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
return string.joinv ("\n", (string[]) _lines);
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ 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] ?? "";
@@ -162,7 +180,8 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
code = splitted[1] ?? "";
if (_language == null && name != "none") {
string node_segment = (container is Api.Package)? "" : container.get_full_name () + ": ";
- reporter.simple_warning ("%s: %s{{{: warning: Unsupported programming language '%s'", file_path, node_segment, name);
+ reporter.simple_warning ("%s: %s{{{: warning: Unsupported programming language '%s'",
+ file_path, node_segment, name);
}
}
}
diff --git a/src/libvaladoc/content/styleattributes.vala b/src/libvaladoc/content/styleattributes.vala
index 42a3caae8e..c24893aaf6 100644
--- a/src/libvaladoc/content/styleattributes.vala
+++ b/src/libvaladoc/content/styleattributes.vala
@@ -98,8 +98,19 @@ public enum Valadoc.Content.VerticalAlign {
}
public interface Valadoc.Content.StyleAttributes : ContentElement {
- public abstract HorizontalAlign? horizontal_align { get; set; }
- public abstract VerticalAlign? vertical_align { get; set; }
- public abstract string? style { get; set; }
+ public abstract HorizontalAlign? horizontal_align {
+ get;
+ set;
+ }
+
+ public abstract VerticalAlign? vertical_align {
+ get;
+ set;
+ }
+
+ public abstract string? style {
+ get;
+ set;
+ }
}
diff --git a/src/libvaladoc/content/symbollink.vala b/src/libvaladoc/content/symbollink.vala
index a73b4880d6..0f49b74302 100644
--- a/src/libvaladoc/content/symbollink.vala
+++ b/src/libvaladoc/content/symbollink.vala
@@ -25,8 +25,15 @@ using Gee;
public class Valadoc.Content.SymbolLink : ContentElement, Inline {
- public Api.Node symbol { get; set; }
- public string label { get; set; }
+ public Api.Node symbol {
+ get;
+ set;
+ }
+
+ public string label {
+ get;
+ set;
+ }
internal SymbolLink (Api.Node? symbol = null, string? label = null) {
base ();
@@ -37,7 +44,9 @@ public class Valadoc.Content.SymbolLink : ContentElement, Inline {
public override void configure (Settings settings, ResourceLocator locator) {
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
}
public override void accept (ContentVisitor visitor) {
diff --git a/src/libvaladoc/content/table.vala b/src/libvaladoc/content/table.vala
index 962b063ec2..0a7941a044 100644
--- a/src/libvaladoc/content/table.vala
+++ b/src/libvaladoc/content/table.vala
@@ -25,7 +25,11 @@ using Gee;
public class Valadoc.Content.Table : ContentElement, Block {
- public Gee.List<TableRow> rows { get { return _rows; } }
+ public Gee.List<TableRow> rows {
+ get {
+ return _rows;
+ }
+ }
private Gee.List<TableRow> _rows;
@@ -34,7 +38,9 @@ public class Valadoc.Content.Table : ContentElement, Block {
_rows = new ArrayList<TableRow> ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check the table consistency in term of row/column number
// Check individual rows
diff --git a/src/libvaladoc/content/tablecell.vala b/src/libvaladoc/content/tablecell.vala
index bf83e7d301..50c7fd4bad 100644
--- a/src/libvaladoc/content/tablecell.vala
+++ b/src/libvaladoc/content/tablecell.vala
@@ -25,11 +25,30 @@ using Gee;
public class Valadoc.Content.TableCell : InlineContent, StyleAttributes {
- public HorizontalAlign? horizontal_align { get; set; }
- public VerticalAlign? vertical_align { get; set; }
- public string? style { get; set; }
- public int colspan { get; set; }
- public int rowspan { get; set; }
+ public HorizontalAlign? horizontal_align {
+ get;
+ set;
+ }
+
+ public VerticalAlign? vertical_align {
+ get;
+ set;
+ }
+
+ public string? style {
+ get;
+ set;
+ }
+
+ public int colspan {
+ get;
+ set;
+ }
+
+ public int rowspan {
+ get;
+ set;
+ }
internal TableCell () {
base ();
@@ -37,7 +56,9 @@ public class Valadoc.Content.TableCell : InlineContent, StyleAttributes {
_rowspan = 1;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check inline content
base.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/tablerow.vala b/src/libvaladoc/content/tablerow.vala
index 1ab62ccd8e..d8759caac1 100644
--- a/src/libvaladoc/content/tablerow.vala
+++ b/src/libvaladoc/content/tablerow.vala
@@ -25,7 +25,11 @@ using Gee;
public class Valadoc.Content.TableRow : ContentElement {
- public Gee.List<TableCell> cells { get { return _cells; } }
+ public Gee.List<TableCell> cells {
+ get {
+ return _cells;
+ }
+ }
private Gee.List<TableCell> _cells;
@@ -34,7 +38,9 @@ public class Valadoc.Content.TableRow : ContentElement {
_cells = new ArrayList<TableCell> ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check individual cells
foreach (var cell in _cells) {
cell.parent = this;
diff --git a/src/libvaladoc/content/text.vala b/src/libvaladoc/content/text.vala
index d1639399ac..42ce1e15fe 100644
--- a/src/libvaladoc/content/text.vala
+++ b/src/libvaladoc/content/text.vala
@@ -25,7 +25,10 @@ using Gee;
public class Valadoc.Content.Text : ContentElement, Inline {
- public string content { get; set; }
+ public string content {
+ get;
+ set;
+ }
construct {
_content = "";
@@ -37,7 +40,9 @@ public class Valadoc.Content.Text : ContentElement, Inline {
}
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
}
public override void accept (ContentVisitor visitor) {
diff --git a/src/libvaladoc/content/warning.vala b/src/libvaladoc/content/warning.vala
index d98fbd765f..445a447f85 100644
--- a/src/libvaladoc/content/warning.vala
+++ b/src/libvaladoc/content/warning.vala
@@ -29,7 +29,9 @@ public class Valadoc.Content.Warning : BlockContent, Block {
base ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check inline content
base.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/wikilink.vala b/src/libvaladoc/content/wikilink.vala
index 2592b879f1..7394a96d27 100644
--- a/src/libvaladoc/content/wikilink.vala
+++ b/src/libvaladoc/content/wikilink.vala
@@ -25,14 +25,23 @@ using Gee;
public class Valadoc.Content.WikiLink : InlineContent, Inline {
- public WikiPage page { get; internal set; }
- public string name { get; set; }
+ public WikiPage page {
+ internal set;
+ get;
+ }
+
+ public string name {
+ get;
+ set;
+ }
internal WikiLink () {
base ();
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
base.check (api_root, container, file_path, reporter, settings);
page = api_root.wikitree.search (name);
diff --git a/src/libvaladoc/devhelp-markupwriter.vala b/src/libvaladoc/devhelp-markupwriter.vala
index 2b846512fa..ae524384c7 100644
--- a/src/libvaladoc/devhelp-markupwriter.vala
+++ b/src/libvaladoc/devhelp-markupwriter.vala
@@ -39,7 +39,13 @@ public class Valadoc.Devhelp.MarkupWriter : Valadoc.MarkupWriter {
}
public MarkupWriter start_book (string title, string lang, string link, string name, string version, string author) {
- this.start_tag ("book", {"xmlns", "http://www.devhelp.net/book", "title", title, "language", lang, "name", name, "version", version, "author", author, "link", link});
+ this.start_tag ("book", {"xmlns", "http://www.devhelp.net/book",
+ "title", title,
+ "language", lang,
+ "name", name,
+ "version", version,
+ "author", author,
+ "link", link});
return this;
}
diff --git a/src/libvaladoc/documentation/documentationparser.vala b/src/libvaladoc/documentation/documentationparser.vala
index 6a36314894..9e0b3bb283 100644
--- a/src/libvaladoc/documentation/documentationparser.vala
+++ b/src/libvaladoc/documentation/documentationparser.vala
@@ -28,7 +28,9 @@ using Gee;
public class Valadoc.DocumentationParser : Object, ResourceLocator {
- public DocumentationParser (Settings settings, ErrorReporter reporter, Api.Tree tree, ModuleLoader modules) {
+ public DocumentationParser (Settings settings, ErrorReporter reporter,
+ Api.Tree tree, ModuleLoader modules)
+ {
_settings = settings;
_reporter = reporter;
_tree = tree;
@@ -70,11 +72,14 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
Comment doc_comment = gtkdoc_parser.parse (element, (Api.GirSourceComment) comment);
return doc_comment;
} else {
- return parse_comment_str (element, comment.content, comment.file.get_name (), comment.first_line, comment.first_column);
+ return parse_comment_str (element, comment.content, comment.file.get_name (),
+ comment.first_line, comment.first_column);
}
}
- public Comment? parse_comment_str (Api.Node element, string content, string filename, int first_line, int first_column) {
+ public Comment? parse_comment_str (Api.Node element, string content, string filename,
+ int first_line, int first_column)
+ {
try {
Comment doc_comment = parse_comment (content, filename, first_line, first_column);
doc_comment.check (_tree, element, filename, _reporter, _settings);
@@ -102,7 +107,9 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
}
}
- private Comment parse_comment (string content, string filename, int first_line, int first_column) throws ParserError {
+ private Comment parse_comment (string content, string filename, int first_line, int first_column)
+ throws ParserError
+ {
_parser = _comment_parser;
_scanner = _comment_scanner;
_stack.clear ();
@@ -172,7 +179,8 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
((Paragraph) ((ListItem) peek ()).content[0]).content.add (_factory.create_text (" "));
return;
} else if (list.bullet != bullet) {
- _parser.error (null, "Invalid bullet type '%s': expected '%s'".printf (bullet_type_string (bullet), bullet_type_string (list.bullet)));
+ _parser.error (null, "Invalid bullet type '%s': expected '%s'"
+ .printf (bullet_type_string (bullet), bullet_type_string (list.bullet)));
return;
}
@@ -236,7 +244,9 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
if (head is Text) {
text_node = (Text) head;
- } else if (head is InlineContent && ((InlineContent) head).content.size > 0 && ((InlineContent) head).content.last () is Text) {
+ } else if (head is InlineContent && ((InlineContent) head).content.size > 0
+ && ((InlineContent) head).content.last () is Text)
+ {
text_node = (Text) ((InlineContent) head).content.last ();
} else {
text_node = _factory.create_text ();
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index 8b9c13e9e6..7b97bef655 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -41,6 +41,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
private bool show_warnings;
private Api.SourceComment comment;
+ private unowned string instance_param_name;
private string[]? comment_lines;
@@ -224,7 +225,14 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
this.comment_lines = this.comment.content.split ("\n");
}
- this.reporter.warning (this.comment.file.get_name (), comment.first_line + got.line, startpos + 1, endpos + 1, this.comment_lines[got.line], "Unexpected Token: %s (Expected: %s)", got.to_string (), expected);
+ this.reporter.warning (this.comment.file.get_name (),
+ comment.first_line + got.line,
+ startpos + 1,
+ endpos + 1,
+ this.comment_lines[got.line],
+ "Unexpected Token: %s (Expected: %s)",
+ got.to_string (),
+ expected);
}
public Parser (Settings settings, ErrorReporter reporter, Api.Tree tree, ModuleLoader modules) {
@@ -234,7 +242,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
this.tree = tree;
try {
- is_numeric_regex = new Regex ("^[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)([eE][+-]?[0-9]+)?$", RegexCompileFlags.OPTIMIZE);
+ is_numeric_regex = new Regex ("^[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)([eE][+-]?[0-9]+)?$",
+ RegexCompileFlags.OPTIMIZE);
normalize_regex = new Regex ("( |\n|\t)+", RegexCompileFlags.OPTIMIZE);
} catch (RegexError e) {
assert_not_reached ();
@@ -245,6 +254,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
public Comment? parse (Api.Node element, Api.GirSourceComment gir_comment) {
this.current_metadata = get_metadata_for_comment (gir_comment);
+ this.instance_param_name = gir_comment.instance_param_name;
this.element = element;
Comment? comment = this.parse_main_content (gir_comment);
@@ -371,7 +381,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
private bool check_xml_open_tag (string tagname) {
- if ((current.type == TokenType.XML_OPEN && current.content != tagname) || current.type != TokenType.XML_OPEN) {
+ if ((current.type == TokenType.XML_OPEN && current.content != tagname)
+ || current.type != TokenType.XML_OPEN)
+ {
return false;
}
@@ -380,7 +392,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
private bool check_xml_close_tag (string tagname) {
- if ((current.type == TokenType.XML_CLOSE && current.content != tagname) || current.type != TokenType.XML_CLOSE) {
+ if ((current.type == TokenType.XML_CLOSE && current.content != tagname)
+ || current.type != TokenType.XML_CLOSE)
+ {
return false;
}
@@ -423,7 +437,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
next ();
// TODO: check xml
- while (!(current.type == TokenType.XML_CLOSE && current.content == tagname) && current.type != TokenType.EOF) {
+ while (!(current.type == TokenType.XML_CLOSE && current.content == tagname)
+ && current.type != TokenType.EOF)
+ {
if (current.type == TokenType.XML_OPEN) {
} else if (current.type == TokenType.XML_CLOSE) {
} else if (current.type == TokenType.XML_COMMENT) {
@@ -473,7 +489,10 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
- if (current.type == TokenType.GTKDOC_FUNCTION || current.type == TokenType.GTKDOC_CONST || current.type == TokenType.GTKDOC_TYPE || current.type == TokenType.WORD || current.type == TokenType.GTKDOC_PROPERTY || current.type == TokenType.GTKDOC_SIGNAL) {
+ if (current.type == TokenType.GTKDOC_FUNCTION || current.type == TokenType.GTKDOC_CONST
+ || current.type == TokenType.GTKDOC_TYPE || current.type == TokenType.WORD
+ || current.type == TokenType.GTKDOC_PROPERTY || current.type == TokenType.GTKDOC_SIGNAL)
+ {
taglet = this.create_type_link (current.content) as InlineTaglet;
assert (taglet != null);
}
@@ -629,7 +648,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
return parse_docbook_itemizedlist ("orderedlist", Content.List.Bullet.ORDERED);
}
- private LinkedList<Block>? parse_docbook_itemizedlist (string tag_name = "itemizedlist", Content.List.Bullet bullet_type = Content.List.Bullet.UNORDERED) {
+ private LinkedList<Block>? 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;
@@ -829,7 +850,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
StringBuilder builder = new StringBuilder ();
- for (next (); current.type != TokenType.EOF && !(current.type == TokenType.XML_CLOSE && current.content == "programlisting"); next ()) {
+ for (next (); current.type != TokenType.EOF && !(current.type == TokenType.XML_CLOSE
+ && current.content == "programlisting"); next ())
+ {
if (current.type == TokenType.WORD) {
builder.append (current.content);
} else if (current.type != TokenType.XML_COMMENT) {
@@ -1540,7 +1563,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
return {id};
}
- private string? resolve_parameter_ctype (string parameter_name, out string? param_name, out string? param_array_name, out bool is_return_type_len) {
+ private string? resolve_parameter_ctype (string parameter_name, out string? param_name,
+ out string? param_array_name, out bool is_return_type_len)
+ {
string[]? parts = split_type_name (parameter_name);
is_return_type_len = false;
param_array_name = null;
@@ -1558,7 +1583,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
- if (this.element is Api.Callable && ((Api.Callable) this.element).implicit_array_length_cparameter_name == parts[0]) {
+ if (this.element is Api.Callable
+ && ((Api.Callable) this.element).implicit_array_length_cparameter_name == parts[0])
+ {
is_return_type_len = true;
}
diff --git a/src/libvaladoc/documentation/gtkdoccommentscanner.vala b/src/libvaladoc/documentation/gtkdoccommentscanner.vala
index 8f97416859..75f2d58ed5 100644
--- a/src/libvaladoc/documentation/gtkdoccommentscanner.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentscanner.vala
@@ -56,7 +56,9 @@ public class Valadoc.Gtkdoc.Token {
public int first_column;
public int last_column;
- public Token (TokenType type, string content, HashMap<string, string>? attributes, string start, int length, int line, int first_column, int last_column) {
+ public Token (TokenType type, string content, HashMap<string, string>? attributes, string start,
+ int length, int line, int first_column, int last_column)
+ {
this.attributes = attributes;
this.content = content;
this.length = length;
@@ -244,11 +246,14 @@ public class Valadoc.Gtkdoc.Scanner {
}
private inline bool letter (unichar c) {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
+ return (c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z');
}
private inline bool letter_or_number (unichar c) {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
+ return (c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9');
}
private inline bool space (unichar c) {
@@ -340,7 +345,14 @@ public class Valadoc.Gtkdoc.Scanner {
}
next_char ();
- return new Token (TokenType.GTKDOC_FUNCTION, start.substring (0, id_len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.GTKDOC_FUNCTION,
+ start.substring (0, id_len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private inline Token? gtkdoc_symbolic_link_prefix (unichar c, TokenType type) {
@@ -403,7 +415,14 @@ public class Valadoc.Gtkdoc.Scanner {
}
}
- return new Token (type, start.substring (1, id_len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (type,
+ start.substring (1, id_len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private inline Token? gtkdoc_property_prefix () {
@@ -423,7 +442,14 @@ public class Valadoc.Gtkdoc.Scanner {
return null;
}
- return new Token (TokenType.GTKDOC_PROPERTY, start.substring (1, id_len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.GTKDOC_PROPERTY,
+ start.substring (1, id_len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private inline Token? gtkdoc_signal_prefix () {
@@ -451,7 +477,14 @@ public class Valadoc.Gtkdoc.Scanner {
return null;
}
- return new Token (TokenType.GTKDOC_SIGNAL, start.substring (1, id_len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.GTKDOC_SIGNAL,
+ start.substring (1, id_len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private inline Token? gtkdoc_const_prefix () {
@@ -493,7 +526,14 @@ public class Valadoc.Gtkdoc.Scanner {
next_char ();
next_char ();
next_char ();
- return new Token (TokenType.XML_COMMENT, "", null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.XML_COMMENT,
+ "",
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
}
} else if (this.pos.has_prefix ("[CDATA[")) {
@@ -513,7 +553,14 @@ public class Valadoc.Gtkdoc.Scanner {
next_char ();
next_char ();
next_char ();
- return new Token (TokenType.WORD, unescape (content), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.WORD,
+ unescape (content),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
}
}
@@ -598,13 +645,34 @@ public class Valadoc.Gtkdoc.Scanner {
next_char ();
if (open_and_close) {
- this.tmp_token = new Token (TokenType.XML_CLOSE, id_start.substring (0, id_len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ this.tmp_token = new Token (TokenType.XML_CLOSE,
+ id_start.substring (0, id_len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
if (close) {
- return new Token (TokenType.XML_CLOSE, id_start.substring (0, id_len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.XML_CLOSE,
+ id_start.substring (0, id_len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
} else {
- return new Token (TokenType.XML_OPEN, id_start.substring (0, id_len), map, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.XML_OPEN,
+ id_start.substring (0, id_len),
+ map,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
}
@@ -623,9 +691,23 @@ public class Valadoc.Gtkdoc.Scanner {
next_char ();
this.line++;
this.column = 0;
- return new Token (TokenType.GTKDOC_PARAGRAPH, "\n\n", null, start, offset (this.pos, start), this.line, this.column, this.column);
+ return new Token (TokenType.GTKDOC_PARAGRAPH,
+ "\n\n",
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ this.column,
+ this.column);
} else {
- return new Token (TokenType.NEWLINE, "\n", null, start, offset (this.pos, start), this.line, this.column, this.column);
+ return new Token (TokenType.NEWLINE,
+ "\n",
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ this.column,
+ this.column);
}
}
@@ -634,7 +716,14 @@ public class Valadoc.Gtkdoc.Scanner {
return null;
}
- return new Token (TokenType.EOF, "", null, this.pos, 1, this.line, this.column, this.column);
+ return new Token (TokenType.EOF,
+ "",
+ null,
+ this.pos,
+ 1,
+ this.line,
+ this.column,
+ this.column);
}
private Token? space_prefix () {
@@ -648,7 +737,14 @@ public class Valadoc.Gtkdoc.Scanner {
return null;
}
- return new Token (TokenType.SPACE, start.substring (0, len), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.SPACE,
+ start.substring (0, len),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private Token? word_prefix () {
@@ -667,7 +763,14 @@ public class Valadoc.Gtkdoc.Scanner {
return null;
}
- return new Token (TokenType.WORD, unescape (start.substring (0, len)), null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.WORD,
+ unescape (start.substring (0, len)),
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private Token? gtkdoc_source_open_prefix () {
@@ -680,7 +783,14 @@ public class Valadoc.Gtkdoc.Scanner {
next_char ();
next_char ();
- return new Token (TokenType.GTKDOC_SOURCE_OPEN, "|[", null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.GTKDOC_SOURCE_OPEN,
+ "|[",
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
private Token? gtkdoc_source_close_prefix () {
@@ -693,7 +803,13 @@ public class Valadoc.Gtkdoc.Scanner {
next_char ();
next_char ();
- return new Token (TokenType.GTKDOC_SOURCE_CLOSE, "]|", null, start, offset (this.pos, start), this.line, column_start, this.column);
+ return new Token (TokenType.GTKDOC_SOURCE_CLOSE, "]|",
+ null,
+ start,
+ offset (this.pos, start),
+ this.line,
+ column_start,
+ this.column);
}
public Token next () {
@@ -772,4 +888,3 @@ public class Valadoc.Gtkdoc.Scanner {
}
}
-
diff --git a/src/libvaladoc/documentation/wiki.vala b/src/libvaladoc/documentation/wiki.vala
index 113f2f08ae..614d91848c 100644
--- a/src/libvaladoc/documentation/wiki.vala
+++ b/src/libvaladoc/documentation/wiki.vala
@@ -110,18 +110,24 @@ public class Valadoc.WikiPageTree : Object {
return null;
}
- private void create_tree_from_path (DocumentationParser docparser, Api.Package package, ErrorReporter reporer, string path, string? nameoffset = null) {
+ private void create_tree_from_path (DocumentationParser docparser, Api.Package package,
+ ErrorReporter reporer, string path, string? nameoffset = null)
+ {
try {
Dir dir = Dir.open (path);
for (string? curname = dir.read_name (); curname!=null ; curname = dir.read_name ()) {
string filename = Path.build_filename (path, curname);
if (curname.has_suffix (".valadoc") && FileUtils.test (filename, FileTest.IS_REGULAR)) {
- WikiPage wikipage = new WikiPage ((nameoffset!=null)? Path.build_filename (nameoffset, curname) : curname, filename, package);
+ WikiPage wikipage = new WikiPage ((nameoffset!=null)
+ ? Path.build_filename (nameoffset, curname)
+ : curname, filename, package);
this.wikipages.add(wikipage);
wikipage.read (reporter);
} else if (FileUtils.test (filename, FileTest.IS_DIR)) {
- this.create_tree_from_path (docparser, package, reporter, filename, (nameoffset!=null)? Path.build_filename (nameoffset, curname) : curname);
+ this.create_tree_from_path (docparser, package, reporter, filename, (nameoffset!=null)
+ ? Path.build_filename (nameoffset, curname)
+ : curname);
}
}
} catch (FileError err) {
diff --git a/src/libvaladoc/documentation/wikiscanner.vala b/src/libvaladoc/documentation/wikiscanner.vala
index b9c2fbecb4..d3e36c6967 100644
--- a/src/libvaladoc/documentation/wikiscanner.vala
+++ b/src/libvaladoc/documentation/wikiscanner.vala
@@ -345,7 +345,9 @@ public class Valadoc.WikiScanner : Object, Scanner {
}
}
- private void look_for_three (unichar c, TokenType one, TokenType two, TokenType three) throws ParserError {
+ private void look_for_three (unichar c, TokenType one, TokenType two, TokenType three)
+ throws ParserError
+ {
if (get_next_char (1) == c) {
if (get_next_char (2) == c) {
emit_token (three);
@@ -359,7 +361,9 @@ public class Valadoc.WikiScanner : Object, Scanner {
}
}
- private void look_for_five (unichar c, TokenType one, TokenType two, TokenType three, TokenType four, TokenType five) throws ParserError {
+ private void look_for_five (unichar c, TokenType one, TokenType two, TokenType three,
+ TokenType four, TokenType five) throws ParserError
+ {
if (get_next_char (1) == c) {
if (get_next_char (2) == c) {
if (get_next_char (3) == c) {
diff --git a/src/libvaladoc/errorreporter.vala b/src/libvaladoc/errorreporter.vala
index b7359820d5..6c5a794a69 100644
--- a/src/libvaladoc/errorreporter.vala
+++ b/src/libvaladoc/errorreporter.vala
@@ -65,8 +65,11 @@ public class Valadoc.ErrorReporter : Object {
this.settings = settings;
}
- private inline void msg (string type, string file, long line, long startpos, long endpos, string errline, string msg_format, va_list args) {
- this.stream.printf ("%s:%lu.%lu-%lu.%lu: %s: ", file, line, startpos, line, endpos, type);
+ private inline void msg (string type, string file, long line, long startpos, long endpos,
+ string errline, string msg_format, va_list args)
+ {
+ this.stream.printf ("%s:%lu.%lu-%lu.%lu: %s: ", file, line, startpos,
+ line, endpos, type);
this.stream.vprintf (msg_format, args);
this.stream.putc ('\n');
@@ -108,13 +111,17 @@ public class Valadoc.ErrorReporter : Object {
}
}
- public void error (string file, long line, long startpos, long endpos, string errline, string msg_format, ...) {
+ public void error (string file, long line, long startpos, long endpos, string errline,
+ string msg_format, ...)
+ {
var args = va_list();
this.msg ("error", file, line, startpos, endpos, errline, msg_format, args);
this._errors++;
}
- public void warning (string file, long line, long startpos, long endpos, string errline, string msg_format, ...) {
+ public void warning (string file, long line, long startpos, long endpos, string errline,
+ string msg_format, ...)
+ {
var args = va_list();
this.msg ("warning", file, line, startpos, endpos, errline, msg_format, args);
this._warnings++;
diff --git a/src/libvaladoc/gtkdocrenderer.vala b/src/libvaladoc/gtkdocrenderer.vala
index f13b09e9b0..69ade76b46 100644
--- a/src/libvaladoc/gtkdocrenderer.vala
+++ b/src/libvaladoc/gtkdocrenderer.vala
@@ -65,21 +65,34 @@ public class Valadoc.GtkdocRenderer : ContentRenderer {
writer.set_wrap (false);
if (item is Api.Method) {
- writer.start_tag ("function").text (((Api.Method)item).get_cname ()).end_tag ("function");
+ writer.start_tag ("function")
+ .text (((Api.Method)item).get_cname ())
+ .end_tag ("function");
} else if (item is Api.FormalParameter) {
- writer.start_tag ("parameter").text (((Api.FormalParameter)item).name ?? "...").end_tag ("parameter");
+ writer.start_tag ("parameter").
+ text (((Api.FormalParameter)item).name ?? "...")
+ .end_tag ("parameter");
} else if (item is Api.Constant) {
- writer.start_tag ("constant").text (((Api.Constant)item).get_cname ()).end_tag ("constant");
+ writer.start_tag ("constant").text (((Api.Constant)item)
+ .get_cname ())
+ .end_tag ("constant");
} else if (item is Api.Property) {
// TODO: use docbook-tags instead
- writer.text ("#").text (get_cname(item.parent)).text (":").text (((Api.Property)item).get_cname ().replace ("_", "-"));
+ writer.text ("#").text (get_cname(item.parent))
+ .text (":")
+ .text (((Api.Property)item)
+ .get_cname ().replace ("_", "-"));
} else if (item is Api.Signal) {
// TODO: use docbook-tags instead
- writer.text ("#").text (get_cname(item.parent)).text ("::").text (((Api.Signal)item).get_cname ().replace ("_", "-"));
+ writer.text ("#").text (get_cname(item.parent))
+ .text ("::")
+ .text (((Api.Signal)item).get_cname ().replace ("_", "-"));
} else if (item is Api.Namespace) {
writer.text (((Api.Namespace) item).get_full_name ());
} else {
- writer.start_tag ("type").text (get_cname (item)).end_tag ("type");
+ writer.start_tag ("type")
+ .text (get_cname (item))
+ .end_tag ("type");
}
writer.set_wrap (true);
@@ -128,15 +141,23 @@ public class Valadoc.GtkdocRenderer : ContentRenderer {
public override void visit_embedded (Embedded element) {
writer.start_tag ("figure");
if (element.caption != null) {
- writer.start_tag ("title").text (element.caption).end_tag ("title");
+ writer.start_tag ("title")
+ .text (element.caption)
+ .end_tag ("title");
}
writer.start_tag ("mediaobject");
- writer.start_tag ("imageobject").simple_tag ("imagedata", {"fileref", element.url}).end_tag ("imageobject");
+ writer.start_tag ("imageobject")
+ .simple_tag ("imagedata", {"fileref", element.url})
+ .end_tag ("imageobject");
if (element.caption != null) {
- writer.start_tag ("textobject").start_tag ("phrase").text (element.caption).end_tag ("phrase").end_tag ("textobject");
+ writer.start_tag ("textobject")
+ .start_tag ("phrase")
+ .text (element.caption)
+ .end_tag ("phrase")
+ .end_tag ("textobject");
}
writer.end_tag ("mediaobject");
@@ -277,9 +298,11 @@ public class Valadoc.GtkdocRenderer : ContentRenderer {
}
public override void visit_source_code (SourceCode element) {
- writer.start_tag ("example").start_tag ("programlisting");
+ writer.start_tag ("example")
+ .start_tag ("programlisting");
writer.text (element.code);
- writer.end_tag ("programlisting").end_tag ("example");
+ writer.end_tag ("programlisting")
+ .end_tag ("example");
}
public override void visit_table (Table element) {
@@ -395,7 +418,8 @@ public class Valadoc.GtkdocRenderer : ContentRenderer {
}
writer.set_wrap (false);
- writer.text ("\nSince: ").text (taglet.version);
+ writer.text ("\nSince: ")
+ .text (taglet.version);
writer.set_wrap (true);
separated = true;
@@ -438,7 +462,9 @@ public class Valadoc.GtkdocRenderer : ContentRenderer {
}
if (first) {
- writer.start_tag ("para").text ("This function may throw:").end_tag ("para");
+ writer.start_tag ("para")
+ .text ("This function may throw:")
+ .end_tag ("para");
writer.start_tag ("table");
}
diff --git a/src/libvaladoc/html/basicdoclet.vala b/src/libvaladoc/html/basicdoclet.vala
index 5977756b69..fceaf906c7 100644
--- a/src/libvaladoc/html/basicdoclet.vala
+++ b/src/libvaladoc/html/basicdoclet.vala
@@ -26,8 +26,16 @@ using Valadoc.Api;
public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
- public Html.LinkHelper linker { protected set; get; }
- public Settings settings { protected set; get; }
+ public Html.LinkHelper linker {
+ protected set;
+ get;
+ }
+
+ public Settings settings {
+ protected set;
+ get;
+ }
+
protected Api.Tree tree;
protected HtmlRenderer _renderer;
protected Html.MarkupWriter writer;
@@ -120,7 +128,8 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
protected virtual string get_img_path (Api.Node element, string type) {
- return Path.build_filename (settings.path, element.package.name, "img", element.get_full_name () + "." + type);
+ return Path.build_filename (settings.path, element.package.name, "img",
+ element.get_full_name () + "." + type);
}
protected virtual string get_icon_directory () {
@@ -162,7 +171,9 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
writer.end_tag ("li");
}
- protected void write_navi_entry_html_template_with_link (string style, string link, string content, bool is_deprecated) {
+ protected void write_navi_entry_html_template_with_link (string style, string link,
+ string content, bool is_deprecated)
+ {
writer.start_tag ("li", {"class", style});
if (is_deprecated) {
@@ -176,7 +187,9 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
writer.end_tag ("li");
}
- protected void write_navi_entry (Api.Node element, Api.Node? pos, string style, bool link, bool full_name = false) {
+ protected void write_navi_entry (Api.Node element, Api.Node? pos, string style,
+ bool link, bool full_name = false)
+ {
string name;
if (full_name == true && element is Namespace) {
@@ -190,13 +203,18 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
bool is_deprecated = element is Symbol && ((Symbol) element).is_deprecated;
if (link == true) {
- this.write_navi_entry_html_template_with_link (style, this.get_link (element, pos), name, is_deprecated);
+ this.write_navi_entry_html_template_with_link (style,
+ this.get_link (element, pos),
+ name,
+ is_deprecated);
} else {
this.write_navi_entry_html_template (style, name, is_deprecated);
}
}
- protected void write_wiki_pages (Api.Tree tree, string css_path_wiki, string js_path_wiki, string contentp) {
+ protected void write_wiki_pages (Api.Tree tree, string css_path_wiki, string js_path_wiki,
+ string contentp)
+ {
if (tree.wikitree == null) {
return ;
}
@@ -221,8 +239,13 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
}
- protected virtual void write_wiki_page (WikiPage page, string contentp, string css_path, string js_path, string pkg_name) {
- GLib.FileStream file = GLib.FileStream.open (Path.build_filename(contentp, page.name.substring (0, page.name.length-7).replace ("/", ".")+"htm"), "w");
+ protected virtual void write_wiki_page (WikiPage page, string contentp, string css_path,
+ string js_path, string pkg_name)
+ {
+ GLib.FileStream file = GLib.FileStream.open (
+ Path.build_filename (contentp, page.name.substring (0, page.name.length-7).replace ("/", ".")+"htm"),
+ "w");
+
writer = new MarkupWriter (file);
_renderer.set_writer (writer);
this.write_file_header (css_path, js_path, pkg_name);
@@ -374,8 +397,13 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
writer.start_tag ("div", {"class", css_package_note});
- writer.start_tag ("b").text ("Package:").end_tag ("b");
- writer.text (" ").start_tag ("a", {"href", get_link (element.package, element)}).text (package).end_tag ("a");
+ writer.start_tag ("b")
+ .text ("Package:")
+ .end_tag ("b");
+ writer.text (" ")
+ .start_tag ("a", {"href", get_link (element.package, element)})
+ .text (package)
+ .end_tag ("a");
writer.end_tag ("div");
}
@@ -390,8 +418,13 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
writer.start_tag ("div", {"class", css_namespace_note});
- writer.start_tag ("b").text ("Namespace:").end_tag ("b");
- writer.text (" ").start_tag ("a", {"href", get_link (ns, element)}).text (ns.get_full_name()).end_tag ("a");
+ writer.start_tag ("b")
+ .text ("Namespace:")
+ .end_tag ("b");
+ writer.text (" ")
+ .start_tag ("a", {"href", get_link (ns, element)})
+ .text (ns.get_full_name())
+ .end_tag ("a");
writer.end_tag ("div");
}
@@ -446,7 +479,8 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
if (replacement != null) {
string replacement_name = replacement.get_value_as_string ();
- Api.Node? replacement_node = tree.search_symbol_str (pos, replacement_name.substring (1, replacement_name.length - 2));
+ Api.Node? replacement_node = tree.search_symbol_str (pos,
+ replacement_name.substring (1, replacement_name.length - 2));
writer.text (" Use ");
if (replacement_node == null) {
@@ -457,7 +491,9 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
string css = cssresolver.resolve (replacement_node);
writer.link (link, replacement_node.get_full_name (), css);
} else {
- writer.start_tag ("code").text (replacement_node.get_full_name ()).end_tag ("code");
+ writer.start_tag ("code")
+ .text (replacement_node.get_full_name ())
+ .end_tag ("code");
}
}
writer.text (".");
@@ -530,17 +566,25 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
public void write_package_index_content (Api.Tree tree) {
writer.start_tag ("div", {"class", css_style_content});
- writer.start_tag ("h1", {"class", css_title}).text ("Packages:").end_tag ("h1");
+ writer.start_tag ("h1", {"class", css_title})
+ .text ("Packages:")
+ .end_tag ("h1");
writer.simple_tag ("hr", {"class", css_headline_hr});
- WikiPage? wikiindex = (tree.wikitree == null)? null : tree.wikitree.search ("index.valadoc");
+ WikiPage? wikiindex = (tree.wikitree == null)
+ ? null
+ : tree.wikitree.search ("index.valadoc");
if (wikiindex != null) {
_renderer.set_container (wikiindex);
_renderer.render (wikiindex.documentation);
}
- writer.start_tag ("h2", {"class", css_title}).text ("Content:").end_tag ("h2");
- writer.start_tag ("h3", {"class", css_title}).text ("Packages:").end_tag ("h3");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Content:")
+ .end_tag ("h2");
+ writer.start_tag ("h3", {"class", css_title})
+ .text ("Packages:")
+ .end_tag ("h3");
this.write_navi_packages_inline (tree);
writer.end_tag ("div");
}
@@ -574,9 +618,15 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
// headline:
writer.start_tag ("div", {"class", css_box_headline});
- writer.start_tag ("div", {"class", css_box_headline_text}).text (headline).end_tag ("div");
+ writer.start_tag ("div", {"class", css_box_headline_text})
+ .text (headline)
+ .end_tag ("div");
writer.start_tag ("div", {"class", css_box_headline_toggle});
- writer.start_tag ("img", {"onclick", "toggle_box (this, '" + html_id + "')", "src", Path.build_filename (get_icon_directory (), "coll_open.png")});
+ writer.start_tag ("img", {"onclick",
+ "toggle_box (this, '" + html_id + "')",
+ "src",
+ Path.build_filename (get_icon_directory (),
+ "coll_open.png")});
writer.raw_text (" ");
writer.end_tag ("div");
writer.end_tag ("div");
@@ -621,10 +671,14 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
public void write_symbol_content (Api.Node node) {
writer.start_tag ("div", {"class", css_style_content});
- writer.start_tag ("h1", {"class", css_title}).text (node.name).end_tag ("h1");
+ writer.start_tag ("h1", {"class", css_title})
+ .text (node.name)
+ .end_tag ("h1");
writer.simple_tag ("hr", {"class", css_headline_hr});
this.write_image_block (node);
- writer.start_tag ("h2", {"class", css_title}).text ("Description:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Description:")
+ .end_tag ("h2");
writer.start_tag ("div", {"class", css_code_definition});
if (node is Symbol) {
this.write_attributes ((Symbol) node, node);
@@ -635,15 +689,25 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
if (node is Class) {
var cl = node as Class;
- write_known_symbols_note (cl.get_known_child_classes (), cl, "All known sub-classes:");
- write_known_symbols_note (cl.get_known_derived_interfaces (), cl, "Required by:");
+ write_known_symbols_note (cl.get_known_child_classes (),
+ cl,
+ "All known sub-classes:");
+ write_known_symbols_note (cl.get_known_derived_interfaces (),
+ cl,
+ "Required by:");
} else if (node is Interface) {
var iface = node as Interface;
- write_known_symbols_note (iface.get_known_implementations (), iface, "All known implementing classes:");
- write_known_symbols_note (iface.get_known_related_interfaces (), iface, "All known sub-interfaces:");
+ write_known_symbols_note (iface.get_known_implementations (),
+ iface,
+ "All known implementing classes:");
+ write_known_symbols_note (iface.get_known_related_interfaces (),
+ iface,
+ "All known sub-interfaces:");
} else if (node is Struct) {
var stru = node as Struct;
- write_known_symbols_note (stru.get_known_child_structs (), stru, "All known sub-structs:");
+ write_known_symbols_note (stru.get_known_child_structs (),
+ stru,
+ "All known sub-structs:");
}
@@ -714,7 +778,9 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
private void write_inherited_members_headline () {
- writer.start_tag ("h3", {"class", css_title}).text ("Inherited Members:").end_tag ("h3");
+ writer.start_tag ("h3", {"class", css_title})
+ .text ("Inherited Members:")
+ .end_tag ("h3");
}
private void write_inherited_symbols_note_for_class (Class cl, Api.Node container) {
@@ -792,16 +858,32 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
private void write_inherited_symbols_note (TypeSymbol symbol, string type, Api.Node container) {
- write_known_symbols_note (symbol.get_children_by_types (inheritable_members, false), container, "All known members inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_types (inheritable_members, false),
+ container,
+ "All known members inherited from %s %s".printf (type, symbol.get_full_name ()));
/*
- write_known_symbols_note (symbol.get_children_by_type (NodeType.CONSTANT, false), container, "All known constants inherited from %s %s".printf (type, symbol.get_full_name ()));
- write_known_symbols_note (symbol.get_children_by_type (NodeType.PROPERTY, false), container, "All known properties inherited from %s %s".printf (type, symbol.get_full_name ()));
- write_known_symbols_note (symbol.get_children_by_type (NodeType.DELEGATE, false), container, "All known delegates inherited from %s %s".printf (type, symbol.get_full_name ()));
- write_known_symbols_note (symbol.get_children_by_type (NodeType.STATIC_METHOD, false), container, "All known static methods inherited from %s %s".printf (type, symbol.get_full_name ()));
- write_known_symbols_note (symbol.get_children_by_type (NodeType.METHOD, false), container, "All known methods inherited from %s %s".printf (type, symbol.get_full_name ()));
- write_known_symbols_note (symbol.get_children_by_type (NodeType.SIGNAL, false), container, "All known signals inherited from %s %s".printf (type, symbol.get_full_name ()));
- write_known_symbols_note (symbol.get_children_by_type (NodeType.FIELD, false), container, "All known fields inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.CONSTANT, false),
+ container,
+ "All known constants inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.PROPERTY, false),
+ container,
+ "All known properties inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.DELEGATE, false),
+ container,
+ "All known delegates inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.STATIC_METHOD, false),
+ container,
+ "All known static methods inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.METHOD, false),
+ container,
+ "All known methods inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.SIGNAL, false),
+ container,
+ "All known signals inherited from %s %s".printf (type, symbol.get_full_name ()));
+ write_known_symbols_note (symbol.get_children_by_type (NodeType.FIELD, false),
+ container,
+ "All known fields inherited from %s %s".printf (type, symbol.get_full_name ()));
*/
}
@@ -821,7 +903,9 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
bool with_childs = parent != null && parent is Package;
- writer.start_tag ("h3", {"class", css_title}).text ("Namespaces:").end_tag ("h3");
+ writer.start_tag ("h3", {"class", css_title})
+ .text ("Namespaces:")
+ .end_tag ("h3");
writer.start_tag ("ul", {"class", css_inline_navigation});
foreach (Namespace child in namespaces) {
if (child.name != null) {
@@ -852,12 +936,16 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
return;
}
- writer.start_tag ("h2", {"class", css_title}).text ("Dependencies:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Dependencies:")
+ .end_tag ("h2");
writer.start_tag ("ul", {"class", css_inline_navigation});
foreach (Package p in deps) {
string? link = this.get_link (p, parent);
if (link == null) {
- writer.start_tag ("li", {"class", cssresolver.resolve (p), "id", p.name}).text (p.name).end_tag ("li");
+ writer.start_tag ("li", {"class", cssresolver.resolve (p), "id", p.name})
+ .text (p.name)
+ .end_tag ("li");
} else {
writer.start_tag ("li", {"class", cssresolver.resolve (p)});
writer.link (get_link (p, parent), p.name);
@@ -870,7 +958,10 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
protected void write_children (Api.Node node, Api.NodeType type, string type_string, Api.Node? container) {
var children = node.get_children_by_type (type);
if (children.size > 0) {
- writer.start_tag ("h3", {"class", css_title}).text (type_string).text (":").end_tag ("h3");
+ writer.start_tag ("h3", {"class", css_title})
+ .text (type_string)
+ .text (":")
+ .end_tag ("h3");
writer.start_tag ("ul", {"class", css_inline_navigation});
foreach (Api.Node child in children) {
writer.start_tag ("li", {"class", cssresolver.resolve (child)});
@@ -910,22 +1001,37 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
var chart = new Charts.Hierarchy (image_factory, element);
chart.save (this.get_img_path (element, "png"), "png");
- writer.start_tag ("h2", {"class", css_title}).text ("Object Hierarchy:").end_tag ("h2");
-
- writer.simple_tag ("img", {"class", css_diagram, "usemap", "#"+element.get_full_name (),"alt", "Object hierarchy for %s".printf (element.name), "src", this.get_img_path_html (element, "png")});
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Object Hierarchy:")
+ .end_tag ("h2");
+
+ writer.simple_tag ("img", {"class",
+ css_diagram,
+ "usemap",
+ "#"+element.get_full_name (),
+ "alt",
+ "Object hierarchy for %s".printf (element.name),
+ "src",
+ this.get_img_path_html (element, "png")});
writer.add_usemap (chart);
}
}
public void write_namespace_content (Namespace node, Api.Node? parent) {
writer.start_tag ("div", {"class", css_style_content});
- writer.start_tag ("h1", {"class", css_title}).text (node.name == null ? "Global Namespace" : node.get_full_name ()).end_tag ("h1");
+ writer.start_tag ("h1", {"class", css_title})
+ .text (node.name == null ? "Global Namespace" : node.get_full_name ())
+ .end_tag ("h1");
writer.simple_tag ("hr", {"class", css_hr});
- writer.start_tag ("h2", {"class", css_title}).text ("Description:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Description:")
+ .end_tag ("h2");
this.write_documentation (node, parent);
- writer.start_tag ("h2", {"class", css_title}).text ("Content:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Content:")
+ .end_tag ("h2");
if (node.name == null) {
this.write_child_namespaces ((Package) node.parent, parent);
@@ -947,9 +1053,13 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
protected void write_package_content (Package node, Api.Node? parent) {
writer.start_tag ("div", {"class", css_style_content});
- writer.start_tag ("h1", {"class", css_title, "id", node.name}).text (node.name).end_tag ("h1");
+ writer.start_tag ("h1", {"class", css_title, "id", node.name})
+ .text (node.name)
+ .end_tag ("h1");
writer.simple_tag ("hr", {"class", css_headline_hr});
- writer.start_tag ("h2", {"class", css_title}).text ("Description:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Description:")
+ .end_tag ("h2");
WikiPage? wikipage = (tree.wikitree == null)? null : tree.wikitree.search ("index.valadoc");
@@ -958,7 +1068,9 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
_renderer.render (wikipage.documentation);
}
- writer.start_tag ("h2", {"class", css_title}).text ("Content:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", css_title})
+ .text ("Content:")
+ .end_tag ("h2");
this.write_child_namespaces (node, parent);
@@ -984,9 +1096,14 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
writer.start_tag ("html");
writer.start_tag ("head");
if (title == null) {
- writer.start_tag ("title").text ("Vala Binding Reference").end_tag ("title");
+ writer.start_tag ("title")
+ .text ("Vala Binding Reference")
+ .end_tag ("title");
} else {
- writer.start_tag ("title").text (title).text (" – Vala Binding Reference").end_tag ("title");
+ writer.start_tag ("title")
+ .text (title)
+ .text (" – Vala Binding Reference")
+ .end_tag ("title");
}
writer.stylesheet_link (css);
writer.javascript_link (js);
diff --git a/src/libvaladoc/html/htmlmarkupwriter.vala b/src/libvaladoc/html/htmlmarkupwriter.vala
index 435d833a19..3a6b4b2e94 100644
--- a/src/libvaladoc/html/htmlmarkupwriter.vala
+++ b/src/libvaladoc/html/htmlmarkupwriter.vala
@@ -29,14 +29,18 @@ public class Valadoc.Html.MarkupWriter : Valadoc.MarkupWriter {
// avoid broken implicit copy
unowned FileStream _stream = stream;
- base ((str) => { _stream.printf (str); }, xml_declaration);
+ base ((str) => {
+ _stream.printf (str);
+ }, xml_declaration);
}
public MarkupWriter.builder (StringBuilder builder, bool xml_declaration = true) {
// avoid broken implicit copy
unowned StringBuilder _builder = builder;
- base ((str) => { _builder.append (str); }, xml_declaration);
+ base ((str) => {
+ _builder.append (str);
+ }, xml_declaration);
}
public MarkupWriter add_usemap (Charts.Chart chart) {
diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala
index 513913fb68..833fd5199d 100644
--- a/src/libvaladoc/html/htmlrenderer.vala
+++ b/src/libvaladoc/html/htmlrenderer.vala
@@ -70,7 +70,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
private void write_resolved_symbol_link (Api.Node symbol, string? given_label) {
if (symbol == _container || symbol == _owner) {
- writer.start_tag ("span", {"css", cssresolver.resolve (symbol)}).text (symbol.name).end_tag ("span");
+ writer.start_tag ("span", {"css", cssresolver.resolve (symbol)})
+ .text (symbol.name)
+ .end_tag ("span");
} else {
var label = (given_label == null || given_label == "") ? symbol.get_full_name () : given_label;
var url = get_url (symbol);
@@ -108,7 +110,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
write_taglets (
() => {
writer.start_tag ("p", {"class", "main_title"});
- writer.start_tag ("b").text ("Deprecated: ").end_tag ("b");
+ writer.start_tag ("b")
+ .text ("Deprecated: ")
+ .end_tag ("b");
},
() => {
writer.end_tag ("p");
@@ -158,7 +162,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
write_taglets (
() => {
- writer.start_tag ("h2", {"class", "main_title"}).text ("Parameters:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", "main_title"})
+ .text ("Parameters:")
+ .end_tag ("h2");
writer.start_tag ("table", {"class", "main_parameter_table"});
},
() => {
@@ -174,7 +180,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
}
writer.start_tag ("tr", unknown_parameter_css);
- writer.start_tag ("td", {"class", "main_parameter_table_name"}).text (param.parameter_name).end_tag ("td");
+ writer.start_tag ("td", {"class", "main_parameter_table_name"})
+ .text (param.parameter_name)
+ .end_tag ("td");
writer.start_tag ("td");
param.accept_children (this);
writer.end_tag ("td");
@@ -184,7 +192,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
taglets = element.find_taglets ((Api.Node) _container, typeof (Taglets.Return));
write_taglets (
() => {
- writer.start_tag ("h2", {"class", "main_title"}).text ("Returns:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", "main_title"})
+ .text ("Returns:")
+ .end_tag ("h2");
writer.start_tag ("table", {"class", "main_parameter_table"});
},
() => {
@@ -204,7 +214,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
taglets = element.find_taglets ((Api.Node) _container, typeof (Taglets.Throws));
write_taglets (
() => {
- writer.start_tag ("h2", {"class", "main_title"}).text ("Exceptions:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", "main_title"})
+ .text ("Exceptions:")
+ .end_tag ("h2");
writer.start_tag ("table", {"class", "main_parameter_table"});
},
() => {
@@ -215,7 +227,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
(taglet) => {
var exception = taglet as Taglets.Throws;
writer.start_tag ("tr");
- writer.start_tag ("td", {"class", "main_parameter_table_name"}).text (exception.error_domain_name).end_tag ("td");
+ writer.start_tag ("td", {"class", "main_parameter_table_name"})
+ .text (exception.error_domain_name)
+ .end_tag ("td");
writer.start_tag ("td");
exception.accept_children (this);
writer.end_tag ("td");
@@ -225,7 +239,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
taglets = element.find_taglets ((Api.Node) _container, typeof (Taglets.Since));
write_taglets (
() => {
- writer.start_tag ("h2", {"class", "main_title"}).text ("Since:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", "main_title"})
+ .text ("Since:")
+ .end_tag ("h2");
writer.start_tag ("p");
},
() => {
@@ -241,7 +257,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
taglets = element.find_taglets ((Api.Node) _container, typeof (Taglets.See));
write_taglets (
() => {
- writer.start_tag ("h2", {"class", "main_title"}).text ("See also:").end_tag ("h2");
+ writer.start_tag ("h2", {"class", "main_title"})
+ .text ("See also:")
+ .end_tag ("h2");
writer.start_tag ("p");
},
() => {
@@ -264,7 +282,8 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
public override void visit_embedded (Embedded element) {
var caption = element.caption;
- var absolute_path = Path.build_filename (settings.path, element.package.name, "img", Path.get_basename (element.url));
+ var absolute_path = Path.build_filename (settings.path, element.package.name, "img",
+ Path.get_basename (element.url));
var relative_path = Path.build_filename ("img", Path.get_basename (element.url));
copy_file (element.url, absolute_path);
@@ -402,7 +421,10 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
private void visit_notification_block (BlockContent element, string headline) {
writer.start_tag ("div", {"class", "main_notification_block"});
- writer.start_tag ("span", {"class", "main_block_headline"}).text (headline).end_tag ("span").text (" ");
+ writer.start_tag ("span", {"class", "main_block_headline"})
+ .text (headline)
+ .end_tag ("span")
+ .text (" ");
writer.start_tag ("div", {"class", "main_block_content"});
element.accept_children (this);
writer.end_tag ("div");
diff --git a/src/libvaladoc/importer/girdocumentationimporter.vala b/src/libvaladoc/importer/girdocumentationimporter.vala
index b2ee4788d7..73d7218428 100644
--- a/src/libvaladoc/importer/girdocumentationimporter.vala
+++ b/src/libvaladoc/importer/girdocumentationimporter.vala
@@ -31,7 +31,11 @@ using Gee;
public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
- public override string file_extension { get { return "gir"; } }
+ public override string file_extension {
+ get {
+ return "gir";
+ }
+ }
private MarkupTokenType current_token;
private MarkupSourceLocation begin;
@@ -54,14 +58,18 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
}
}
- public GirDocumentationImporter (Api.Tree tree, DocumentationParser parser, ModuleLoader modules, Settings settings, ErrorReporter reporter) {
+ public GirDocumentationImporter (Api.Tree tree, DocumentationParser parser,
+ ModuleLoader modules, Settings settings,
+ ErrorReporter reporter)
+ {
base (tree, modules, settings);
this.reporter = reporter;
this.parser = parser;
}
public override void process (string source_file) {
- this.file = new Api.SourceFile (new Api.Package (Path.get_basename (source_file), true, null), source_file, null, null);
+ this.file = new Api.SourceFile (new Api.Package (Path.get_basename (source_file), true, null),
+ source_file, null, null);
this.reader = new MarkupReader (source_file, reporter);
// xml prolog
@@ -94,7 +102,14 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
return param_names[length_pos];
}
- private void attach_comment (string cname, Api.GirSourceComment? comment, string[]? param_names = null, ImplicitParameterPos[]? destroy_notifies = null, ImplicitParameterPos[]? closures = null, ImplicitParameterPos[]? array_lengths = null, int array_length_ret = -1) {
+ private void attach_comment (string cname,
+ Api.GirSourceComment? comment,
+ string[]? param_names = null,
+ ImplicitParameterPos[]? destroy_notifies = null,
+ ImplicitParameterPos[]? closures = null,
+ ImplicitParameterPos[]? array_lengths = null,
+ int array_length_ret = -1)
+ {
if (comment == null) {
return ;
}
@@ -111,7 +126,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
continue ;
}
- param.implicit_destroy_cparameter_name = get_cparameter_name (param_names, pos.position);
+ param.implicit_destroy_cparameter_name
+ = get_cparameter_name (param_names, pos.position);
}
foreach (ImplicitParameterPos pos in closures) {
@@ -120,7 +136,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
continue ;
}
- param.implicit_closure_cparameter_name = get_cparameter_name (param_names, pos.position);
+ param.implicit_closure_cparameter_name
+ = get_cparameter_name (param_names, pos.position);
}
foreach (ImplicitParameterPos pos in array_lengths) {
@@ -129,11 +146,13 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
continue ;
}
- param.implicit_array_length_cparameter_name = get_cparameter_name (param_names, pos.position);
+ param.implicit_array_length_cparameter_name
+ = get_cparameter_name (param_names, pos.position);
}
if (node is Api.Callable) {
- ((Api.Callable) node).implicit_array_length_cparameter_name = get_cparameter_name (param_names, array_length_ret);
+ ((Api.Callable) node).implicit_array_length_cparameter_name
+ = get_cparameter_name (param_names, array_length_ret);
}
}
@@ -146,11 +165,13 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
}
private void warning (string message) {
- reporter.warning (this.file.relative_path, this.begin.line, this.begin.column, this.end.column, this.reader.get_line_content (this.begin.line), message);
+ reporter.warning (this.file.relative_path, this.begin.line, this.begin.column, this.end.column,
+ this.reader.get_line_content (this.begin.line), message);
}
private void error (string message) {
- reporter.error (this.file.relative_path, this.begin.line, this.begin.column, this.end.column, this.reader.get_line_content (this.begin.line), message);
+ reporter.error (this.file.relative_path, this.begin.line, this.begin.column, this.end.column,
+ this.reader.get_line_content (this.begin.line), message);
}
private void next () {
@@ -177,7 +198,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
private void parse_repository () {
start_element ("repository");
if (reader.get_attribute ("version") != GIR_VERSION) {
- error ("unsupported GIR version %s (supported: %s)".printf (reader.get_attribute ("version"), GIR_VERSION));
+ error ("unsupported GIR version %s (supported: %s)"
+ .printf (reader.get_attribute ("version"), GIR_VERSION));
return;
}
next ();
@@ -299,7 +321,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
Api.GirSourceComment? comment = null;
if (current_token == MarkupTokenType.TEXT) {
- comment = new Api.GirSourceComment (reader.content, file, begin.line, begin.column, end.line, end.column);
+ comment = new Api.GirSourceComment (reader.content, file, begin.line,
+ begin.column, end.line, end.column);
next ();
}
@@ -318,7 +341,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
Api.SourceComment? comment = null;
if (current_token == MarkupTokenType.TEXT) {
- comment = new Api.SourceComment (reader.content, file, begin.line, begin.column, end.line, end.column);
+ comment = new Api.SourceComment (reader.content, file, begin.line,
+ begin.column, end.line, end.column);
next ();
}
@@ -376,7 +400,9 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
end_element ("return-value");
}
- private void parse_parameter (out Api.SourceComment? comment, out string param_name, out int destroy_pos, out int closure_pos, out int array_length_pos) {
+ private void parse_parameter (out Api.SourceComment? comment, out string param_name,
+ out int destroy_pos,
+ out int closure_pos, out int array_length_pos) {
start_element ("parameter");
param_name = reader.get_attribute ("name");
array_length_pos = -1;
@@ -560,7 +586,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
private void parse_property () {
start_element ("property");
- string c_identifier = "%s:%s".printf (parent_c_identifier, reader.get_attribute ("name").replace ("-", "_"));
+ string c_identifier = "%s:%s".printf (parent_c_identifier, reader.get_attribute ("name")
+ .replace ("-", "_"));
next ();
Api.GirSourceComment? comment = parse_symbol_doc ();
@@ -595,11 +622,13 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
break;
case "virtual-method":
- c_identifier = "%s->%s".printf (this.parent_c_identifier, reader.get_attribute ("name").replace ("-", "_"));
+ c_identifier = "%s->%s".printf (this.parent_c_identifier, reader.get_attribute ("name")
+ .replace ("-", "_"));
break;
case "glib:signal":
- c_identifier = "%s::%s".printf (this.parent_c_identifier, reader.get_attribute ("name").replace ("-", "_"));
+ c_identifier = "%s::%s".printf (this.parent_c_identifier, reader.get_attribute ("name")
+ .replace ("-", "_"));
break;
default:
@@ -622,7 +651,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
parse_return_value (out return_comment, out array_length_ret);
if (return_comment != null) {
if (comment == null) {
- comment = new Api.GirSourceComment ("", file, begin.line, begin.column, end.line, end.column);
+ comment = new Api.GirSourceComment ("", file, begin.line, begin.column,
+ end.line, end.column);
}
comment.return_comment = return_comment;
}
@@ -640,7 +670,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
int closure_pos;
string? param_name;
- parse_parameter (out param_comment, out param_name, out destroy_pos, out closure_pos, out array_length_pos);
+ parse_parameter (out param_comment, out param_name, out destroy_pos,
+ out closure_pos, out array_length_pos);
param_names += param_name;
if (destroy_pos >= 0 && pcount != destroy_pos) {
@@ -657,7 +688,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
if (param_comment != null) {
if (comment == null) {
- comment = new Api.GirSourceComment ("", file, begin.line, begin.column, end.line, end.column);
+ comment = new Api.GirSourceComment ("", file, begin.line, begin.column,
+ end.line, end.column);
}
comment.add_parameter_content (param_name, param_comment);
@@ -666,7 +698,8 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
end_element ("parameters");
}
- attach_comment (c_identifier, comment, param_names, destroy_notifies, closures, array_lengths, array_length_ret);
+ attach_comment (c_identifier, comment, param_names, destroy_notifies, closures,
+ array_lengths, array_length_ret);
end_element (element_name);
}
diff --git a/src/libvaladoc/importer/valadocdocumentationimporter.vala b/src/libvaladoc/importer/valadocdocumentationimporter.vala
index b005217f78..e6025c96bf 100644
--- a/src/libvaladoc/importer/valadocdocumentationimporter.vala
+++ b/src/libvaladoc/importer/valadocdocumentationimporter.vala
@@ -42,7 +42,9 @@ public class Valadoc.Importer.ValadocDocumentationImporter : DocumentationImport
private ErrorReporter reporter;
- public ValadocDocumentationImporter (Api.Tree tree, DocumentationParser parser, ModuleLoader modules, Settings settings, ErrorReporter reporter) {
+ public ValadocDocumentationImporter (Api.Tree tree, DocumentationParser parser, ModuleLoader modules,
+ Settings settings, ErrorReporter reporter)
+ {
base (tree, modules, settings);
this.factory = new Content.ContentFactory (settings, this, modules);
this.reporter = reporter;
@@ -121,7 +123,9 @@ public class Valadoc.Importer.ValadocDocumentationImporter : DocumentationImport
REPLACE
}
- private void add_documentation (string _symbol_name, StringBuilder? comment, string filename, SourceLocation src_ref) {
+ private void add_documentation (string _symbol_name, StringBuilder? comment, string filename,
+ SourceLocation src_ref)
+ {
Api.Node? symbol = null;
InsertionMode insertion_mode;
diff --git a/src/libvaladoc/parser/manyrule.vala b/src/libvaladoc/parser/manyrule.vala
index be19b5ba41..093223ac95 100644
--- a/src/libvaladoc/parser/manyrule.vala
+++ b/src/libvaladoc/parser/manyrule.vala
@@ -46,7 +46,9 @@ internal class Valadoc.ManyRule : Rule {
return false;
}
- public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward) throws ParserError {
+ public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward)
+ throws ParserError
+ {
var state = parser.get_rule_state () as State;
if (state == null) {
state = new State ();
@@ -102,6 +104,9 @@ internal class Valadoc.ManyRule : Rule {
if (state == null) {
state = new State ();
}
- return "%-15s%-15s(started=%s;done_one=%s)".printf (name != null ? name : " ", "[many]", state.started.to_string (), state.done_one.to_string ());
+ return "%-15s%-15s(started=%s;done_one=%s)".printf (name != null ? name : " ",
+ "[many]",
+ state.started.to_string (),
+ state.done_one.to_string ());
}
}
diff --git a/src/libvaladoc/parser/oneofrule.vala b/src/libvaladoc/parser/oneofrule.vala
index 19e94190f9..946335233a 100644
--- a/src/libvaladoc/parser/oneofrule.vala
+++ b/src/libvaladoc/parser/oneofrule.vala
@@ -47,7 +47,9 @@ internal class Valadoc.OneOfRule : Rule {
return false;
}
- public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward) throws ParserError {
+ public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward)
+ throws ParserError
+ {
var state = parser.get_rule_state () as State;
if (state == null) {
state = new State ();
@@ -88,6 +90,9 @@ internal class Valadoc.OneOfRule : Rule {
if (state == null) {
state = new State ();
}
- return "%-15s%-15s(selected=%d/%d)".printf (name != null ? name : " ", "[one-of]", state.selected, _scheme.length);
+ return "%-15s%-15s(selected=%d/%d)".printf (name != null ? name : " ",
+ "[one-of]",
+ state.selected,
+ _scheme.length);
}
}
diff --git a/src/libvaladoc/parser/optionalrule.vala b/src/libvaladoc/parser/optionalrule.vala
index 693b581de5..6945afa38c 100644
--- a/src/libvaladoc/parser/optionalrule.vala
+++ b/src/libvaladoc/parser/optionalrule.vala
@@ -42,7 +42,9 @@ internal class Valadoc.OptionalRule : Rule {
return has_start_token (_scheme, token);
}
- public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward) throws ParserError {
+ public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward)
+ throws ParserError
+ {
var state = parser.get_rule_state () as State;
if (state == null) {
state = new State ();
@@ -79,6 +81,8 @@ internal class Valadoc.OptionalRule : Rule {
if (state == null) {
state = new State ();
}
- return "%-15s%-15s(started=%s)".printf (name != null ? name : " ", "[option]", state.started.to_string ());
+ return "%-15s%-15s(started=%s)".printf (name != null ? name : " ",
+ "[option]",
+ state.started.to_string ());
}
}
diff --git a/src/libvaladoc/parser/parser.vala b/src/libvaladoc/parser/parser.vala
index c4841c4996..bf3a598895 100644
--- a/src/libvaladoc/parser/parser.vala
+++ b/src/libvaladoc/parser/parser.vala
@@ -54,7 +54,9 @@ public class Valadoc.Parser : ParserCallback {
_root_rule = root_rule;
}
- public void parse (string content, string filename, int first_line, int first_column) throws ParserError {
+ public void parse (string content, string filename, int first_line, int first_column)
+ throws ParserError
+ {
_filename = filename;
_first_line = first_line;
_first_column = first_column;
@@ -161,7 +163,8 @@ public class Valadoc.Parser : ParserCallback {
#if HARD_DEBUG
Rule? parent_rule = peek_rule ();
if (parent_rule != null) {
- debug ("Reduced to %2d: %s", rule_stack.size - 1, parent_rule.to_string (peek_state ()));
+ debug ("Reduced to %2d: %s", rule_stack.size - 1,
+ parent_rule.to_string (peek_state ()));
}
#endif
}
@@ -172,7 +175,8 @@ public class Valadoc.Parser : ParserCallback {
Object? state = peek_state (offset);
while (parent_rule != null) {
#if VERY_HARD_DEBUG
- debug ("WouldAccept - Offset %d; Index %d: %s", offset, rule_stack.size + offset, parent_rule.to_string (state));
+ debug ("WouldAccept - Offset %d; Index %d: %s", offset,
+ rule_stack.size + offset, parent_rule.to_string (state));
#endif
if (parent_rule.would_accept_token (token, state)) {
#if VERY_HARD_DEBUG
@@ -202,7 +206,8 @@ public class Valadoc.Parser : ParserCallback {
Object? state = peek_state (offset);
while (parent_rule != null) {
#if VERY_HARD_DEBUG
- debug ("WouldReduce - Offset %d; Index %d: %s", offset, rule_stack.size + offset, parent_rule.to_string (state));
+ debug ("WouldReduce - Offset %d; Index %d: %s", offset,
+ rule_stack.size + offset, parent_rule.to_string (state));
#endif
if (!parent_rule.would_reduce (token, state)) {
break;
diff --git a/src/libvaladoc/parser/rule.vala b/src/libvaladoc/parser/rule.vala
index 50ff6e3935..7ecbc35637 100644
--- a/src/libvaladoc/parser/rule.vala
+++ b/src/libvaladoc/parser/rule.vala
@@ -117,15 +117,19 @@ public abstract class Valadoc.Rule : Object {
return false;
}
- protected bool try_to_apply (Object? scheme_element, Token token, ParserCallback parser, out bool handled) throws ParserError {
+ protected bool try_to_apply (Object? scheme_element, Token token, ParserCallback parser,
+ out bool handled) throws ParserError
+ {
#if VERY_HARD_DEBUG
{
TokenType? scheme_token = scheme_element as TokenType;
Rule? scheme_rule = scheme_element as Rule;
if (scheme_token != null) {
- message ("TryToApply: token='%s'; scheme_token='%s'", token.to_string (), scheme_token.to_string ());
+ message ("TryToApply: token='%s'; scheme_token='%s'", token.to_string (),
+ scheme_token.to_string ());
} else if (scheme_rule != null) {
- message ("TryToApply: token='%s'; scheme_rule='%s'", token.to_string (), scheme_rule.to_string (parser.get_rule_state ()));
+ message ("TryToApply: token='%s'; scheme_rule='%s'", token.to_string (),
+ scheme_rule.to_string (parser.get_rule_state ()));
} else {
assert (scheme_element != null);
}
diff --git a/src/libvaladoc/parser/sequencerule.vala b/src/libvaladoc/parser/sequencerule.vala
index 268d50a933..f14cf070d9 100644
--- a/src/libvaladoc/parser/sequencerule.vala
+++ b/src/libvaladoc/parser/sequencerule.vala
@@ -67,7 +67,9 @@ internal class Valadoc.SequenceRule : Rule {
return true;
}
- public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward) throws ParserError {
+ public override bool accept_token (Token token, ParserCallback parser,
+ Rule.Forward forward) throws ParserError
+ {
var state = parser.get_rule_state () as State;
if (state == null) {
state = new State ();
diff --git a/src/libvaladoc/parser/stubrule.vala b/src/libvaladoc/parser/stubrule.vala
index 92dfe369f2..0f6f979300 100644
--- a/src/libvaladoc/parser/stubrule.vala
+++ b/src/libvaladoc/parser/stubrule.vala
@@ -42,7 +42,9 @@ public class Valadoc.StubRule : Rule {
return _rule.starts_with_token (token);
}
- public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward) throws ParserError {
+ public override bool accept_token (Token token, ParserCallback parser, Rule.Forward forward)
+ throws ParserError
+ {
return _rule.accept_token (token, parser, forward);
}
diff --git a/src/libvaladoc/taglets/tagletdeprecated.vala b/src/libvaladoc/taglets/tagletdeprecated.vala
index 49636cafb2..16e71afa70 100644
--- a/src/libvaladoc/taglets/tagletdeprecated.vala
+++ b/src/libvaladoc/taglets/tagletdeprecated.vala
@@ -29,9 +29,12 @@ public class Valadoc.Taglets.Deprecated : InlineContent, Taglet, Block {
return run_rule;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
base.check (api_root, container, file_path, reporter, settings);
- reporter.simple_warning ("%s: %s: @deprecated: warning: @deprecated is deprecated. Use [Deprecated]", file_path, container.get_full_name ());
+ reporter.simple_warning ("%s: %s: @deprecated: warning: @deprecated is deprecated. Use [Deprecated]",
+ file_path, container.get_full_name ());
}
public override void accept (ContentVisitor visitor) {
diff --git a/src/libvaladoc/taglets/tagletinheritdoc.vala b/src/libvaladoc/taglets/tagletinheritdoc.vala
index caaa6659a7..54c90d7013 100644
--- a/src/libvaladoc/taglets/tagletinheritdoc.vala
+++ b/src/libvaladoc/taglets/tagletinheritdoc.vala
@@ -56,7 +56,9 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
return null;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// TODO Check that the container is an override of an abstract symbol
// Also retrieve that abstract symbol _inherited
@@ -124,7 +126,9 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
return null;
}
- internal void transform (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ internal void transform (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
ContentElement separator = this;
Run right_run = null;
Run left_run = null;
@@ -147,7 +151,8 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
}
if (separator is Paragraph == false || separator.parent is Comment == false) {
- reporter.simple_error ("%s: %s: @inheritDoc: error: Parent documentation can't be copied to this location.", file_path, container.get_full_name ());
+ reporter.simple_error ("%s: %s: @inheritDoc: error: Parent documentation can't be copied to this location.",
+ file_path, container.get_full_name ());
return ;
}
diff --git a/src/libvaladoc/taglets/tagletlink.vala b/src/libvaladoc/taglets/tagletlink.vala
index 39e4948b5e..84bbbeff57 100644
--- a/src/libvaladoc/taglets/tagletlink.vala
+++ b/src/libvaladoc/taglets/tagletlink.vala
@@ -51,7 +51,8 @@ public class Valadoc.Taglets.Link : InlineTaglet {
});
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings) {
if (symbol_name.has_prefix ("c::")) {
_symbol_name = _symbol_name.substring (3);
_symbol = api_root.search_symbol_cstr (container, symbol_name);
@@ -73,7 +74,8 @@ public class Valadoc.Taglets.Link : InlineTaglet {
if (_symbol == null && symbol_name != "main") {
string node_segment = (container is Api.Package)? "" : container.get_full_name () + ": ";
- reporter.simple_warning ("%s: %s@link: warning: %s does not exist", file_path, node_segment, symbol_name);
+ reporter.simple_warning ("%s: %s@link: warning: %s does not exist",
+ file_path, node_segment, symbol_name);
}
base.check (api_root, container, file_path, reporter, settings);
diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala
index 277d9b6aa3..1fa30072a2 100644
--- a/src/libvaladoc/taglets/tagletparam.vala
+++ b/src/libvaladoc/taglets/tagletparam.vala
@@ -40,7 +40,9 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
});
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// Check for the existence of such a parameter
unowned string? implicit_return_array_length = null;
bool is_implicit = false;
@@ -49,7 +51,8 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
if (container is Api.Callable) {
implicit_return_array_length = ((Api.Callable) container).implicit_array_length_cparameter_name;
} else {
- reporter.simple_warning ("%s: %s: @param: warning: @param used outside method/delegate/signal context", file_path, container.get_full_name ());
+ reporter.simple_warning ("%s: %s: @param: warning: @param used outside method/delegate/signal context",
+ file_path, container.get_full_name ());
base.check (api_root, container, file_path, reporter, settings);
return ;
}
@@ -65,7 +68,9 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
}
}
} else {
- Gee.List<Api.Node> params = container.get_children_by_types ({Api.NodeType.FORMAL_PARAMETER, Api.NodeType.TYPE_PARAMETER}, false);
+ Gee.List<Api.Node> params = container.get_children_by_types ({Api.NodeType.FORMAL_PARAMETER,
+ Api.NodeType.TYPE_PARAMETER},
+ false);
int pos = 0;
foreach (Api.Node param in params) {
@@ -76,7 +81,10 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
}
Api.FormalParameter formalparam = param as Api.FormalParameter;
- if (formalparam != null && (formalparam.implicit_array_length_cparameter_name == parameter_name || formalparam.implicit_closure_cparameter_name == parameter_name || formalparam.implicit_destroy_cparameter_name == parameter_name)) {
+ if (formalparam != null && (formalparam.implicit_array_length_cparameter_name == parameter_name
+ || formalparam.implicit_closure_cparameter_name == parameter_name
+ || formalparam.implicit_destroy_cparameter_name == parameter_name))
+ {
is_implicit = true;
break;
}
@@ -84,17 +92,22 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
pos++;
}
- if (this.parameter == null && (parameter_name == "error" && container.has_children ({Api.NodeType.ERROR_DOMAIN, Api.NodeType.CLASS})
- || parameter_name == implicit_return_array_length)) {
+ if (this.parameter == null
+ && (parameter_name == "error"
+ && container.has_children ({Api.NodeType.ERROR_DOMAIN, Api.NodeType.CLASS})
+ || parameter_name == implicit_return_array_length))
+ {
is_implicit = true;
}
}
if (this.parameter == null) {
if (is_implicit) {
- reporter.simple_note ("%s: %s: @param: warning: Implicit parameter `%s' exposed in documentation", file_path, container.get_full_name (), parameter_name);
+ reporter.simple_note ("%s: %s: @param: warning: Implicit parameter `%s' exposed in documentation",
+ file_path, container.get_full_name (), parameter_name);
} else {
- reporter.simple_warning ("%s: %s: @param: warning: Unknown parameter `%s'", file_path, container.get_full_name (), parameter_name);
+ reporter.simple_warning ("%s: %s: @param: warning: Unknown parameter `%s'",
+ file_path, container.get_full_name (), parameter_name);
}
}
diff --git a/src/libvaladoc/taglets/tagletreturn.vala b/src/libvaladoc/taglets/tagletreturn.vala
index d447e6eb5d..71b583694c 100644
--- a/src/libvaladoc/taglets/tagletreturn.vala
+++ b/src/libvaladoc/taglets/tagletreturn.vala
@@ -30,7 +30,8 @@ public class Valadoc.Taglets.Return : InlineContent, Taglet, Block {
return run_rule;
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings) {
Api.TypeReference? type_ref = null;
bool creation_method = false;
@@ -40,11 +41,13 @@ public class Valadoc.Taglets.Return : InlineContent, Taglet, Block {
} else if (container is Api.Callable) {
type_ref = ((Api.Callable) container).return_type;
} else {
- reporter.simple_warning ("%s: %s: @return: warning: @return used outside method/delegate/signal context", file_path, container.get_full_name ());
+ reporter.simple_warning ("%s: %s: @return: warning: @return used outside method/delegate/signal context",
+ file_path, container.get_full_name ());
}
if (type_ref != null && type_ref.data_type == null && !creation_method) {
- reporter.simple_warning ("%s: %s: @return: warning: Return description declared for void function", file_path, container.get_full_name ());
+ reporter.simple_warning ("%s: %s: @return: warning: Return description declared for void function",
+ file_path, container.get_full_name ());
}
base.check (api_root, container, file_path, reporter, settings);
diff --git a/src/libvaladoc/taglets/tagletsee.vala b/src/libvaladoc/taglets/tagletsee.vala
index 2d019988fa..7ac5666cee 100644
--- a/src/libvaladoc/taglets/tagletsee.vala
+++ b/src/libvaladoc/taglets/tagletsee.vala
@@ -39,7 +39,8 @@ public class Valadoc.Taglets.See : ContentElement, Taglet, Block {
});
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings) {
if (symbol_name.has_prefix ("c::")) {
symbol_name = symbol_name.substring (3);
symbol = api_root.search_symbol_cstr (container, symbol_name);
@@ -52,7 +53,8 @@ public class Valadoc.Taglets.See : ContentElement, Taglet, Block {
if (symbol == null) {
// TODO use ContentElement's source reference
- reporter.simple_warning ("%s: %s: @see: warning: %s does not exist", file_path, container.get_full_name (), symbol_name);
+ reporter.simple_warning ("%s: %s: @see: warning: %s does not exist",
+ file_path, container.get_full_name (), symbol_name);
}
}
diff --git a/src/libvaladoc/taglets/tagletsince.vala b/src/libvaladoc/taglets/tagletsince.vala
index 10b87b93b3..fccc063ef3 100644
--- a/src/libvaladoc/taglets/tagletsince.vala
+++ b/src/libvaladoc/taglets/tagletsince.vala
@@ -38,7 +38,9 @@ public class Valadoc.Taglets.Since : ContentElement, Taglet, Block {
});
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
}
public override void accept (ContentVisitor visitor) {
diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala
index 2423287107..daacd73336 100644
--- a/src/libvaladoc/taglets/tagletthrows.vala
+++ b/src/libvaladoc/taglets/tagletthrows.vala
@@ -42,10 +42,13 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block {
});
}
- public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ public override void check (Api.Tree api_root, Api.Node container, string file_path,
+ ErrorReporter reporter, Settings settings)
+ {
// context check:
if (container is Api.Method == false && container is Api.Delegate == false) {
- reporter.simple_warning ("%s: %s: @throws: warning: @throws used outside method/delegate context", file_path, container.get_full_name ());
+ reporter.simple_warning ("%s: %s: @throws: warning: @throws used outside method/delegate context",
+ file_path, container.get_full_name ());
base.check (api_root, container, file_path, reporter, settings);
return ;
}
@@ -55,24 +58,32 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block {
error_domain = api_root.search_symbol_str (container, error_domain_name);
if (error_domain == null) {
// TODO use ContentElement's source reference
- reporter.simple_error ("%s: %s: @throws: error: %s does not exist", file_path, container.get_full_name (), error_domain_name);
+ reporter.simple_error ("%s: %s: @throws: error: %s does not exist",
+ file_path, container.get_full_name (), error_domain_name);
base.check (api_root, container, file_path, reporter, settings);
return ;
}
// Check if the method is allowed to throw the given type or error code:
- Gee.List<Api.Node> exceptions = container.get_children_by_types ({Api.NodeType.ERROR_DOMAIN, Api.NodeType.CLASS}, false);
- Api.Item expected_error_domain = (error_domain is Api.ErrorCode)? error_domain.parent : error_domain;
+ Gee.List<Api.Node> exceptions = container.get_children_by_types ({Api.NodeType.ERROR_DOMAIN,
+ Api.NodeType.CLASS},
+ false);
+ Api.Item expected_error_domain = (error_domain is Api.ErrorCode)
+ ? error_domain.parent
+ : error_domain;
bool report_warning = true;
foreach (Api.Node exception in exceptions) {
- if (exception == expected_error_domain || (exception is Api.Class && expected_error_domain is Api.ErrorDomain)) {
+ if (exception == expected_error_domain
+ || (exception is Api.Class && expected_error_domain is Api.ErrorDomain))
+ {
report_warning = false;
break;
}
}
if (report_warning) {
- reporter.simple_warning ("%s: %s: @throws: warning: %s does not exist in exception list", file_path, container.get_full_name (), error_domain_name);
+ reporter.simple_warning ("%s: %s: @throws: warning: %s does not exist in exception list",
+ file_path, container.get_full_name (), error_domain_name);
}
base.check (api_root, container, file_path, reporter, settings);
|
ba475c843b6e0af795c00b77c75f49689dc0a999
|
arquillian$arquillian-graphene
|
ARQGRA-84: added support for JQuery selectors
Original vision to support only Sizzle selectors was not working with
HTMLUnit driver therefore added JQyery selectors 1.2.6.
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/.gitignore b/.gitignore
index b6d4b94e1..0e7054f40 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,4 @@ test-output
.classpath
.settings
.project
+chromedriver.log
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/JQuerySelectorsPageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/JQuerySelectorsPageExtensionTestCase.java
new file mode 100644
index 000000000..f3172b4e0
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/JQuerySelectorsPageExtensionTestCase.java
@@ -0,0 +1,178 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.arquillian.graphene.ftest.page.extension;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.net.URL;
+import java.util.List;
+
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.enricher.findby.ByJQuery;
+import org.jboss.arquillian.graphene.spi.annotations.FindBy;
+import org.jboss.arquillian.junit.Arquillian;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.NoSuchElementException;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebDriverException;
+import org.openqa.selenium.WebElement;
+
+/**
+ * @author <a href="mailto:[email protected]">Juraj Huska</a>
+ */
+@RunWith(Arquillian.class)
+public class JQuerySelectorsPageExtensionTestCase {
+
+ @FindBy(jquery = ":header")
+ private WebElement webElementByJQuery;
+
+ @FindBy(jquery = ":header")
+ private List<WebElement> listOfWebElementsByJQuery;
+
+ @FindBy(jquery = "div:eq(1)")
+ private JQuerySelectorTestPageFragment jquerySelectorTestPageFragment;
+
+ @FindBy(jquery = "div:eq(1)")
+ private List<JQuerySelectorTestPageFragment> listOfJQueryPageFragments;
+
+ @Drone
+ private WebDriver browser;
+
+ private static String EXPECTED_JQUERY_TEXT_1 = "Hello jquery selectors!";
+ private static String EXPECTED_JQUERY_TEXT_2 = "Nested div with foo class.";
+ private static String EXPECTED_NO_SUCH_EL_EX_MSG = "Cannot locate elements using";
+ private static String EXPECTED_WRONG_SELECTOR_MSG = "Check out whether it is correct!";
+
+ public void loadPage() {
+ URL page = this.getClass().getClassLoader()
+ .getResource("org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html");
+ browser.get(page.toString());
+ }
+
+ @Test
+ public void testFindByWrongSelector() {
+ loadPage();
+
+ @SuppressWarnings("unused")
+ WebElement element = null;
+
+ try {
+ element = browser.findElement(ByJQuery.jquerySelector(":notExistingSelector"));
+ } catch (WebDriverException ex) {
+ // desired state
+ assertTrue("The exception thrown after locating element by non existing selector is wrong!", ex.getMessage()
+ .contains(EXPECTED_WRONG_SELECTOR_MSG));
+ return;
+ }
+
+ fail("There should be webdriver exception thrown when locating element by wrong selector!");
+ }
+
+ @Test
+ public void testFindNonExistingElement() {
+ loadPage();
+
+ try {
+ @SuppressWarnings("unused")
+ WebElement nonExistingElement = browser.findElement(ByJQuery.jquerySelector(":contains('non existing string')"));
+ } catch (NoSuchElementException ex) {
+ // this is desired state
+ assertTrue("Error message of NoSuchElementException is wrong!", ex.getMessage()
+ .contains(EXPECTED_NO_SUCH_EL_EX_MSG));
+ return;
+ }
+
+ fail("There was not thrown NoSuchElementException when trying to locate non existed element!");
+ }
+
+ @Test
+ public void testFindingWebElementFromAnotherWebElement() {
+ loadPage();
+
+ WebElement root = browser.findElement(ByJQuery.jquerySelector("#root:visible"));
+
+ WebElement div = root.findElement(ByJQuery.jquerySelector(".foo:visible"));
+
+ assertNotNull("The div element should be found!", div);
+ assertEquals("The element was not referenced from parent WebElement correctly!", EXPECTED_JQUERY_TEXT_2, div.getText());
+ }
+
+ @Test
+ public void testJQuerySelectorCallingFindByDirectly() {
+ loadPage();
+
+ ByJQuery headerBy = new ByJQuery(":header");
+ WebElement headerElement = browser.findElement(headerBy);
+
+ assertNotNull(headerElement);
+ assertEquals("h1", headerElement.getTagName());
+ }
+
+ @Test
+ public void testFindByOnWebElement() {
+ loadPage();
+
+ assertNotNull(webElementByJQuery);
+ assertEquals("h1", webElementByJQuery.getTagName());
+ }
+
+ @Test
+ public void testFindByOnListOfWebElement() {
+ loadPage();
+
+ assertNotNull(listOfWebElementsByJQuery);
+ assertEquals("h1", listOfWebElementsByJQuery.get(0).getTagName());
+ }
+
+ @Test
+ public void testFindByOnPageFragment() {
+ loadPage();
+
+ assertNotNull(jquerySelectorTestPageFragment);
+ assertEquals(EXPECTED_JQUERY_TEXT_1, jquerySelectorTestPageFragment.getJQueryLocator().getText());
+ }
+
+ @Test
+ public void testFindByOnListOfPageFragments() {
+ loadPage();
+
+ assertNotNull(listOfJQueryPageFragments);
+ assertEquals(EXPECTED_JQUERY_TEXT_1, listOfJQueryPageFragments.get(0).getJQueryLocator().getText());
+ }
+
+ /* *************
+ * Page Fragment
+ */
+ public class JQuerySelectorTestPageFragment {
+
+ @FindBy(jquery = "div:contains('jquery selectors')")
+ private WebElement jqueryLocator;
+
+ public WebElement getJQueryLocator() {
+ return jqueryLocator;
+ }
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/SizzleJSPageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/SizzleJSPageExtensionTestCase.java
deleted file mode 100644
index bb84963c8..000000000
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/SizzleJSPageExtensionTestCase.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.arquillian.graphene.ftest.page.extension;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.net.URL;
-import java.util.List;
-
-import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.enricher.annotation.ByJQuery;
-import org.jboss.arquillian.graphene.spi.annotations.FindBy;
-import org.jboss.arquillian.junit.Arquillian;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-
-/**
- * @author <a href="mailto:[email protected]">Juraj Huska</a>
- */
-@RunWith(Arquillian.class)
-public class SizzleJSPageExtensionTestCase {
-
- @FindBy(jquery = ":header")
- private WebElement webElementBySizzle;
-
- @FindBy(jquery = ":header")
- private List<WebElement> listOfWebElementsBySizzle;
-
- @FindBy(jquery = "div:first")
- private SizzleTestPageFragment sizzleTestPageFragment;
-
- @FindBy(jquery = "div:first")
- private List<SizzleTestPageFragment> listOfSizzlePageFragments;
-
- @Drone
- private WebDriver browser;
-
- private static String EXPECTED_SIZZLE_TEXT = "Hello sizzle locators!";
-
- public void loadPage() {
- URL page = this.getClass().getClassLoader()
- .getResource("org/jboss/arquillian/graphene/ftest/page/extension/sample.html");
- browser.get(page.toString());
- }
-
- @Test
- public void testSizzleJSPageExtensionInstalled() {
- loadPage();
-
- ByJQuery htmlBy = new ByJQuery("html");
- WebElement htmlElement = browser.findElement(htmlBy);
-
- assertNotNull(htmlElement);
- assertEquals("html", htmlElement.getTagName());
- }
-
- @Test
- public void testFindByOnWebElementSizzleLocator() {
- loadPage();
-
- assertNotNull(webElementBySizzle);
- assertEquals("h1", webElementBySizzle.getTagName());
- }
-
- @Test
- public void testFindByOnListOfWebElementSizzleLocator() {
- loadPage();
-
- assertNotNull(listOfWebElementsBySizzle);
- assertEquals("h1", listOfWebElementsBySizzle.get(0).getTagName());
- }
-
- @Test
- public void testFindByOnPageFragmentBySizzleLocator() {
- loadPage();
-
- assertNotNull(sizzleTestPageFragment);
- assertEquals(EXPECTED_SIZZLE_TEXT, sizzleTestPageFragment.getSizzleLocator().getText());
- }
-
- @Test
- public void testFindByOnListOfPageFragments() {
- loadPage();
-
- assertNotNull(listOfSizzlePageFragments);
- assertEquals(EXPECTED_SIZZLE_TEXT, listOfSizzlePageFragments.get(0).getSizzleLocator().getText());
- }
-
- /* *************
- * Page Fragment
- */
- public class SizzleTestPageFragment {
-
- @FindBy(jquery = "div:contains(sizzle locators)")
- private WebElement sizzleLocator;
-
- public WebElement getSizzleLocator() {
- return sizzleLocator;
- }
- }
-}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html
index febc81c19..4ca19adfe 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html
@@ -4,8 +4,5 @@
</head>
<body>
<h1>Hello World!</h1>
- <div>
- <div>Hello sizzle locators!</div>
- </div>
</body>
</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html
new file mode 100644
index 000000000..91a76bf28
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html>
+<head>
+</head>
+<body>
+ <h1>Hello World!</h1>
+ <div class="foo">Outer div with foo class.</div>
+ <div id="root">
+ <div>Hello jquery selectors!</div>
+ <div class="foo">Nested div with foo class.</div>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
index 513d274d2..353cc0354 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
@@ -29,8 +29,8 @@
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.ServiceLoader;
-import org.jboss.arquillian.graphene.enricher.annotation.FindByUtilities;
import org.jboss.arquillian.graphene.enricher.exception.PageFragmentInitializationException;
+import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
import org.jboss.arquillian.graphene.spi.annotations.Root;
import org.openqa.selenium.By;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
index b6f3b1ac0..cb608f712 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
@@ -24,8 +24,8 @@
import java.lang.reflect.Field;
import java.util.List;
-import org.jboss.arquillian.graphene.enricher.annotation.FindByUtilities;
import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
+import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/ByJQuery.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
similarity index 51%
rename from graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/ByJQuery.java
rename to graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
index e0bd43568..9dfbce493 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/ByJQuery.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
@@ -19,16 +19,21 @@
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
-package org.jboss.arquillian.graphene.enricher.annotation;
+package org.jboss.arquillian.graphene.enricher.findby;
import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
import org.jboss.arquillian.graphene.page.extension.SizzleJSPageExtension;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
/**
@@ -45,18 +50,61 @@ public ByJQuery(String jquerySelector) {
}
public static ByJQuery jquerySelector(String selector) {
- if(selector == null) {
- throw new IllegalArgumentException("Can not find elements when jquerySelector is null!");
+ if (selector == null) {
+ throw new IllegalArgumentException("Cannot find elements when jquerySelector is null!");
}
return new ByJQuery(selector);
}
+ @Override
+ public String toString() {
+ return "By.jquerySelector " + jquerySelector;
+ }
+
@SuppressWarnings("unchecked")
@Override
public List<WebElement> findElements(SearchContext context) {
+ installSizzleJSExtension();
+
+ List<WebElement> elements = null;
+
+ try {
+ // the element is referenced from parent web element
+ if (context instanceof WebElement) {
+ elements = (List<WebElement>) executor.executeScript(
+ "return $(\"" + jquerySelector + "\", arguments[0]).get()", (WebElement) context);
+ } else if (context instanceof WebDriver) { // element is not referenced from parent
+ elements = (List<WebElement>) executor.executeScript("return $(\"" + jquerySelector + "\").get()");
+ } else { // other unknown case
+ Logger
+ .getLogger(this.getClass().getName())
+ .log(
+ Level.SEVERE,
+ "Cannot determine the SearchContext you are passing to the findBy/s method! It is not instance of WebDriver nor WebElement! It is: "
+ + context);
+ }
+ } catch (Exception ex) {
+ throw new WebDriverException("Can not locate element using selector " + jquerySelector
+ + " Check out whether it is correct!", ex);
+ }
+
+ if (elements == null || elements.size() == 0) {
+ throw new NoSuchElementException("Cannot locate elements using: " + jquerySelector);
+ }
+
+ return elements;
+ }
+
+ @Override
+ public WebElement findElement(SearchContext context) {
+ installSizzleJSExtension();
+
+ return this.findElements(context).get(0);
+ }
+
+ private void installSizzleJSExtension() {
SizzleJSPageExtension pageExtension = new SizzleJSPageExtension();
GraphenePageExtensionsContext.getRegistryProxy().register(pageExtension);
GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtension.getName()).install();
-
- return (List<WebElement>) executor.executeScript("return window.Sizzle('" + jquerySelector + "')");
- }}
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/FindByUtilities.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/FindByUtilities.java
rename to graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
index 299c45932..916cd28a4 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/FindByUtilities.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
@@ -19,7 +19,7 @@
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
-package org.jboss.arquillian.graphene.enricher.annotation;
+package org.jboss.arquillian.graphene.enricher.findby;
import java.lang.reflect.Field;
import java.util.List;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java
index f06ab2fca..795c4beb7 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java
@@ -39,12 +39,12 @@ public String getName() {
@Override
public JavaScript getExtensionScript() {
- return JavaScript.fromResource("com/sizzlejs/sizzle.js");
+ return JavaScript.fromResource("com/jquery/jquery-1.2.6.min.js");
}
@Override
public JavaScript getInstallationDetectionScript() {
- return JavaScript.fromString("return ((typeof window.Sizzle != 'undefined') && (window.Sizzle() != null))");
+ return JavaScript.fromString("return ((typeof $ != 'undefined') && ($() != null))");
}
@Override
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/jquery/jquery-1.2.6.min.js b/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/jquery/jquery-1.2.6.min.js
new file mode 100644
index 000000000..82b98e1d7
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/jquery/jquery-1.2.6.min.js
@@ -0,0 +1,32 @@
+/*
+ * jQuery 1.2.6 - New Wave Javascript
+ *
+ * Copyright (c) 2008 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
+ * $Rev: 5685 $
+ */
+(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
+return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
+return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
+selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
+return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
+this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
+return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
+jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&©&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
+script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
+for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
+for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
+jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
+ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
+while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
+while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
+for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
+jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
+xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
+jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
+for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
+s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
+e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/sizzlejs/sizzle.js b/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/sizzlejs/sizzle.js
deleted file mode 100644
index 3e3caed4b..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/sizzlejs/sizzle.js
+++ /dev/null
@@ -1,1710 +0,0 @@
-/*!
- * Sizzle CSS Selector Engine
- * Copyright 2012 jQuery Foundation and other contributors
- * Released under the MIT license
- * http://sizzlejs.com/
- */
-(function( window, undefined ) {
-
-var cachedruns,
- assertGetIdNotName,
- Expr,
- getText,
- isXML,
- contains,
- compile,
- sortOrder,
- hasDuplicate,
- outermostContext,
-
- strundefined = "undefined",
-
- // Used in sorting
- MAX_NEGATIVE = 1 << 31,
- baseHasDuplicate = true,
-
- expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
-
- Token = String,
- document = window.document,
- docElem = document.documentElement,
- dirruns = 0,
- done = 0,
- pop = [].pop,
- push = [].push,
- slice = [].slice,
- // Use a stripped-down indexOf if a native one is unavailable
- indexOf = [].indexOf || function( elem ) {
- var i = 0,
- len = this.length;
- for ( ; i < len; i++ ) {
- if ( this[i] === elem ) {
- return i;
- }
- }
- return -1;
- },
-
- // Augment a function for special use by Sizzle
- markFunction = function( fn, value ) {
- fn[ expando ] = value == null || value;
- return fn;
- },
-
- createCache = function() {
- var cache = {},
- keys = [];
-
- return markFunction(function( key, value ) {
- // Only keep the most recent entries
- if ( keys.push( key ) > Expr.cacheLength ) {
- delete cache[ keys.shift() ];
- }
-
- // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
- return (cache[ key + " " ] = value);
- }, cache );
- },
-
- classCache = createCache(),
- tokenCache = createCache(),
- compilerCache = createCache(),
-
- // Regex
-
- // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
- whitespace = "[\\x20\\t\\r\\n\\f]",
- // http://www.w3.org/TR/css3-syntax/#characters
- characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
-
- // Loosely modeled on CSS identifier characters
- // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
- // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = characterEncoding.replace( "w", "w#" ),
-
- // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
- operators = "([*^$|!~]?=)",
- attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
- "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
-
- // Prefer arguments not in parens/brackets,
- // then attribute selectors and non-pseudos (denoted by :),
- // then anything else
- // These preferences are here to reduce the number of selectors
- // needing tokenize in the PSEUDO preFilter
- pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
-
- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
- rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
- rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
- rpseudo = new RegExp( pseudos ),
-
- // Easily-parseable/retrievable ID or TAG or CLASS selectors
- rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
-
- rsibling = /[\x20\t\r\n\f]*[+~]/,
-
- rheader = /h\d/i,
- rinputs = /input|select|textarea|button/i,
-
- rbackslash = /\\(?!\\)/g,
-
- matchExpr = {
- "ID": new RegExp( "^#(" + characterEncoding + ")" ),
- "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
- "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
- "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
- "ATTR": new RegExp( "^" + attributes ),
- "PSEUDO": new RegExp( "^" + pseudos ),
- "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
- // For use in libraries implementing .is()
- // We use this for POS matching in `select`
- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
- whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
- },
-
- // Support
-
- // Used for testing something on an element
- assert = function( fn ) {
- var div = document.createElement("div");
-
- try {
- return fn( div );
- } catch (e) {
- return false;
- } finally {
- // release memory in IE
- div = null;
- }
- },
-
- // Check if getElementsByTagName("*") returns only elements
- assertTagNameNoComments = assert(function( div ) {
- div.appendChild( document.createComment("") );
- return !div.getElementsByTagName("*").length;
- }),
-
- // Check if getAttribute returns normalized href attributes
- assertHrefNotNormalized = assert(function( div ) {
- div.innerHTML = "<a href='#'></a>";
- return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
- div.firstChild.getAttribute("href") === "#";
- }),
-
- // Check if attributes should be retrieved by attribute nodes
- assertAttributes = assert(function( div ) {
- div.innerHTML = "<select></select>";
- var type = typeof div.lastChild.getAttribute("multiple");
- // IE8 returns a string for some attributes even when not present
- return type !== "boolean" && type !== "string";
- }),
-
- // Check if getElementsByClassName can be trusted
- assertUsableClassName = assert(function( div ) {
- // Opera can't find a second classname (in 9.6)
- div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
- if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
- return false;
- }
-
- // Safari 3.2 caches class attributes and doesn't catch changes
- div.lastChild.className = "e";
- return div.getElementsByClassName("e").length === 2;
- }),
-
- // Check if getElementById returns elements by name
- // Check if getElementsByName privileges form controls or returns elements by ID
- assertUsableName = assert(function( div ) {
- // Inject content
- div.id = expando + 0;
- div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
- docElem.insertBefore( div, docElem.firstChild );
-
- // Test
- var pass = document.getElementsByName &&
- // buggy browsers will return fewer than the correct 2
- document.getElementsByName( expando ).length === 2 +
- // buggy browsers will return more than the correct 0
- document.getElementsByName( expando + 0 ).length;
- assertGetIdNotName = !document.getElementById( expando );
-
- // Cleanup
- docElem.removeChild( div );
-
- return pass;
- });
-
-// If slice is not available, provide a backup
-try {
- slice.call( docElem.childNodes, 0 )[0].nodeType;
-} catch ( e ) {
- slice = function( i ) {
- var elem,
- results = [];
- for ( ; (elem = this[i]); i++ ) {
- results.push( elem );
- }
- return results;
- };
-}
-
-function Sizzle( selector, context, results, seed ) {
- results = results || [];
- context = context || document;
- var match, elem, xml, m,
- nodeType = context.nodeType;
-
- if ( !selector || typeof selector !== "string" ) {
- return results;
- }
-
- if ( nodeType !== 1 && nodeType !== 9 ) {
- return [];
- }
-
- xml = isXML( context );
-
- if ( !xml && !seed ) {
- if ( (match = rquickExpr.exec( selector )) ) {
- // Speed-up: Sizzle("#ID")
- if ( (m = match[1]) ) {
- if ( nodeType === 9 ) {
- elem = context.getElementById( m );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- if ( elem && elem.parentNode ) {
- // Handle the case where IE, Opera, and Webkit return items
- // by name instead of ID
- if ( elem.id === m ) {
- results.push( elem );
- return results;
- }
- } else {
- return results;
- }
- } else {
- // Context is not a document
- if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
- contains( context, elem ) && elem.id === m ) {
- results.push( elem );
- return results;
- }
- }
-
- // Speed-up: Sizzle("TAG")
- } else if ( match[2] ) {
- push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
- return results;
-
- // Speed-up: Sizzle(".CLASS")
- } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
- push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
- return results;
- }
- }
- }
-
- // All others
- return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
-}
-
-Sizzle.matches = function( expr, elements ) {
- return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
- return Sizzle( expr, null, null, [ elem ] ).length > 0;
-};
-
-// Returns a function to use in pseudos for input types
-function createInputPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === type;
- };
-}
-
-// Returns a function to use in pseudos for buttons
-function createButtonPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return (name === "input" || name === "button") && elem.type === type;
- };
-}
-
-// Returns a function to use in pseudos for positionals
-function createPositionalPseudo( fn ) {
- return markFunction(function( argument ) {
- argument = +argument;
- return markFunction(function( seed, matches ) {
- var j,
- matchIndexes = fn( [], seed.length, argument ),
- i = matchIndexes.length;
-
- // Match elements found at the specified indexes
- while ( i-- ) {
- if ( seed[ (j = matchIndexes[i]) ] ) {
- seed[j] = !(matches[j] = seed[j]);
- }
- }
- });
- });
-}
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
- var node,
- ret = "",
- i = 0,
- nodeType = elem.nodeType;
-
- if ( nodeType ) {
- if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
- // Use textContent for elements
- // innerText usage removed for consistency of new lines (see #11153)
- if ( typeof elem.textContent === "string" ) {
- return elem.textContent;
- } else {
- // Traverse its children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- ret += getText( elem );
- }
- }
- } else if ( nodeType === 3 || nodeType === 4 ) {
- return elem.nodeValue;
- }
- // Do not include comment or processing instruction nodes
- } else {
-
- // If no nodeType, this is expected to be an array
- for ( ; (node = elem[i]); i++ ) {
- // Do not traverse comment nodes
- ret += getText( node );
- }
- }
- return ret;
-};
-
-isXML = Sizzle.isXML = function( elem ) {
- // documentElement is verified for cases where it doesn't yet exist
- // (such as loading iframes in IE - #4833)
- var documentElement = elem && (elem.ownerDocument || elem).documentElement;
- return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-// Element contains another
-contains = Sizzle.contains = docElem.contains ?
- function( a, b ) {
- var adown = a.nodeType === 9 ? a.documentElement : a,
- bup = b && b.parentNode;
- return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
- } :
- docElem.compareDocumentPosition ?
- function( a, b ) {
- return b && !!( a.compareDocumentPosition( b ) & 16 );
- } :
- function( a, b ) {
- while ( (b = b.parentNode) ) {
- if ( b === a ) {
- return true;
- }
- }
- return false;
- };
-
-Sizzle.attr = function( elem, name ) {
- var val,
- xml = isXML( elem );
-
- if ( !xml ) {
- name = name.toLowerCase();
- }
- if ( (val = Expr.attrHandle[ name ]) ) {
- return val( elem );
- }
- if ( xml || assertAttributes ) {
- return elem.getAttribute( name );
- }
- val = elem.getAttributeNode( name );
- return val ?
- typeof elem[ name ] === "boolean" ?
- elem[ name ] ? name : null :
- val.specified ? val.value : null :
- null;
-};
-
-Expr = Sizzle.selectors = {
-
- // Can be adjusted by the user
- cacheLength: 50,
-
- createPseudo: markFunction,
-
- match: matchExpr,
-
- // IE6/7 return a modified href
- attrHandle: assertHrefNotNormalized ?
- {} :
- {
- "href": function( elem ) {
- return elem.getAttribute( "href", 2 );
- },
- "type": function( elem ) {
- return elem.getAttribute("type");
- }
- },
-
- find: {
- "ID": assertGetIdNotName ?
- function( id, context, xml ) {
- if ( typeof context.getElementById !== strundefined && !xml ) {
- var m = context.getElementById( id );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- return m && m.parentNode ? [m] : [];
- }
- } :
- function( id, context, xml ) {
- if ( typeof context.getElementById !== strundefined && !xml ) {
- var m = context.getElementById( id );
-
- return m ?
- m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
- [m] :
- undefined :
- [];
- }
- },
-
- "TAG": assertTagNameNoComments ?
- function( tag, context ) {
- if ( typeof context.getElementsByTagName !== strundefined ) {
- return context.getElementsByTagName( tag );
- }
- } :
- function( tag, context ) {
- var results = context.getElementsByTagName( tag );
-
- // Filter out possible comments
- if ( tag === "*" ) {
- var elem,
- tmp = [],
- i = 0;
-
- for ( ; (elem = results[i]); i++ ) {
- if ( elem.nodeType === 1 ) {
- tmp.push( elem );
- }
- }
-
- return tmp;
- }
- return results;
- },
-
- "NAME": assertUsableName && function( tag, context ) {
- if ( typeof context.getElementsByName !== strundefined ) {
- return context.getElementsByName( name );
- }
- },
-
- "CLASS": assertUsableClassName && function( className, context, xml ) {
- if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
- return context.getElementsByClassName( className );
- }
- }
- },
-
- relative: {
- ">": { dir: "parentNode", first: true },
- " ": { dir: "parentNode" },
- "+": { dir: "previousSibling", first: true },
- "~": { dir: "previousSibling" }
- },
-
- preFilter: {
- "ATTR": function( match ) {
- match[1] = match[1].replace( rbackslash, "" );
-
- // Move the given value to match[3] whether quoted or unquoted
- match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
-
- if ( match[2] === "~=" ) {
- match[3] = " " + match[3] + " ";
- }
-
- return match.slice( 0, 4 );
- },
-
- "CHILD": function( match ) {
- /* matches from matchExpr["CHILD"]
- 1 type (only|nth|...)
- 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
- 3 xn-component of xn+y argument ([+-]?\d*n|)
- 4 sign of xn-component
- 5 x of xn-component
- 6 sign of y-component
- 7 y of y-component
- */
- match[1] = match[1].toLowerCase();
-
- if ( match[1] === "nth" ) {
- // nth-child requires argument
- if ( !match[2] ) {
- Sizzle.error( match[0] );
- }
-
- // numeric x and y parameters for Expr.filter.CHILD
- // remember that false/true cast respectively to 0/1
- match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
- match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
-
- // other types prohibit arguments
- } else if ( match[2] ) {
- Sizzle.error( match[0] );
- }
-
- return match;
- },
-
- "PSEUDO": function( match ) {
- var unquoted, excess;
- if ( matchExpr["CHILD"].test( match[0] ) ) {
- return null;
- }
-
- if ( match[3] ) {
- match[2] = match[3];
- } else if ( (unquoted = match[4]) ) {
- // Only check arguments that contain a pseudo
- if ( rpseudo.test(unquoted) &&
- // Get excess from tokenize (recursively)
- (excess = tokenize( unquoted, true )) &&
- // advance to the next closing parenthesis
- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
- // excess is a negative index
- unquoted = unquoted.slice( 0, excess );
- match[0] = match[0].slice( 0, excess );
- }
- match[2] = unquoted;
- }
-
- // Return only captures needed by the pseudo filter method (type and argument)
- return match.slice( 0, 3 );
- }
- },
-
- filter: {
- "ID": assertGetIdNotName ?
- function( id ) {
- id = id.replace( rbackslash, "" );
- return function( elem ) {
- return elem.getAttribute("id") === id;
- };
- } :
- function( id ) {
- id = id.replace( rbackslash, "" );
- return function( elem ) {
- var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
- return node && node.value === id;
- };
- },
-
- "TAG": function( nodeName ) {
- if ( nodeName === "*" ) {
- return function() { return true; };
- }
- nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
-
- return function( elem ) {
- return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
- };
- },
-
- "CLASS": function( className ) {
- var pattern = classCache[ expando ][ className + " " ];
-
- return pattern ||
- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
- classCache( className, function( elem ) {
- return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
- });
- },
-
- "ATTR": function( name, operator, check ) {
- return function( elem ) {
- var result = Sizzle.attr( elem, name );
-
- if ( result == null ) {
- return operator === "!=";
- }
- if ( !operator ) {
- return true;
- }
-
- result += "";
-
- return operator === "=" ? result === check :
- operator === "!=" ? result !== check :
- operator === "^=" ? check && result.indexOf( check ) === 0 :
- operator === "*=" ? check && result.indexOf( check ) > -1 :
- operator === "$=" ? check && result.substr( result.length - check.length ) === check :
- operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
- operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
- false;
- };
- },
-
- "CHILD": function( type, argument, first, last ) {
-
- if ( type === "nth" ) {
- return function( elem ) {
- var node, diff,
- parent = elem.parentNode;
-
- if ( first === 1 && last === 0 ) {
- return true;
- }
-
- if ( parent ) {
- diff = 0;
- for ( node = parent.firstChild; node; node = node.nextSibling ) {
- if ( node.nodeType === 1 ) {
- diff++;
- if ( elem === node ) {
- break;
- }
- }
- }
- }
-
- // Incorporate the offset (or cast to NaN), then check against cycle size
- diff -= last;
- return diff === first || ( diff % first === 0 && diff / first >= 0 );
- };
- }
-
- return function( elem ) {
- var node = elem;
-
- switch ( type ) {
- case "only":
- case "first":
- while ( (node = node.previousSibling) ) {
- if ( node.nodeType === 1 ) {
- return false;
- }
- }
-
- if ( type === "first" ) {
- return true;
- }
-
- node = elem;
-
- /* falls through */
- case "last":
- while ( (node = node.nextSibling) ) {
- if ( node.nodeType === 1 ) {
- return false;
- }
- }
-
- return true;
- }
- };
- },
-
- "PSEUDO": function( pseudo, argument ) {
- // pseudo-class names are case-insensitive
- // http://www.w3.org/TR/selectors/#pseudo-classes
- // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
- // Remember that setFilters inherits from pseudos
- var args,
- fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
- Sizzle.error( "unsupported pseudo: " + pseudo );
-
- // The user may use createPseudo to indicate that
- // arguments are needed to create the filter function
- // just as Sizzle does
- if ( fn[ expando ] ) {
- return fn( argument );
- }
-
- // But maintain support for old signatures
- if ( fn.length > 1 ) {
- args = [ pseudo, pseudo, "", argument ];
- return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
- markFunction(function( seed, matches ) {
- var idx,
- matched = fn( seed, argument ),
- i = matched.length;
- while ( i-- ) {
- idx = indexOf.call( seed, matched[i] );
- seed[ idx ] = !( matches[ idx ] = matched[i] );
- }
- }) :
- function( elem ) {
- return fn( elem, 0, args );
- };
- }
-
- return fn;
- }
- },
-
- pseudos: {
- "not": markFunction(function( selector ) {
- // Trim the selector passed to compile
- // to avoid treating leading and trailing
- // spaces as combinators
- var input = [],
- results = [],
- matcher = compile( selector.replace( rtrim, "$1" ) );
-
- return matcher[ expando ] ?
- markFunction(function( seed, matches, context, xml ) {
- var elem,
- unmatched = matcher( seed, null, xml, [] ),
- i = seed.length;
-
- // Match elements unmatched by `matcher`
- while ( i-- ) {
- if ( (elem = unmatched[i]) ) {
- seed[i] = !(matches[i] = elem);
- }
- }
- }) :
- function( elem, context, xml ) {
- input[0] = elem;
- matcher( input, null, xml, results );
- return !results.pop();
- };
- }),
-
- "has": markFunction(function( selector ) {
- return function( elem ) {
- return Sizzle( selector, elem ).length > 0;
- };
- }),
-
- "contains": markFunction(function( text ) {
- return function( elem ) {
- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
- };
- }),
-
- "enabled": function( elem ) {
- return elem.disabled === false;
- },
-
- "disabled": function( elem ) {
- return elem.disabled === true;
- },
-
- "checked": function( elem ) {
- // In CSS3, :checked should return both checked and selected elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- var nodeName = elem.nodeName.toLowerCase();
- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
- },
-
- "selected": function( elem ) {
- // Accessing this property makes selected-by-default
- // options in Safari work properly
- if ( elem.parentNode ) {
- elem.parentNode.selectedIndex;
- }
-
- return elem.selected === true;
- },
-
- "parent": function( elem ) {
- return !Expr.pseudos["empty"]( elem );
- },
-
- "empty": function( elem ) {
- // http://www.w3.org/TR/selectors/#empty-pseudo
- // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
- // not comment, processing instructions, or others
- // Thanks to Diego Perini for the nodeName shortcut
- // Greater than "@" means alpha characters (specifically not starting with "#" or "?")
- var nodeType;
- elem = elem.firstChild;
- while ( elem ) {
- if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
- return false;
- }
- elem = elem.nextSibling;
- }
- return true;
- },
-
- "header": function( elem ) {
- return rheader.test( elem.nodeName );
- },
-
- "text": function( elem ) {
- var type, attr;
- // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
- // use getAttribute instead to test this case
- return elem.nodeName.toLowerCase() === "input" &&
- (type = elem.type) === "text" &&
- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
- },
-
- // Input types
- "radio": createInputPseudo("radio"),
- "checkbox": createInputPseudo("checkbox"),
- "file": createInputPseudo("file"),
- "password": createInputPseudo("password"),
- "image": createInputPseudo("image"),
-
- "submit": createButtonPseudo("submit"),
- "reset": createButtonPseudo("reset"),
-
- "button": function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === "button" || name === "button";
- },
-
- "input": function( elem ) {
- return rinputs.test( elem.nodeName );
- },
-
- "focus": function( elem ) {
- var doc = elem.ownerDocument;
- return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
- },
-
- "active": function( elem ) {
- return elem === elem.ownerDocument.activeElement;
- },
-
- // Positional types
- "first": createPositionalPseudo(function() {
- return [ 0 ];
- }),
-
- "last": createPositionalPseudo(function( matchIndexes, length ) {
- return [ length - 1 ];
- }),
-
- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
- return [ argument < 0 ? argument + length : argument ];
- }),
-
- "even": createPositionalPseudo(function( matchIndexes, length ) {
- for ( var i = 0; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "odd": createPositionalPseudo(function( matchIndexes, length ) {
- for ( var i = 1; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- })
- }
-};
-
-function siblingCheck( a, b ) {
-
- if ( a && b ) {
- var cur = a.nextSibling;
-
- while ( cur ) {
- if ( cur === b ) {
- return -1;
- }
-
- cur = cur.nextSibling;
- }
- }
-
- return a ? 1 : -1;
-}
-
-sortOrder = docElem.compareDocumentPosition ?
- function( a, b ) {
- var compare, parent;
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- if ( a.compareDocumentPosition && b.compareDocumentPosition ) {
- if ( (compare = a.compareDocumentPosition( b )) & 1 || (( parent = a.parentNode ) && parent.nodeType === 11) ) {
- if ( a === document || contains(document, a) ) {
- return -1;
- }
- if ( b === document || contains(document, b) ) {
- return 1;
- }
- return 0;
- }
- return compare & 4 ? -1 : 1;
- }
-
- return a.compareDocumentPosition ? -1 : 1;
- } :
- function( a, b ) {
- // The nodes are identical, we can exit early
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
-
- // Fallback to using sourceIndex (in IE) if it's available on both nodes
- } else if ( a.sourceIndex && b.sourceIndex ) {
- return ( ~b.sourceIndex || ( MAX_NEGATIVE ) ) - ( contains( document, a ) && ~a.sourceIndex || ( MAX_NEGATIVE ) );
- }
-
- var i = 0,
- ap = [ a ],
- bp = [ b ],
- aup = a.parentNode,
- bup = b.parentNode,
- cur = aup;
-
- // If no parents were found then the nodes are disconnected
- if ( a === document ) {
- return -1;
-
- } else if ( b === document ) {
- return 1;
-
- } else if ( !aup && !bup ) {
- return 0;
-
- } else if ( !bup ) {
- return -1;
-
- } else if ( !aup ) {
- return 1;
-
- // If the nodes are siblings (or identical) we can do a quick check
- } else if ( aup === bup ) {
- return siblingCheck( a, b );
- }
-
- // Otherwise they're somewhere else in the tree so we need
- // to build up a full list of the parentNodes for comparison
- while ( cur ) {
- ap.unshift( cur );
- cur = cur.parentNode;
- }
-
- cur = bup;
-
- while ( cur ) {
- bp.unshift( cur );
- cur = cur.parentNode;
- }
-
- // Walk down the tree looking for a discrepancy
- while ( ap[i] === bp[i] ) {
- i++;
- }
-
- // Prefer our document
- if ( i === 0 ) {
- if ( ap[0] === document || contains(document, ap[0]) ) {
- return -1;
- }
- if ( bp[0] === document || contains(document, bp[0]) ) {
- return 1;
- }
- return 0;
- }
-
- // We ended someplace up the tree so do a sibling check
- return siblingCheck( ap[i], bp[i] );
- };
-
-// Always assume the presence of duplicates if sort doesn't
-// pass them to our comparison function (as in Google Chrome).
-[0, 0].sort( sortOrder );
-baseHasDuplicate = !hasDuplicate;
-
-// Document sorting and removing duplicates
-Sizzle.uniqueSort = function( results ) {
- var elem,
- duplicates = [],
- i = 1,
- j = 0;
-
- hasDuplicate = baseHasDuplicate;
- results.sort( sortOrder );
-
- if ( hasDuplicate ) {
- for ( ; (elem = results[i]); i++ ) {
- if ( elem === results[ i - 1 ] ) {
- j = duplicates.push( i );
- }
- }
- while ( j-- ) {
- results.splice( duplicates[ j ], 1 );
- }
- }
-
- return results;
-};
-
-Sizzle.error = function( msg ) {
- throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-function tokenize( selector, parseOnly ) {
- var matched, match, tokens, type,
- soFar, groups, preFilters,
- cached = tokenCache[ expando ][ selector + " " ];
-
- if ( cached ) {
- return parseOnly ? 0 : cached.slice( 0 );
- }
-
- soFar = selector;
- groups = [];
- preFilters = Expr.preFilter;
-
- while ( soFar ) {
-
- // Comma and first run
- if ( !matched || (match = rcomma.exec( soFar )) ) {
- if ( match ) {
- // Don't consume trailing commas as valid
- soFar = soFar.slice( match[0].length ) || soFar;
- }
- groups.push( tokens = [] );
- }
-
- matched = false;
-
- // Combinators
- if ( (match = rcombinators.exec( soFar )) ) {
- tokens.push( matched = new Token( match.shift() ) );
- soFar = soFar.slice( matched.length );
-
- // Cast descendant combinators to space
- matched.type = match[0].replace( rtrim, " " );
- }
-
- // Filters
- for ( type in Expr.filter ) {
- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
- (match = preFilters[ type ]( match ))) ) {
-
- tokens.push( matched = new Token( match.shift() ) );
- soFar = soFar.slice( matched.length );
- matched.type = type;
- matched.matches = match;
- }
- }
-
- if ( !matched ) {
- break;
- }
- }
-
- // Return the length of the invalid excess
- // if we're just parsing
- // Otherwise, throw an error or return tokens
- return parseOnly ?
- soFar.length :
- soFar ?
- Sizzle.error( selector ) :
- // Cache the tokens
- tokenCache( selector, groups ).slice( 0 );
-}
-
-function addCombinator( matcher, combinator, base ) {
- var dir = combinator.dir,
- checkNonElements = base && combinator.dir === "parentNode",
- doneName = done++;
-
- return combinator.first ?
- // Check against closest ancestor/preceding element
- function( elem, context, xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( checkNonElements || elem.nodeType === 1 ) {
- return matcher( elem, context, xml );
- }
- }
- } :
-
- // Check against all ancestor/preceding elements
- function( elem, context, xml ) {
- // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
- if ( !xml ) {
- var cache,
- dirkey = dirruns + " " + doneName + " ",
- cachedkey = dirkey + cachedruns;
- while ( (elem = elem[ dir ]) ) {
- if ( checkNonElements || elem.nodeType === 1 ) {
- if ( (cache = elem[ expando ]) === cachedkey ) {
- return elem.sizset;
- } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
- if ( elem.sizset ) {
- return elem;
- }
- } else {
- elem[ expando ] = cachedkey;
- if ( matcher( elem, context, xml ) ) {
- elem.sizset = true;
- return elem;
- }
- elem.sizset = false;
- }
- }
- }
- } else {
- while ( (elem = elem[ dir ]) ) {
- if ( checkNonElements || elem.nodeType === 1 ) {
- if ( matcher( elem, context, xml ) ) {
- return elem;
- }
- }
- }
- }
- };
-}
-
-function elementMatcher( matchers ) {
- return matchers.length > 1 ?
- function( elem, context, xml ) {
- var i = matchers.length;
- while ( i-- ) {
- if ( !matchers[i]( elem, context, xml ) ) {
- return false;
- }
- }
- return true;
- } :
- matchers[0];
-}
-
-function condense( unmatched, map, filter, context, xml ) {
- var elem,
- newUnmatched = [],
- i = 0,
- len = unmatched.length,
- mapped = map != null;
-
- for ( ; i < len; i++ ) {
- if ( (elem = unmatched[i]) ) {
- if ( !filter || filter( elem, context, xml ) ) {
- newUnmatched.push( elem );
- if ( mapped ) {
- map.push( i );
- }
- }
- }
- }
-
- return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
- if ( postFilter && !postFilter[ expando ] ) {
- postFilter = setMatcher( postFilter );
- }
- if ( postFinder && !postFinder[ expando ] ) {
- postFinder = setMatcher( postFinder, postSelector );
- }
- return markFunction(function( seed, results, context, xml ) {
- var temp, i, elem,
- preMap = [],
- postMap = [],
- preexisting = results.length,
-
- // Get initial elements from seed or context
- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
- // Prefilter to get matcher input, preserving a map for seed-results synchronization
- matcherIn = preFilter && ( seed || !selector ) ?
- condense( elems, preMap, preFilter, context, xml ) :
- elems,
-
- matcherOut = matcher ?
- // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
- postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
- // ...intermediate processing is necessary
- [] :
-
- // ...otherwise use results directly
- results :
- matcherIn;
-
- // Find primary matches
- if ( matcher ) {
- matcher( matcherIn, matcherOut, context, xml );
- }
-
- // Apply postFilter
- if ( postFilter ) {
- temp = condense( matcherOut, postMap );
- postFilter( temp, [], context, xml );
-
- // Un-match failing elements by moving them back to matcherIn
- i = temp.length;
- while ( i-- ) {
- if ( (elem = temp[i]) ) {
- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
- }
- }
- }
-
- if ( seed ) {
- if ( postFinder || preFilter ) {
- if ( postFinder ) {
- // Get the final matcherOut by condensing this intermediate into postFinder contexts
- temp = [];
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) ) {
- // Restore matcherIn since elem is not yet a final match
- temp.push( (matcherIn[i] = elem) );
- }
- }
- postFinder( null, (matcherOut = []), temp, xml );
- }
-
- // Move matched elements from seed to results to keep them synchronized
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) &&
- (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
-
- seed[temp] = !(results[temp] = elem);
- }
- }
- }
-
- // Add elements to results, through postFinder if defined
- } else {
- matcherOut = condense(
- matcherOut === results ?
- matcherOut.splice( preexisting, matcherOut.length ) :
- matcherOut
- );
- if ( postFinder ) {
- postFinder( null, results, matcherOut, xml );
- } else {
- push.apply( results, matcherOut );
- }
- }
- });
-}
-
-function matcherFromTokens( tokens ) {
- var checkContext, matcher, j,
- len = tokens.length,
- leadingRelative = Expr.relative[ tokens[0].type ],
- implicitRelative = leadingRelative || Expr.relative[" "],
- i = leadingRelative ? 1 : 0,
-
- // The foundational matcher ensures that elements are reachable from top-level context(s)
- matchContext = addCombinator( function( elem ) {
- return elem === checkContext;
- }, implicitRelative, true ),
- matchAnyContext = addCombinator( function( elem ) {
- return indexOf.call( checkContext, elem ) > -1;
- }, implicitRelative, true ),
- matchers = [ function( elem, context, xml ) {
- return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
- (checkContext = context).nodeType ?
- matchContext( elem, context, xml ) :
- matchAnyContext( elem, context, xml ) );
- } ];
-
- for ( ; i < len; i++ ) {
- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
- matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
- } else {
- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
- // Return special upon seeing a positional matcher
- if ( matcher[ expando ] ) {
- // Find the next relative operator (if any) for proper handling
- j = ++i;
- for ( ; j < len; j++ ) {
- if ( Expr.relative[ tokens[j].type ] ) {
- break;
- }
- }
- return setMatcher(
- i > 1 && elementMatcher( matchers ),
- i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
- matcher,
- i < j && matcherFromTokens( tokens.slice( i, j ) ),
- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
- j < len && tokens.join("")
- );
- }
- matchers.push( matcher );
- }
- }
-
- return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
- // A counter to specify which element is currently being matched
- var matcherCachedRuns = 0,
- bySet = setMatchers.length > 0,
- byElement = elementMatchers.length > 0,
- superMatcher = function( seed, context, xml, results, expandContext ) {
- var elem, j, matcher,
- setMatched = [],
- matchedCount = 0,
- i = "0",
- unmatched = seed && [],
- outermost = expandContext != null,
- contextBackup = outermostContext,
- // We must always have either seed elements or context
- elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
- // Nested matchers should use non-integer dirruns
- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
-
- if ( outermost ) {
- outermostContext = context !== document && context;
- cachedruns = matcherCachedRuns;
- }
-
- // Add elements passing elementMatchers directly to results
- for ( ; (elem = elems[i]) != null; i++ ) {
- if ( byElement && elem ) {
- for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
- if ( matcher( elem, context, xml ) ) {
- results.push( elem );
- break;
- }
- }
- if ( outermost ) {
- dirruns = dirrunsUnique;
- cachedruns = ++matcherCachedRuns;
- }
- }
-
- // Track unmatched elements for set filters
- if ( bySet ) {
- // They will have gone through all possible matchers
- if ( (elem = !matcher && elem) ) {
- matchedCount--;
- }
-
- // Lengthen the array for every element, matched or not
- if ( seed ) {
- unmatched.push( elem );
- }
- }
- }
-
- // Apply set filters to unmatched elements
- // `i` starts as a string, so matchedCount would equal "00" if there are no elements
- matchedCount += i;
- if ( bySet && i !== matchedCount ) {
- for ( j = 0; (matcher = setMatchers[j]); j++ ) {
- matcher( unmatched, setMatched, context, xml );
- }
-
- if ( seed ) {
- // Reintegrate element matches to eliminate the need for sorting
- if ( matchedCount > 0 ) {
- while ( i-- ) {
- if ( !(unmatched[i] || setMatched[i]) ) {
- setMatched[i] = pop.call( results );
- }
- }
- }
-
- // Discard index placeholder values to get only actual matches
- setMatched = condense( setMatched );
- }
-
- // Add matches to results
- push.apply( results, setMatched );
-
- // Seedless set matches succeeding multiple successful matchers stipulate sorting
- if ( outermost && !seed && setMatched.length > 0 &&
- ( matchedCount + setMatchers.length ) > 1 ) {
-
- Sizzle.uniqueSort( results );
- }
- }
-
- // Override manipulation of globals by nested matchers
- if ( outermost ) {
- dirruns = dirrunsUnique;
- outermostContext = contextBackup;
- }
-
- return unmatched;
- };
-
- return bySet ?
- markFunction( superMatcher ) :
- superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
- var i,
- setMatchers = [],
- elementMatchers = [],
- cached = compilerCache[ expando ][ selector + " " ];
-
- if ( !cached ) {
- // Generate a function of recursive functions that can be used to check each element
- if ( !group ) {
- group = tokenize( selector );
- }
- i = group.length;
- while ( i-- ) {
- cached = matcherFromTokens( group[i] );
- if ( cached[ expando ] ) {
- setMatchers.push( cached );
- } else {
- elementMatchers.push( cached );
- }
- }
-
- // Cache the compiled function
- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
- }
- return cached;
-};
-
-function multipleContexts( selector, contexts, results ) {
- var i = 0,
- len = contexts.length;
- for ( ; i < len; i++ ) {
- Sizzle( selector, contexts[i], results );
- }
- return results;
-}
-
-function select( selector, context, results, seed, xml ) {
- var i, tokens, token, type, find,
- match = tokenize( selector );
-
- if ( !seed ) {
- // Try to minimize operations if there is only one group
- if ( match.length === 1 ) {
-
- // Take a shortcut and set the context if the root selector is an ID
- tokens = match[0] = match[0].slice( 0 );
- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
- context.nodeType === 9 && !xml &&
- Expr.relative[ tokens[1].type ] ) {
-
- context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
- if ( !context ) {
- return results;
- }
-
- selector = selector.slice( tokens.shift().length );
- }
-
- // Fetch a seed set for right-to-left matching
- for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
- token = tokens[i];
-
- // Abort if we hit a combinator
- if ( Expr.relative[ (type = token.type) ] ) {
- break;
- }
- if ( (find = Expr.find[ type ]) ) {
- // Search, expanding context for leading sibling combinators
- if ( (seed = find(
- token.matches[0].replace( rbackslash, "" ),
- rsibling.test( tokens[0].type ) && context.parentNode || context,
- xml
- )) ) {
-
- // If seed is empty or no tokens remain, we can return early
- tokens.splice( i, 1 );
- selector = seed.length && tokens.join("");
- if ( !selector ) {
- push.apply( results, slice.call( seed, 0 ) );
- return results;
- }
-
- break;
- }
- }
- }
- }
- }
-
- // Compile and execute a filtering function
- // Provide `match` to avoid retokenization if we modified the selector above
- compile( selector, match )(
- seed,
- context,
- xml,
- results,
- rsibling.test( selector )
- );
- return results;
-}
-
-if ( document.querySelectorAll ) {
- (function() {
- var disconnectedMatch,
- oldSelect = select,
- rescape = /'|\\/g,
- rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
-
- // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
- // A support test would require too much code (would include document ready)
- rbuggyQSA = [ ":focus" ],
-
- // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
- // A support test would require too much code (would include document ready)
- // just skip matchesSelector for :active
- rbuggyMatches = [ ":active" ],
- matches = docElem.matchesSelector ||
- docElem.mozMatchesSelector ||
- docElem.webkitMatchesSelector ||
- docElem.oMatchesSelector ||
- docElem.msMatchesSelector;
-
- // Build QSA regex
- // Regex strategy adopted from Diego Perini
- assert(function( div ) {
- // Select is set to empty string on purpose
- // This is to test IE's treatment of not explictly
- // setting a boolean content attribute,
- // since its presence should be enough
- // http://bugs.jquery.com/ticket/12359
- div.innerHTML = "<select><option selected=''></option></select>";
-
- // IE8 - Some boolean attributes are not treated correctly
- if ( !div.querySelectorAll("[selected]").length ) {
- rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
- }
-
- // Webkit/Opera - :checked should return selected option elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- // IE8 throws error here (do not put tests after this one)
- if ( !div.querySelectorAll(":checked").length ) {
- rbuggyQSA.push(":checked");
- }
- });
-
- assert(function( div ) {
-
- // Opera 10-12/IE9 - ^= $= *= and empty values
- // Should not select anything
- div.innerHTML = "<p test=''></p>";
- if ( div.querySelectorAll("[test^='']").length ) {
- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
- }
-
- // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
- // IE8 throws error here (do not put tests after this one)
- div.innerHTML = "<input type='hidden'/>";
- if ( !div.querySelectorAll(":enabled").length ) {
- rbuggyQSA.push(":enabled", ":disabled");
- }
- });
-
- // rbuggyQSA always contains :focus, so no need for a length check
- rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
-
- select = function( selector, context, results, seed, xml ) {
- // Only use querySelectorAll when not filtering,
- // when this is not xml,
- // and when no QSA bugs apply
- if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
- var groups, i,
- old = true,
- nid = expando,
- newContext = context,
- newSelector = context.nodeType === 9 && selector;
-
- // qSA works strangely on Element-rooted queries
- // We can work around this by specifying an extra ID on the root
- // and working up from there (Thanks to Andrew Dupont for the technique)
- // IE 8 doesn't work on object elements
- if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
- groups = tokenize( selector );
-
- if ( (old = context.getAttribute("id")) ) {
- nid = old.replace( rescape, "\\$&" );
- } else {
- context.setAttribute( "id", nid );
- }
- nid = "[id='" + nid + "'] ";
-
- i = groups.length;
- while ( i-- ) {
- groups[i] = nid + groups[i].join("");
- }
- newContext = rsibling.test( selector ) && context.parentNode || context;
- newSelector = groups.join(",");
- }
-
- if ( newSelector ) {
- try {
- push.apply( results, slice.call( newContext.querySelectorAll(
- newSelector
- ), 0 ) );
- return results;
- } catch(qsaError) {
- } finally {
- if ( !old ) {
- context.removeAttribute("id");
- }
- }
- }
- }
-
- return oldSelect( selector, context, results, seed, xml );
- };
-
- if ( matches ) {
- assert(function( div ) {
- // Check to see if it's possible to do matchesSelector
- // on a disconnected node (IE 9)
- disconnectedMatch = matches.call( div, "div" );
-
- // This should fail with an exception
- // Gecko does not error, returns false instead
- try {
- matches.call( div, "[test!='']:sizzle" );
- rbuggyMatches.push( "!=", pseudos );
- } catch ( e ) {}
- });
-
- // rbuggyMatches always contains :active and :focus, so no need for a length check
- rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
-
- Sizzle.matchesSelector = function( elem, expr ) {
- // Make sure that attribute selectors are quoted
- expr = expr.replace( rattributeQuotes, "='$1']" );
-
- // rbuggyMatches always contains :active, so no need for an existence check
- if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
- try {
- var ret = matches.call( elem, expr );
-
- // IE 9's matchesSelector returns false on disconnected nodes
- if ( ret || disconnectedMatch ||
- // As well, disconnected nodes are said to be in a document
- // fragment in IE 9
- elem.document && elem.document.nodeType !== 11 ) {
- return ret;
- }
- } catch(e) {}
- }
-
- return Sizzle( expr, null, null, [ elem ] ).length > 0;
- };
- }
- })();
-}
-
-// Deprecated
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Easy API for creating new setFilters
-function setFilters() {}
-Expr.filters = setFilters.prototype = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-// EXPOSE
-if ( typeof define === "function" && define.amd ) {
- define(function() { return Sizzle; });
-} else {
- window.Sizzle = Sizzle;
-}
-// EXPOSE
-
-})( window );
|
d36f376a8e13c69c3bd78b4d43f554b44b692ed1
|
elasticsearch
|
fix cluster state mapping informaton
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java
index dc9192c3566d4..75aa769ebcb68 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java
@@ -72,7 +72,7 @@ public class RestClusterStateAction extends BaseRestHandler {
builder.startObject("mappings");
for (Map.Entry<String, String> entry : indexMetaData.mappings().entrySet()) {
- builder.startObject("mapping").field("name", entry.getKey()).field("value", entry.getValue()).endObject();
+ builder.startObject(entry.getKey()).field("source", entry.getValue()).endObject();
}
builder.endObject();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.